text:
Q: programmatically logout a "specific" user Is it possible in Asp.NET MVC to proframmatically logout a user? I am aware that you can use:
FormsService.SignOut();

But this refers to the context of the webpage making the request.  I'm trying to prevent a user logging in twice.  So if I call:
MembershipUser membershipUser = Membership.GetUser(userName);
if (membershipUser.IsOnline == true)
{
    //  log this user out so we can log them in again
    FormsService.SignOut();
}

Calling FormsService.SignOut(); has no bearing on the context of the user say, with another webbrowser who is logged in already?

A: One common method to accomplish this goal is to, on each page load, check whether the current user needs to be signed out.
if (User.Identity.IsAuthenticated && UserNeedsToSignOut())
{
    FormsAuthentication.SignOut(); // kill the authentication cookie:
    Response.Redirect("~/default.aspx"); // make sure you redirect in order for the cookie to not be sent on subsequent request
}

You may be concerned that this method will be too slow,

"Why do I have to call this damned function each page load? It probably hits the database each time!"

It doesn't need to be slow. You may cache a list of users that should not be signed in at any given time. If their username is in that cache, then the sign out code will be triggered next time they access a page.

A: Take a look at this blog How to allow only one user per account in ASP.Net


text:
Q: How do I cd into a hard drive with a GPT partition table using a raspberry pi running raspbian? My ubuntu laptop has died, and so I am attempting to recover some files off the hard drive using a raspberry pi. I have removed my laptop's hard drive and attached it to my raspberry pi via usb. I am now trying to figure out how I can cd into it to view my files.
online, various forums say to use sudo fdisk -l but this apparently cannot read GPT. When I run the command, a message says "The util fdisk doesn't support GPT. Use GNU Parted."
Gparted is a graphical application. I would like a way to do this using the terminal alone.
I do not wish to modify the hard drive, only read from it.
How can I do this and access my files?
Update: So I figured out sudo parted -l outputs
Model: ST500LT0 32-1E9142 (scsi)
Disk /dev/sda: 500GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt

Number  Start   End    Size    File system     Name  Flags
 1      1049kB  538MB  537MB   fat32                 boot
 2      538MB   492GB  491GB   ext4
 3      492GB   500GB  8483MB  linux-swap(v1)

I want to cd into the 492GB partition. I tried sudo mount /dev/sda2 /mnt but that gives me
mount: wrong fs type, bad option, bad superblock on /dev/sda2,
missing codepage or helper program, or other error

Any ideas as to what I'm doing wrong?

A: Using parted is fairly straightforward. The man page doesn't give examples but it's quite readable. Really. Here's a safe example for you:
parted /dev/sdb unit MiB print

Once you have this information you still need to mount the various filesystems.
mkdir /mnt/part              # Adjust to suit
mount /dev/sdb1 /mnt/part    # You might need /dev/sdb2, /dev/sdb3, etc.
cd /mnt/part
...
cd
umount /mnt/part

These will be read/write mounts. If you want to mount read-only then include the -r flag - mount -r /dev/sdb1 /mnt/part, etc.

A: You can use sgdisk utility, sgdisk supports GPT.
To list the partition table
  sgdisk -p /dev/<dev-node>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flutter responsive design for container height and width, fontsize of text, padding, margin, etc What is the best approach/ best practice to design a responsive Flutter app? Like the width and height of a container, fontSize of a text that is responsive to different size of device.
I have tried like
Size size = MediaQuery.of(context).size;
Text(
    "Dummy Text",
    style: TextStyle(fontSize: size.height * 0.03),
)

but it just doesn't seem right.

A: It is very broad question, i'll try to answer based on my knowledge.
There are several ways in which you can achieve responsiveness.
1.Extended, Flexible,AspectRatio

By using screen-responsive layout widgets like Extended, Flexible, and AspectRatio. Your UI can adapt to various screen sizes and orientations with the aid of these widgets.

2.MediaQuery

To determine the device screen size and modify your UI components accordingly, you can use MediaQuery. To obtain the device's screen dimensions, you can use MediaQuery.of(context).size.width or MediaQuery.of(context).size.height.

3.LayoutBuilder

To modify your UI elements in accordance with the limitations offered by its parent widget, you can use the LayoutBuilder widget. It is based on the principle as its restrictions change, this widget rebuilds its child widget.

4.FittedBox

To automatically resize your UI components to fit within their parent container, you can take aid of FittedBox widget.

5.AspectRatio

To specify a certain aspect ratio that the widget should have on the screen, use the AspectRatio widget.

Example:
Text(
  'Dummy Text',
  style: TextStyle(
      fontSize: MediaQuery.of(context).size.width * 0.05,
      fontWeight: FontWeight.bold,
   ),
);

In this example, the fontSize is set to 5% of the width of the device's screen.


text:
Q: Regression through the Origin on the Galton dataset using manipulator to create a slider for the beta R Programming I am very new to R. I am trying to run a Regression through the Origin on the Galton dataset using manipulator to create a slider for the beta.
Below is the code, but am getting multiple errors. What am I doing wrong? I am running it in RStudio 3.2.5 on a Windows 2016 PC.
Both the Code and Error message are below
The Code
    library(UsingR)
    library(shiny)
    library(ggplot2)
    data(galton)
shinyUI(fluidPage(                # Application title

  titlePanel("Now we re-create the scatterplot with the linear line that that is forced to go through the mean of the parent's hight and mean of the child's height."),
  sidebarLayout(
    sidebarPanel(
      sliderInput("beta",
                  "Beta:",
                  min = 0.6,
                  max = 1.2,
                  step = .02,
                  value = 0.6)                                        ),

    # Show a plot of the generated distribution

    mainPanel(

      plotOutput("myPlot",height = "700px", width = "700")
    )
  )
))

output$myPlot <- renderPlot({        y <- galton$child - mean(galton$child)
x <- galton$parent - mean(galton$parent)
freqData <- as.data.frame(table(x, y))
names(freqData) <- c("child", "parent", "freq")
freqData$child <- as.numeric(as.character(freqData$child))
freqData$parent <- as.numeric(as.character(freqData$parent))

# note couldn't get filter to work so changed it to subset below

g <- ggplot(subset(freqData,freq > 0), aes(x = parent, y = child))
g <- g  + scale_size(range = c(2, 20), guide = "none" )
g <- g + geom_point(colour="grey50", aes(size = freq+20, show_guide = FALSE))
g <- g + geom_point(aes(colour=freq, size = freq))
g <- g + scale_colour_gradient(low = "lightblue", high="white")                         g <- g + geom_abline(intercept = 0, slope = input$beta, size = 3)
mse <- mean( (y - input$beta * x) ^2 )
g <- g + ggtitle(paste("beta = ", input$beta, "mse = ", round(mse, 3)))    g       })

```
This is my error message
R version 3.2.5 (2016-04-14) -- "Very, Very Secure Dishes"
Copyright (C) 2016 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

>
>
> library(UsingR)
Loading required package: MASS
Loading required package: HistData
Loading required package: Hmisc
Loading required package: lattice
Loading required package: survival
Loading required package: Formula
Loading required package: ggplot2

Attaching package: 'Hmisc'

The following objects are masked from 'package:base':

    format.pval, round.POSIXt, trunc.POSIXt, units

Attaching package: 'UsingR'

The following object is masked from 'package:survival':

    cancer

> library(shiny)
> library(ggplot2)
> data(galton)
>
>
> shinyUI(fluidPage(                # Application title
+
+   titlePanel("Now we re-create the scatterplot with the linear line that that is forced to go through the mean of the parent's hight and mean of the child's height."),
+   sidebarLayout(
+     sidebarPanel(
+       sliderInput("beta",
+                   "Beta:",
+                   min = 0.6,
+                   max = 1.2,
+                   step = .02,
+                   value = 0.6)                                        ),
+
+     # Show a plot of the generated distribution
+
+     mainPanel(
+
+       plotOutput("myPlot",height = "700px", width = "700")
+     )
+   )
+ ))
<div class="container-fluid">
  <h2>Now we re-create the scatterplot with the linear line that that is forced to go through the mean of the parents hight and mean of the childs height.</h2>
  <div class="row">
    <div class="col-sm-4">
      <form class="well">
        <div class="form-group shiny-input-container">
          <label class="control-label" for="beta">Beta:</label>
          <input class="js-range-slider" id="beta" data-min="0.6" data-max="1.2" data-from="0.6" data-step="0.02" data-grid="true" data-grid-num="10" data-grid-snap="false" data-prettify-separator="," data-keyboard="true" data-keyboard-step="3.33333333333333" data-drag-interval="true" data-data-type="number"/>
        </div>
      </form>
    </div>
    <div class="col-sm-8">
      <div id="myPlot" class="shiny-plot-output" style="width: 700px ; height: 700px"></div>
    </div>
  </div>
</div>
>
>
> output$myPlot <- renderPlot({        y <- galton$child - mean(galton$child)
+ x <- galton$parent - mean(galton$parent)
+ freqData <- as.data.frame(table(x, y))
+ names(freqData) <- c("child", "parent", "freq")
+ freqData$child <- as.numeric(as.character(freqData$child))
+ freqData$parent <- as.numeric(as.character(freqData$parent))
+
+ # note couldn't get filter to work so changed it to subset below
+
+ g <- ggplot(subset(freqData,freq > 0), aes(x = parent, y = child))
+ g <- g  + scale_size(range = c(2, 20), guide = "none" )
+ g <- g + geom_point(colour="grey50", aes(size = freq+20, show_guide = FALSE))
+ g <- g + geom_point(aes(colour=freq, size = freq))
+ g <- g + scale_colour_gradient(low = "lightblue", high="white")                         g <- g + geom_abline(intercept = 0, slope = input$beta, size = 3)
Error: unexpected symbol in:
"g <- g + geom_point(aes(colour=freq, size = freq))
g <- g + scale_colour_gradient(low = "lightblue", high="white")                         g"
> mse <- mean( (y - input$beta * x) ^2 )
Error in mean((y - input$beta * x)^2) : object 'y' not found
> g <- g + ggtitle(paste("beta = ", input$beta, "mse = ", round(mse, 3)))    g       })
Error: unexpected symbol in "g <- g + ggtitle(paste("beta = ", input$beta, "mse = ", round(mse, 3)))    g"
>
> ```

Error: attempt to use zero-length variable name

A: On this line:

g <- g + scale_colour_gradient(low = "lightblue", high="white")                         g <- g + geom_abline(intercept = 0, slope = input$beta, size = 3)

there are two commands on the same line. Each must be on their line (or ; separated).


text:
Q: AKKA Actor and DataBase Operation I'm trying to figure out how to best handle database operations while using an actor system. indeed database operations are blocking while we try not to block in AKKA.
I red in the main doc that one way to handle that was to create one a pool of actors behind a router, potentially on a separated executionContext, that would handle database access.
Therefore i have the following questions:
1 - Does the databaseActors keep the connection open the all time?
2 - How does it work together with connection Pooling as offered by many database?
3 - Shall we combine both, and have the DatabaseActors request a new connection from the pool each time they are solicited. If not, isn't it keeping a connection open at all time a bad thing to do?
4 - Can someone explain to me the subtle thing that make it an approach that avoid thread starvation. For instance using Play or spray, the handling of a request is an asynchronous task, however if that task need a database access and we send an ask to the DatabaseActor, does the block on the database Actor (if it occur) do not induce, a block in the asynchronous task, leading to possible thread starvation ?
5 -  Is it 100% sure the DB ACID property ensures the safety of the multiple read and write and therefore happens before relationship.
6 - I'm using the semantic database also called triple store and make heavy using of semantic reasoning capability during my request. I also perform a lot of write access, any advise, concerning tuning parameters of pooling and actor numbers or dedicated execution context?
Best,
M

A: This blog post has some really good points why not to use Actor per DB connection.
In particular, it means you need to manage the concurrency level instead of letting the native connection pool to handle it for you.
It also may mislead you to think your code runs in parallel while in fact your code runs serially.

A:
1 - Does the databaseActors keep the connection open the all time?

Akka actors are stateful i.e., you can safely store state (in this case DB connection) inside an actor. You can either write you own connection management logic or use the one that is provided by the your database driver.

2 - How does it work together with connection Pooling as offered by many database?
3 - Shall we combine both, and have the DatabaseActors request a new connection from the pool each time they are solicited. If not, isn't it keeping a connection open at all time a bad thing to do?

You can combine both. Have an actor for each connection in the pool. Why do you think having a connection alive is a bad thing? Isn't the whole point of having a connection pool is to reuse resources (connections) and not pay the price of creating/destroying them every time.

4 - Can someone explain to me the subtle thing that make it an approach that avoid thread starvation. For instance using Play or spray, the handling of a request is an asynchronous task, however if that task need a database access and we send an ask to the DatabaseActor, does the block on the database Actor (if it occur) do not induce, a block in the asynchronous task, leading to possible thread starvation ?

If your database driver is blocking then you eventually have to block also. The recommended practice is to execute this blocking piece of code in a separate execution context/thread pool. Or if you have the option choose a datastore that has a reactive database driver (e.g., ReactiveMongo for MongoDB) which is completely async and non-blocking.

5 - Is it 100% sure the DB ACID property ensures the safety of the multiple read and write and therefore happens before relationship.

I don't understand what you mean by this.

6 - I'm using the semantic database also called triple store and make heavy using of semantic reasoning capability during my request. I also perform a lot of write access, any advise, concerning tuning parameters of pooling and actor numbers or dedicated execution context?

You should definitely use a different execution context. The turning of parameters really depends on your hardware configuration and other specifics of your software (type of database, remote db vs embedded db, requests/second etc).
I don't think there is a one size fits all when it comes to Akka dispatchers. It's more of an art. My only recommendation is that make sure you are not blocking anywhere in your code.


text:
Q: ExtJS5 How to let keymap call viewController function? I was wondering how to call a controller function from a keymaps in extjs 5?
The following code in the view is working to bind the keys to a an anonymous function, however not to a controller function. The function is also called by the button, and is working. How do I set the scope correctly that it is calling the controller function?
Ext.define("MyApp.view.users.List",{
    extend: 'Ext.grid.Panel',
    alias: 'widget.usersList',
    controller: 'users-list',
    listeners: {
        scope: 'controller',
        afterrender: function(window, options) {
            this.keyNav = new Ext.util.KeyMap ({
                target:window.el,
                binding: [
                    {key:"s", ctrl:true, fn: function(){alert("hallo shortkey");}},
                    {key:"c", ctrl:true, fn: "newUserFn"},
                ],
                scope:'controller'
            });
        }
    },
    tbar: [
        {
            itemId: 'users-list-btn-new',
            iconCls: 'icon-add',
            text: 'New User',
            handler: 'newUserFn'
        }
    ]
});

A: I had similar troubles with scope on key press events. I'm not using a KeyMap as you are but the event logic is still relevant.
The following assumes a controller with method "saveNewComponent" that you want to call. You must fire the view event "callSave" which is being listened to in the view to correctly forward to the controller.
Ext.define('teams.view.component.FormPanel', {
    extend: 'Ext.form.Panel',
    controller: "FormPanelController",
    listeners: {
        callSave: "saveNewComponent"
    },
    beforeShow: function(){
        var me = this;
        me.body.dom.addEventListener("keydown", Ext.bind(onKeyDown, this), false);
        function onKeyDown(e) {
            //Listen for Ctrl+S
            if (e.ctrlKey && e.which === 83){
                e.preventDefault();
                me.fireEvent("callSave");
                return false;
            }
        }
    },
    ....
}

I tried many ways of achieving this, this this solution was the only one that had the correct context when actually inside the controller (ie this var was correct)


text:
Q: Python equivalent of the R operator "%in%" What is the python equivalent of this in operator?  I am trying to filter down a pandas database by having rows only remain if a column in the row has a value found in my list.
I tried using any() and am having immense difficulty with this.

A: Pandas comparison with R docs are here.
s <- 0:4
s %in% c(2,4)

The isin method is similar to R %in% operator:
In [13]: s = pd.Series(np.arange(5),dtype=np.float32)

In [14]: s.isin([2, 4])
Out[14]:
0    False
1    False
2     True
3    False
4     True
dtype: bool

A: FWIW: without having to call pandas, here's the answer using a for loop and list compression in pure python
x = [2, 3, 5]
y = [1, 2, 3]

# for loop
for i in x: [].append(i in y)

Out: [True, True, False]

# list comprehension
[i in y for i in x]

Out: [True, True, False]

A: If you want to use only numpy without panads (like a use case I had) then you can:
import numpy as np

x = np.array([1, 2, 3, 10])
y = np.array([10, 11, 2])
np.isin(y, x)

This is equivalent to:
c(10, 11, 2) %in% c(1, 2, 3, 10)

Note that the last line will work only for numpy >= 1.13.0, for older versions you'll need to use np.in1d.

A: As others indicate, in operator of base Python works well.
myList = ["a00", "b000", "c0"]

"a00" in myList
# True

"a" in myList
# False


text:
Q: Mongoose Auth Error: command find requires authentication. But I did I'm trying to find a document I know exists because I can see it in the admin console thanks to mongo-express... however when I use Model.findOne( it vomits the below error message. WHAT am I doing wrong? ( the hostname 'mongo' is my docker container, and it connects just fine, I can see it in the logs )
This my code:
// This all works because the following events show success, and no error.
// So I know it's authing correctly on initial connection
-dbConnect.js-
"user strict"

import mongoose from "mongoose"

const connection = mongoose.createConnection(
"mongodb://mongo:27017/dbName?authSource=admin", {
              useNewUrlParser: true,
              user: process.env.user,
              pass: process.env.pass,
              keepAlive: true,
            })
connection.on( "connected", () => {
  console.log( "MONGOOSE: connected" )
})

connection.on( "close", () => {
  console.log( "MONGOOSE: connection close" )
})

connection.on( "error", error => {
  console.log( "MONGOOSE: connection error", error )
})

export default connection

*

*

-models/auth.js-
"use strict"

import mongoose from "mongoose"
import connection from "../dbConnect"

const xSchema = new mongoose.Schema(
  {
    id    : String,
    user  : String,
    pass  : String
  },
  { collection: "x" }
)
export const X = connection.model( "X", xSchema )

*

*

-controllers/auth.js-
import { X } from "../models/auth"
//Promise wrapper
X.findOne( { id: incomingId }, ( error, x ) => {
  //handler
})

And I end up with this error
MongoError: command find requires authentication
    at Connection.<anonymous> (/usr/src/app/node_modules/mongodb-core/lib/connection/pool.js:443:61)
    at Connection.emit (events.js:189:13)
    at Connection.EventEmitter.emit (domain.js:441:20)
    at processMessage (/usr/src/app/node_modules/mongodb-core/lib/connection/connection.js:364:10)
    at Socket.<anonymous> (/usr/src/app/node_modules/mongodb-core/lib/connection/connection.js:533:15)
    at Socket.emit (events.js:189:13)
    at Socket.EventEmitter.emit (domain.js:441:20)
    at addChunk (_stream_readable.js:284:12)
    at readableAddChunk (_stream_readable.js:265:11)
    at Socket.Readable.push (_stream_readable.js:220:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)

A: Answer was simple and stupid. Everything above is correct... leave for the environment variables being undefined.
Apparently mongo lets you connect without being authorized, you just can't do anything. Filling those env vars correctly everything moved along perfectly.


text:
Q: using intentservice to handle upload and update UI I've read the example for a Local Service here several times: http://developer.android.com/reference/android/app/Service.html#RemoteMessengerServiceSample.
I am trying to upload something in a thread spawned by a Service so that the app is usable. Before the upload starts I want to show a ProgressBar in every custom title bar (custom title bar is already implemented) throughout the app until the upload finishes, then I want to remove the ProgressBar. How can this be achieved using a IntentService?


text:
Q: Can a servlet truly access jars in Tomcat's lib dir? Background first:

*

*Tomcat 6.0 on WindowsXP & OpenSUSE SLED 11.0 (same results on both platforms)

*Oracle JDK v6

*Spring 3.0

*Javolution 5.5.1
I've got a strange problem with a jar (javolution-5.5.1.jar) that my app is using.  I've had this jar in WEB-INF/lib for some time now without any problems.  We determined that this jar really needs to be in Tomcat's lib dir instead of our app's lib dir because it is shared across several apps, so we moved it.
However, doing so has caused a new RuntimeException trying to access a class (Scinv) that extends a Struct from javolution.jar.  Is there some reason an app wouldn't be able to access a class in a JAR from Tomcat's lib dir in this way?
My class is (irrelevant details removed):
import javolution.io.Struct;
public class Scinv extends Struct {
    public static methodA() {...}
    public static methodB() {...}
    public static class ProdRecs extends Struct {...}
    public static class ProdRec extends Struct {...}
}

When I try to access the static methods of Scinv, which make use of the static nested classes, I'm getting this:
Apr 5, 2011 3:40:50 PM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet inventory threw exception
java.lang.RuntimeException: Struct class: general.dao.externalfiles.Scinv$ProdRec not found
at javolution.io.Struct.array(Struct.java:557)
at general.dao.externalfiles.Scinv$ProdRecs.<init>(Scinv.java:447)

Apr 5, 2011 3:40:50 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet default threw exception
java.lang.RuntimeException: Struct class: general.dao.externalfiles.Scinv$ProdRec not found
at javolution.io.Struct.array(Struct.java:557)
at general.dao.externalfiles.Scinv$ProdRecs.<init>(Scinv.java:447)

All I have to do is move the javolution-5.5.1.jar from Tomcat/lib to my WEB-INF/lib dir, and the app works fine again, no RuntimeExceptions.
Any ideas on why this is failing?  We also have postgres-9.0.jar file in Tomcat/lib dir, and it seems to work fine.
I'd be happy to provide more details if you need them, and any suggestions would be appreciated as I'm kind of stumped on this one!

A: I don't think it's the problem of putting javolution-5.5.1.jar in TOMCAT_HOME/lib folder, the JVM would have worried about the Struct object already (javolution.io.Struct.array(Struct.java:557)). The real cause of the problem is: What is happening on your constructor in general.dao.externalfiles.Scinv$ProdRecs class (Scinv.java:447)? Something is causing the object not to initialize and thus, the runtime exception.


text:
Q: How can I bind a kbd macro to a key for future sessions in common lisp? This is probably a newbie question.
I'm trying to bind a keyboard macro to a key and have it available each time I load a file. I'm using lispbox.
This is the code I'm trying (the macro used here is just a placeholder):
(fset 'macro1
      (lambda (&optional arg)
    "Keyboard macro."
    (interactive "p")
    (kmacro-exec-ring-item (quote ("uuu" 0 "%d")) arg)))
(global-set-key "[f5]" 'macro1)

But when evaluating, fset and global-set-key are undefined. I think I managed to avoid using fset by doing:
(setf (symbol-function 'macro1)...

But I can´t work my way around global-set-key. Calling the variable global-map shows the same message. I'm guessing, after searching a lot, that this isn't meant to work en CL but in Elisp. How should I proceed?


text:
Q: How to filter a table by checkbox with javascript? I'm creating a table from a XML file. The table has three columns (name, date, secret) and dynamic rows. I have created a checkbox on the header of the secret column (third column). When I click on the checkbox it should only show the one row with the oldest date of those who has the same "secret" and the same "name". If two rows has two identical secrets, but two different names, then both rows should be shown. The main part in the XSLT file is just the checkbox. I am not sure if I really need a onchange="identicalSecrets()" for the xslt code.
See code below for javascript. It doesn't work so I'm pretty sure that I have many mistakes on javascript code.
XSLT or HTML:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:template match="/">

    <title>Shared Secrets</title>

Shared Secrets

        <colgroup>
            <col width="150" style="background-color:red"></col>
            <col width="165"></col>
        </colgroup>

            plane
                <select id="modelRangeDropdown" onchange="filterReports()">
                     <option selected="selected">All</option>
                     <xsl:for-each select="logstore/plane">
                        <option>
                         <xsl:value-of select="Name" />
                        </option>
                     </xsl:for-each>
                </select>

            Datum
            Secret
                <input type="checkbox" id="identicalSecrets" onchange="identicalSecrets()"></input>
                hide identical secrets

        <xsl:for-each select="logstore/plane/trigger">

                <xsl:value-of select="../Name"/>
                <xsl:value-of select="date"/>
                <xsl:value-of select="secret"/>

        </xsl:for-each>

</xsl:template>
</xsl:stylesheet>

Main part on the code above:
Secret
    <input type="checkbox" id="identicalSecrets" onchange="identicalSecrets()"></input>
    hide identical secrets

Javascript code:
function identicalSecrets() {
    let checkBox, filter, rows, cells, secret;
    checkBox=document.getElementById('identicalSecrets');
    rows = table.getElementsByTagName("tr");
    filter = checkBox.value;
    for (let row of rows) {
        cells = row.getElementsByTagName("td");
        secret = cells[2];
        if (filter == true) {
            if (secret === row[-1].getElementsbyTagName("td")[2] && secret ===  row[-1].getElementsbyTagName("td")[0]) { // If the actual secret is equal to the secret in the last row and the modelranges are equal then hide these rows.
                row.style.display = "none"; // hide this row
            }
            else { // if secret or modelrange are not equal
                row.style.display = ""; // show this row
            }
        }
    }

}

I expect that when I click the checkbox, all rows with equal first column and third column will disappear except the row with the oldest date (second column).

A: There are a number of things wrong with your javascript...

*

*You have referenced a variable called table, but have not defined it.

*Doing row[-1] is not valid because row is not an array (rows is), and -1 isn't a valid index as arrays are 0-based. You should really set up a variable (called index) to keep a count of the row indexes, then you can do rows[index - 1] to get the previous row

*You only want to start checking the rows on the third row (as the first row is the header row, and the second row will have no previous data row to check)

*You are comparing the secret value with both the first and third columns. But you should be checking the name for the first column

*Javascript functions are case-sensitive, so getElementsbyTagName will not work due to the lower-case "by"

*You should really use "innerText" to get the text value of the cell, as you want to compare the text, not the cell object itself.

So, putting it all together, your javascript should probably look like this:
function identicalSecrets() {
    let table, checkBox, filter, rows, cells, secret, name;
    table = document.getElementById('myTable');
    checkBox=document.getElementById('identicalSecrets');
    rows = table.getElementsByTagName("tr");
    filter = checkBox.checked;
    let index = 0;
    for (let row of rows) {
        if (index > 1) {
            cells = row.getElementsByTagName("td");
            name = cells[0].innerText;
            secret = cells[2].innerText;
            if (filter == true) {
                if (name === rows[index - 1].getElementsByTagName("td")[0].innerText && secret === rows[index - 1].getElementsByTagName("td")[2].innerText) {
                    row.style.display = "none"; // hide this row
                }
                else { // if secret or modelrange are not equal
                    row.style.display = "table-row"; // show this row
                }
            }
            else {
                row.style.display = "table-row"; // show this row
            }
        }
        index++;
    }
}

See it in action at http://xsltfiddle.liberty-development.net/bnnZWi


text:
Q: Argument for setting the reference group to the biggest group in linear regression Is there, either for the lm() function or for some other function for linear regression, an argument such that the reference group can be set to always be the biggest group rather than the alphabetical/numerical default in lm()?
As this's often done in stats, I'm thinking I somehow keep missing it when I search the documentation or that I'm looking in the wrong places. Any help would be appreciated!
Below, even when in a UDF, is what I'd like NOT to have to keep doing.
mtcars # load dataset
mtcars <- mtcars[1:31, ]  # remove a now so that there is a single biggest group
lm(mpg ~ gear+carb+disp, data = mtcars ) # carb's group 1 is the reference by default
mtcars$carb <- as.factor(mtcars$carb)
mtcars <- within(mtcars, carb <- relevel(carb, ref = "4")) # set carb's group 4 as the reference
lm(mpg ~ gear+carb+disp, data = mtcars )

A: It doesn't look like lm has any option for this, but you can just create a wrapper function to change the levels of a factor accounting to frequeuncy, then use that in the formula.
big.ref <- function(x) {
  if(!is.factor(x)) x<-factor(x)
  counts <- sort(table(x), decreasing = TRUE)
  relevel(x, ref=names(counts)[1])
}
lm(mpg ~ gear + big.ref(carb) + disp, data = mtcars )

A: I don't believe there is a built-in function to do that but it's not that difficult to write one.
largest_ref <- function(DF, col){
    DF[[col]] <- factor(DF[[col]])
    tbl <- table(DF[[col]])
    largest <- names(tbl)[which.max(tbl)]
    DF[[col]] <- relevel(DF[[col]], ref = largest)
    DF
}

Now I will reload the test dataset and change a copy of it. Then run regressions on both datasets, the one releveled by your code and the one releveled by the function above.
data(mtcars)
mtcars <- mtcars[1:31, ]
mtc <- mtcars

mtcars$carb <- as.factor(mtcars$carb)
mtcars <- within(mtcars, carb <- relevel(carb, ref = "4")) # set carb's group 4 as the reference
fit1 <- lm(mpg ~ gear + carb + disp, data = mtcars)

mtc <- largest_ref(mtc, "carb")
fit2 <- lm(mpg ~ gear + carb + disp, data = mtc)

identical(coef(fit1), coef(fit2))
#[1] TRUE

As you can see, the results are the same. You can further see it with (output omited).
summary(fit1)
summary(fit2)


text:
Q: shared image file in Kotlin android studio I have an application in which I try to share a photo, but when you share the application it crashes.
    val bitmap = (imageViewx1.drawable as BitmapDrawable).bitmap
    val nombreArchivo:String="Shared.jpg"
    val patchload= getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString() + nombreArchivo
    val mifile2 =File(patchload)
    val stream: OutputStream = FileOutputStream(mifile2)
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
    stream.flush()
    stream.close()
    val shareIntent = Intent(Intent.ACTION_SEND)
    shareIntent.type = "image/jpg"
    val photoFile = File(filesDir, "PicturesShared.jpg")
    Toast.makeText(this, photoFile.toString(), Toast.LENGTH_SHORT).show()
    shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(photoFile))
    startActivity(Intent.createChooser(shareIntent, "Share image using"))

log:
Process: app.xxxx.appimage, PID: 21588
android.os.FileUriExposedException: file:///storage/emulated/0/Android/data/app.xxxx.appimage/files/PicturesShared.jpg expobeyond app through ClipData.Item.getUri()
    at android.os.StrictMode.onFileUriExposed(StrictMode.java:1967)
    at android.net.Uri.checkFileUriExposed(Uri.java:2364)
    at android.content.ClipData.prepareToLeaveProcess(ClipData.java:941)
    at android.content.Intent.prepareToLeaveProcess(Intent.java:9747)
    at android.content.Intent.prepareToLeaveProcess(Intent.java:9753)
    at android.content.Intent.prepareToLeaveProcess(Intent.java:9732)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1679)
    at android.app.Activity.startActivityForResult(Activity.java:4477)
    at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:676)
    at android.app.Activity.startActivityForResult(Activity.java:4435)
    at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:663)
    at android.app.Activity.startActivity(Activity.java:4800)
    at android.app.Activity.startActivity(Activity.java:4768)
    at app.xxxx.appimage.flip$onCreate$4.onClick(flip.kt:97)
    at android.view.View.performClick(View.java:6259)
    at android.view.View$PerformClick.run(View.java:24732)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6694)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)

A: The exception raised is
android.os.FileUriExposedException: file:///storage/emulated/0/Android/data/app.xxxx.appimage/files/PicturesShared.jpg expobeyond app through ClipData.Item.getUri()

FileUriExposedException is caused by

The exception that is thrown when an application exposes a file:// Uri
to another app.

When targeting Api 24 or higher you need to use a content provider to share a file with another app.


text:
Q: Python read file N line convert into 1 line Read N line file and display in one line.
i tried used list but cant make it.
a=open("txt","r")
b=a.read()
c=b.split()

The file got line 1 a,line 2 b,line 3 c,i need read the file and display abc.

A: Use readlines() to read all lines and join them:
with open('some.txt', 'r') as f:
    print(''.join(list(map(str.strip, f.readlines()))))

A: Use readlines():
with open('filename.txt', 'r') as f:
    content = f.readlines()

print("".join(c.strip() for c in content))


text:
Q: multi part identifier sql inner join I am creating an inner join between my tables companydetails andzonerpm.
I wrote this query:
select distinct
    coma.comname
from
    companydetails
inner join
    zonerpm zona  on coma.id = zona.comname
where
    zona.trainer = 'ayan pal'

but I get these errors:

Msg 4104, Level 16, State 1, Line 1
  The multi-part identifier "coma.id" could not be bound.
Msg 207, Level 16, State 1, Line 3
  Invalid column name 'comname'.
Msg 4104, Level 16, State 1, Line 3
  The  multi-part identifier "coma.comname" could not be bound.

A: Put an alias on companydetails
 select distinct coma.comname from companydetails coma
 inner join
 zonerpm zona  on coma.id=zona.comname
 where zona.trainer='ayan pal'


text:
Q: 10x10 table is not creating properly I want to create 10x10 grid so I am using TableLayout and this answer.
I am creating my tableView programmatically like this:
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val table = TableLayout(this)
    for (i in 0..9) {
        val row = TableRow(this)
        for (j in 0..9) {
            val cell = EditText(this)
            cell.setText("test")
            row.addView(cell)
        }
        table.addView(row)
    }

    setContentView(table)
}

Problem: this will work but will replace the layout of this activity (Probably because I am calling  setContentView(table))
How can I put my table view inside TableLayout (it's a view inside the activity layout) instead of my current resault?

For better understanding, my current code gives me this result (as I mentioned above):

A: You should checkout the Android basics first.
Anyway. Put your TableLayout into your layout, use findViewById() and use it instead of creating a new one.
val table = findViewById<TableLayout>(R.id.tablelayout)
for (i in 0..9) {
 // ... Same code
}


text:
Q: Failed to use CoCreateInstanceFromApp for sensor api, error: -2147221164, GetLastError 1008 Our team need to develop an app runing at IoT Non-UWP environment, and we need to call the sensor COM interface. but it failed at first to use the CoCreateInstanceFromApp/CoCreateInstanceEx.
The code snippet is like this:
ULONG ulCount = 0;
COINIT dwCoinit = COINIT_MULTITHREADED;
auto hr2 = CoInitializeEx(NULL, dwCoinit);

if (FAILED(hr2))
  {
  cout << "Failed to run  CoInitializeEx: " << hr2 << endl;
  return;
  }

MULTI_QI res = { 0 };
res.pItf = NULL;
res.hr = S_OK;
res.pIID = &IID_PPV_ARGS(&_pSensor);
//_hr = CoCreateInstanceEx(CLSID_SensorManager,
_hr = CoCreateInstanceFromApp(CLSID_SensorManager,
    NULL, CLSCTX_INPROC_SERVER, NULL, 1, &res);
if (S_OK != _hr)
{
   auto result = GetLastError();
   cout << "Failed Create Instance : " << _hr << " WinAPI Error: " << result  <<endl;
   return;
}

and it failed with the log:
Failed Create Instance : -2147221164 WinAPI Error: 1008
the error code means:
(-2147221164) "Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"
1008 means: ERROR_NO_TOKEN
it seems the sensorManager is not available.
Anyone know the method to fix it, and does MSFT expose the sensor api for Non-UWP environment?
Thanks
Jerome


text:
Q: SwiftUI - Binding var updates the original value only the first time, and then it doesn't update anymore I have a Picker that updates a @Binding value, that is linked to the original @State value. The problem is that it gets updated only the first time I change it, and then it always remains like that. Not only in the sheet, but also in the ContentView, which is the original view in which the @State variable is declared. Here's a video showing the problem, and here's the code:
ContentView:
struct ContentView: View {

    @State var cityForTheView = lisbon
    @State var showCitySelection = false

    var body: some View {
        VStack {
            //View
        }
        .sheet(isPresented: $showCitySelection) {
            MapView(cityFromCV: $cityForTheView)
        }
    }
}

MapView:
struct MapView: View {

    @Environment(\.presentationMode) var presentationMode
    @Binding var cityFromCV : CityModel

    @State var availableCities = [String]()
    @State var selectedCity = "Lisbon"

    var body: some View {
        NavigationView {
            ZStack {
            VStack {
                Form {
                    HStack {
                        Text("Select a city:")
                        Spacer()
                        Picker("", selection: $selectedCity) {
                            ForEach(availableCities, id: \.self) {
                                            Text($0)
                                        }
                                    }
                        .accentColor(.purple)

                    }
                    .pickerStyle(MenuPickerStyle())

                    Section {
                        Text("Current city: \(cityFromCV.cityName)")
                    }
                }
            }
        }
        }
        .interactiveDismissDisabled()
        .onAppear {
            availableCities = []
            for ct in cities {
                availableCities.append(ct.cityName)
            }
        }
        .onChange(of: selectedCity) { newv in
            self.cityFromCV = cities.first(where: { $0.cityName == newv })!
        }
    }
}

CityModel:
class CityModel : Identifiable, Equatable, ObservableObject, Comparable {

    var id = UUID()
    var cityName : String
    var country : String
    var imageName : String

    init(cityName: String, country: String, imageName : String) {
        self.cityName = cityName
        self.country = country
        self.imageName = imageName
    }

    static func == (lhs: CityModel, rhs: CityModel) -> Bool {
        true
    }

    static func < (lhs: CityModel, rhs: CityModel) -> Bool {
        true
    }

}

var cities = [
    lisbon,
    CityModel(cityName: "Madrid", country: "Spain", imageName: "Madrid"),
    CityModel(cityName: "Barcelona", country: "Spain", imageName: "Barcelona"),
    CityModel(cityName: "Paris", country: "France", imageName: "Paris")
]

var lisbon = CityModel(cityName: "Lisbon", country: "Portugal", imageName: "Lisbon")

What am I doing wrong?

A: The problem are:
at line 35: you use selectedCity to store the selected data from your picker.
 Picker("", selection: $selectedCity) {

then at your line 46: you use cityFromCV.cityName to display the data which will always show the wrong data because you store your selected data in the variable selectedCity.
 Section {
  Text("Current city: \(cityFromCV.cityName)")
 }

Solution: Just change from cityFromCV.cityName to selectedCity.


text:
Q: Send notification to status bar I try to buid a phonegap app and I want to send notification to status bar of the phone(like facebook app when you receive a notification).
I build my app on build.phonegap.com because I'm newbie.
Can anyone send me a tutorial how I do that ?

A: Not sure if you there is currently a means by which you can send a notification to the status bar outside of a native app atm?


text:
Q: how to save local image to online database I am creating iPhone app where I am taking photo. Now I want to save this photo online (say at link www.test.com/myiPhoneAppImages/).
Any idea how to take image from iPhone to website?
I tried googling it, however didn't find any useful tuts.
Any help/ suggestion would be greatful.

A: Oh! don't know why google won't give you any result, let I did it for you!
1) Uploading images to Remote Server, iPhone
2) upload images and texts to server
3) how to upload UIImage on server?
4) Iphone> Uploading UIImage object to server via ASIHTTPRequest, photo name?
5) iphone: upload image to server using ASIFormDataRequest ---Recommanded
Overall Results page

A: Try the below method to post images to server
- (void) doPostImage

{
    NSAutoreleasePool   *pool                       = [[NSAutoreleasePool alloc]init];

    //Add your images here...
    NSArray *imageParams = [NSArray arrayWithObjects:@"myimage1.png", nil];

    NSString *urlString = @"http://yourURL";

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    [request setURL:[NSURL URLWithString:urlString]];

    [request setHTTPMethod:@"POST"];

    NSMutableData *body = [NSMutableData data];

    NSString *boundary = @"---------------------------14737809831466499882746641449";

    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];

    [request addValue:contentType forHTTPHeaderField:@"Content-Type"];

    // add the image form fields

    for (int i=0; i<[imageParams count]; i++) {

        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: attachment; name=\"image%d\"; filename=\"%@\"\r\n", i, [imageParams objectAtIndex:i]] dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

        [body appendData:[NSData dataWithData:UIImageJPEGRepresentation(m_ImgVw_SelectedImage.image, 90)]];

        [body appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    }

    // add the text form fields

    // close the form
        [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    // set request body
       [request setHTTPBody:body];

    // send the request (submit the form) and get the response

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    [request release];

    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

    if(returnString)
    {
        [m_ctrlActivityView stopAnimating];
        NSString *m_strMessage=[NSString stringWithFormat:@" Your image is recieved"];
        [returnString release];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Thank you" message:m_strMessage delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"Error in server communication. Try again later" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];

    }

    CFRunLoopRun();

    [pool release];
}

A: you could search it in the search engine.
data way: phone image-----upload to website------save to dataBase by the website logic.
By the way,you needn't to write the upload logic yourself, AFNetworking would be a cool third-part framework for you. GitHub link


text:
Q: Understanding Standard Error ($\frac{\sigma}{\sqrt{n}}$) from the definition In the "normal" sense, I have understood standard error to be the standard deviation of the means. Hence, you would need to calculate multiple averages ($\bar{x}_1,..., \bar{x}_n$) and calculate the standard deviation (let $u$ be the average of the average):
$$SE = \sqrt{\frac{\sum\limits_{i=1}^{n} (\mu - \bar{x}_i)^2}{n-1}}$$
I do not understand how this eventually becomes $(1) \ SE = \frac{\sigma}{\sqrt{n}}$ . Afterall, don't you need multiple averages to get this value? How are we able to calculate it with just one set of data? An explanation on how $(1)$ is derived would be greatly appeciated.

A: If the $X_i$ are i.i.d. with expectation $\mu$ and variance $\sigma^2$, and you take a sample size $n$ then the mean $\bar X$ is distributed with expectation $\mu$ and variance $\dfrac{\sigma^2}{n}$.  The square root of that variance is then the standard error of the mean and is $\sqrt{\mathbb E\left[(\bar X-\mu)^2\right]} = \sqrt{\dfrac{\sigma^2}{n}}=\dfrac{\sigma}{\sqrt n}$.
If you do not know $\sigma^2$ then you may want to estimate the standard error from your observations.  Your expression is a possible approach based on taking multiple samples, so if you took $m$ of these (not the same as $n$) then you could use $\sqrt{\dfrac{\sum\limits_{j=1}^{m} \left( \bar{x}_j - \overline{\bar x}\right)^2 }{m-1}}$, but this would involve $mn$ observations as well as averages of averages.
Alternatively, you could use one sample size $n$ to estimate $\sigma^2$ perhaps with $\dfrac{1}{n-1}\sum\limits_{i=1}^{n} ({x}_i-\bar x )^2$, and thus estimate   $\dfrac{\sigma}{\sqrt n}$ using $\sqrt{\dfrac{1}{n(n-1)}\sum\limits_{i=1}^{n} ( {x}_i-\bar x )^2}$.


text:
Q: How can I iterate the excel column data in Simulink (matlab function block)? I would like to import data one by one from excel(.csv) to Simulink.
With readtable or readcell, I can call a group of data.
But I would like to update the data in excel one by one automatically.
For example,
In loop :
I import the data in Excel A1, and I apply my function.
secondly the data in Excel A2, and I apply my function.
A3, A4, A5..
excel data example
In Python, I can use like this :
 sheet1.cell(row=i+1, column= 1, value= x_in_data[0])
so that I can easily apply the iteration.
However, in Simulink Matlab function block,
The readcell command is actually calling the string like this.
M = readcell('airlinesmall_subset.xlsx','Sheet','2007','Range','G2:I11')
What should I do?


text:
Q: how to set value in dropdown in react js? could you please tell me how to set value in dropdown in react js ?
I am getting dropdown data after few seconds 3000 and then I need to set value on dropdown
const App = ({ children }) => {
  const val = "ax";
  const [state, setState] = useState([]);
  setTimeout(() => {
    setState(countryOptions);
  }, 2000);
  return (
    <Container style={{ margin: 20 }}>
      <Example countryOptions={state} />
    </Container>
  );
};

https://codesandbox.io/s/semantic-ui-example-utev4
expected output
Aland Islands should be selected.
{ key: "ax", value: "ax", text: "Aland Islands" },
as after three second I want to select this element
const val = "ax";

A: As stavros answer suggested; it may be better to keep state in App component and pass the setVal to the dropdown:
App:
const App = ({ children }) => {
  const [state, setState] = useState([]);
  //added val and setVal in App state
  const [val,setVal]=useState('ax');
  setTimeout(() => {
    setState(countryOptions);
  }, 2000);
  return (
    <Container style={{ margin: 20 }}>
      //pass val and setVal so dropdown can set val on change
      <Example countryOptions={state} val={val} onChange={setVal}/>
    </Container>
  );
};

Dropdown:
const DropdownExampleClearableMultiple = ({ countryOptions,val,onChange }) => (
  <Dropdown
    clearable
    fluid
    search
    closeOnChange
    selection
    options={countryOptions}
    //set value to passed in val
    value={val}
    //use setVal that was passed in as onChange
    onChange={(_,i)=>onChange(i.value)}
    placeholder="Select Country"
  />
);

A: You should update your question because only after visiting the codesandbox was I able to get enough info for an answer..
In your index.js you should update setState(countryOptions) to :
setState({countryOptions:countryOptions},()=>setState({val:"ax"})

Then line 39  to :
<Example countryOptions={state.countryOptions:countryOptions} val={state.val} />

Then in your example.js update const DropdownExampleClearableMultiple to:
const DropdownExampleClearableMultiple = ({ countryOptions, val }) => (
<Dropdown
  clearable
  fluid
  search
  closeOnChange
  selection
  options={countryOptions}
  placeholder="Select Country"
  value={val}
/>
);

A: Use the "value" prop.
// index.js
const App = ({ children }) => {
  const val = "ax";
  const [state, setState] = useState([]);
  setTimeout(() => {
    setState(countryOptions);
  }, 2000);
  return (
    <Container style={{ margin: 20 }}>
      <Example countryOptions={state} value={val} />
    </Container>
  );
};

// example.js
const DropdownExampleClearableMultiple = ({ countryOptions, value }) => (
  <Dropdown
    clearable
    fluid
    search
    closeOnChange
    selection
    value={value}
    options={countryOptions}
    placeholder="Select Country"
  />
);

A: You can pass value to value property of Dropdown. Use state property for selected value.
Make sure that you change/update state on onchange event.


text:
Q: Having trouble adding files to an existing, empty github repository First, I created a repository on github that is obviously empty. Then I initiated a git bash terminal in my working directory. Once I do that, I'm using the following code to push my files to the github repository:
git init
git add .
git commit -m "my commit"
git remote set-url origin git@github.com:username/repo.git
git push origin master

When I run git push origin master, I get the following error:
error: src refspec master does not match any.
error: failed to push some refs to 'git@github.com:/madsthaks/AdTrackingFraudDetection.git'

I'm not very comfortable with git so I'm having a bit of trouble with this. Any help would be much appreciated.

A: try
git init
echo. readme>README.md
git add .
git commit -am "Initial Commit"
git remote add origin https://github.com/madsthaks/AdTrackingFraudDetection
git push --set-upstream origin master


text:
Q: prove $f(x)=x^3+x$ is one to one and onto The Problem
For my discrete structures course, I need to prove that $f(x)$ is one-to-one and onto, with $f:{\rm I\!R}\rightarrow{\rm I\!R}$ where $f(x)=x^3+x$. Based on the graph, this function is one-to-one and onto, and Wolfram confirms this, but I don't know how to approach the actual proof.
Proving it One-to-One
I understand a function $f(x)$ is one-to-one if for $x_1,x_2\in{\rm I\!R}$, if $f(x_1)=f(x_2)$ implies $x_1=x_2$.
 The problem is when I set $f(x_1)=f(x_2)$ this, I eventually get to
$$\sqrt[3]{x_1^3+x_1}=\sqrt[3]{x_2^3+x_2}$$
It's at this point I'm stuck, and don't know how to progress any further.
Proving it Onto
So I understand to prove a function is onto, you solve $f(x)$ for $y$, and use the result as input to $f(x)$, and if $f(x)=y$, the function is onto. But I run into a similar problems where
$$x^3+x=y$$
I could take a cubic root or rearrange the variables all I want but I can't think of a way to isolate $x$ and get $x=something$

A: Let $f:\Bbb R\to\Bbb R$ be the function $f(x)=x^3+x$. Then $f'(x)=3x^2+1\ge 1>0$, so $f$ is strictly monotone, thus injective (one-to-one). Then the limits of $f$ at $\pm\infty$ are respectively $\pm\infty$, and from the continuity of $f$ each value in between is taken.
Note: One can also show algebraically that $f$ is injective, so assume $f(a)=f(b)$, then
$$
0=f(a)-f(b)=(a-b)\underbrace{(a^2+ab+b^2+1)}_{\ge 0+1>0}\ ,
$$
so the factor $(a-b)$ must vanish, so $a=b$.

A: Surjectivity:  For each $y$ polynomial equation $$x^3+x=y$$ is of odd degree, so it must have at least one real solution and thus $x^3+x$ is surjective.
Injectivety: Say there are $a$, $b$ such that $f(a)= f(b)$ and suppose $a\ne b$, then $$ (a-b)(a^2+ab+b^2+1)=0\implies a^2+ab+b^2+1=0$$
so multilpying this with 2 we get $$ (a+b)^2+a^2+b^2 +2 =0$$ which is clearly nosense. So $a=b$.

A: Partial answer:
1) Injective:
$x_1,x_2 \in \mathbb{R}$, and let
$f(x_1)=f(x_2).$
$x_1^3 +x_1=x_2^3+x_2$;
$x_1^3-x_2^3 +x_1-x_2=0;$
$(x_1-x_2)(x_1^2+x_1x_2+x_2) +(x_1-x_2)=0;$
$(x_1-x_2)(x_1^2+x_1x_2+x_2^2+1)=0;$
It follows $x_1=x_2$ , and we are done,
since $(x_1^2+x_1x_2+x_2^2+ 1) >0$.
Recall: $a^2+b^2 \ge 2|ab|$,
$a^2+ab+b^2 \ge 2|ab| +ab \ge$
$|ab| \ge 0.$
$a^2+ab+b^2 +1 \ge 1 >0.$
2) $y=x^3+x$ , a polynomial of degree $3$ has at least one real root.(Cf. Answer by Maria Mazur).
For given $y$, it has exactly one real root since $y=f(x)$ is injective.

A: It is one-to-one because it is strictly increasing ($x>y\implies f(x)>f(y)$) and it is surjective be cause $\lim_{x\to\pm\infty}f(x)=\pm\infty$ and by the intermediate value theorem.

A: Just to take a different approach, you can use Cardano's formula: write the equation $x^3+x=y$ as $x^3+x-y=0$. The discriminant is
$$
\frac{y^2}{4}+\frac{1}{27}>0
$$
so the equation has a single real solution, for every $y$. This proves at once both injectivity and surjectivity.
You can even solve for the inverse function:
$$
x=\sqrt[3]{\frac{y}{2}+\sqrt{\frac{y^2}{4}+\frac{1}{27}}}+
  \sqrt[3]{\frac{y}{2}-\sqrt{\frac{y^2}{4}+\frac{1}{27}}}
$$


text:
Q: Why is this type not considered Newable in TypeScript
export class Thing{
    name: string = "dunno"
}

export interface IMakeThing<T extends new (...args: any) => any>{
    value: T
}

const owner = new Thing();

const test:  IMakeThing<Thing> = {
    value: new Thing
};

It complains when using the Thing as a generic param on IMakeThing.  But I am not sure why as the generic constraint asks for a constructor function.
Playground link here
https://www.typescriptlang.org/play?noImplicitAny=false&strictFunctionTypes=false&strictBindCallApply=false&target=1&module=1&ts=4.1.3&ssl=14&ssc=3&pln=1&pc=1#code/LAKApgHgDg9gTgFwAQGMA2BDAzlpAVACwEsA7AcwG9QkakSMBbMALiSwTlLKQF4kAiACYBXEiRj9QAX1ChIsRElIIwcAGYYUYJAEkAshgDWYQlwA8eJJBUlBuEmADuSABQA6DxjhksrDCQBPAEpeAD4kfwDQqhBaJAA3DDRhFnxpWRAUGBJ2JBhHBzheOid8YnIXIIBuDKyc5BV2Vl0DY1NyC3KycL4YuMTk1IdndrJpKqA

A: For convenience, class types are the type of the class objects, and the type of the actual class (the constructor) is typeof Class. So, in this case, you'd have to use IMakeThing<typeof Thing>, not IMakeThing<Thing>. You have another issue where value will then have to be the actual class object, so you could make a ConstructedType utility type that extracts the type constructed and uses that for the type of value:
export class Thing{
    name: string = "dunno"
}

type ConstructedType<T extends new (...args: any) => any>
    = T extends new (...args: any) => infer R ? R : never;

export interface IMakeThing<T extends new (...args: any) => any>{
    value: ConstructedType<T>
}

const owner = new Thing();

const test:  IMakeThing<typeof Thing> = {
    value: new Thing
};

Or just use the much prettier approach of just using the object type from the beginning since you don't need the constructor type:
export class Thing{
    name: string = "dunno"
}

export interface IMakeThing<T>{
    value: T
}

const owner = new Thing();

const test:  IMakeThing<Thing> = {
    value: new Thing
};

If you actually mean to put the constructor function under value, then just pass Thing, not new Thing, since new Thing expands to new Thing():
export class Thing{
    name: string = "dunno"
}

export interface IMakeThing<T extends new (...args: any) => any>{
    value: T
}

const owner = new Thing();

const test:  IMakeThing<typeof Thing> = {
    value: Thing
};


text:
Q: Edit TextArea in for loop I have this method in my jFrame Training.java
public void editText(String S){
        jTextArea1.append(S);
    }

And I called in other class
for(int k=0;k<filesX.length;k++){
           try{
               I=ImageIO.read(filesX[k]);
               for(int i=0;i<I.getWidth();i++)
                   for(int j=0;j<I.getHeight();j++){
                        colorAux=new Color(I.getRGB(i, j));
                            r=colorAux.getRed();
                            g=colorAux.getGreen();
                            b=colorAux.getBlue();
                   }
            }catch(Exception e){}
            E.editText("Image #"+(k+1)+"..."+"\n");
 }

But the append just work at the end adding the full text but I need to edit the jTextArea for each iteration.
Sorry for my bad English and thank you.
PD. ty @mojo I resolved like you say adding a SwingWorker object...

A: append() does exactly what it says. It appends text to the text area. Instead you should use setText()
public void editText(String S){
    jTextArea1.setText(S);
}


text:
Q: cannot display data based on passing parameter? i have a difficulty to display data based on the parameter pass. below are my code based on the sequence. My problem is, when is debug, the controller where it pass to second page jsp, it retrieve the parameter which is courseId, but when it doesn't display the data in jsp and in the controller of get the data.. I know my question is long but please help me.the first page will show the list of courses available. when the user click on the course, it will go the controller
@RequestMapping(value="MregisteredClassesDetail.phone")
public final ModelAndView registeredClassesDetail(final HttpServletRequest request,
        final HttpServletResponse response,HttpSession session) {
    ModelAndView mav = new ModelAndView();
    log.debug("Registered Classes Detail:");
    log.debug("CourseId:"+request.getParameter("courseId"));
    request.setAttribute("page",  AlteraCommonConstant.DEFAULT_PAGE);
    request.setAttribute("row",  AlteraCommonConstant.DEFAULT_PAGE_SIZE);
    request.setAttribute("courseId","courseId");
    System.out.println(">>>>>>>>>>>>>>>> Registered Classes Detail");
    mav.setViewName("mobile/MregisteredClassesDetail.jsp");
    return mav;
}

then it will go to the jsp second page..
$('#MregisteredClassesDetails').live('pageshow', function(){
    var rowInput = "1";
    var pageInput = "1";
    var idInput = document.getElementById("courseId");

    $.ajax({
     url: '${pageContext.request.contextPath}/getRegisteredClassesDetails.html',
     data: ( {rows : rowInput , page : pageInput, courseId : idInput}),
     type: 'POST',

     success: function(json_results){
       $('#list').append('<ul data-role="listview" data-inset="true"
');
       listItems = $('#list').find('ul');
       html  = '#################################################################################################';
       html += '
' +json_results.courseName+'
';
       html += '#################################################################################################';
       html += '
 Registration #    : '+json_results.regNo+'
';
       html += '
 Status            : '+json_results.regStatus+'
';
       html += '
 Location          : '+json_results.courseLoc+'
';
       html += '
 Start Date        : '+json_results.startDate+'
';
       html += '
 Registered Person : '+json_results.fullName+'
';
       html += '
 Rate              : '+json_results.rate+'
';
       listItems.append(html);

       $('#list ul').listview();
       $.mobile.pageLoading(true);
    }
});
});

and the html
<form name="ViewClassForm" method="POST">
<input name="courseId" type="hidden" value="${MregisteredClassesDetail.courseId}"/>
</form>

then it will go to the controller back to retrieve data..
@RequestMapping(value = "getRegisteredClassesDetails.html", method = RequestMethod.POST)
public @ResponseBody CustomPagedResultResponse getRegisteredClassesDetails(
        HttpServletRequest request,HttpSession session) {
    CustomPagedResultResponse paging = new CustomPagedResultResponse();

    log.debug("getRegisteredClassesData.html:");
    log.debug("rows:"+request.getParameter("rows"));
    log.debug("courseId:"+request.getParameter("courseId"));
    log.debug("page:"+request.getParameter("page"));
    log.debug("sidx:"+request.getParameter("sidx"));
    log.debug("sord:"+request.getParameter("sord"));

    String page = request.getParameter("page");
    int pageSize = new Integer(request.getParameter("rows")).intValue();
    StringBuffer condition = new StringBuffer();
    if (request.getParameter("sidx") != null && !request.getParameter("sidx").equals("")) {
        condition.append(request.getParameter("sidx"));
        condition.append(" ");
    }
    if (request.getParameter("sord") != null && !request.getParameter("sord").equals("")) {
        condition.append(request.getParameter("sord"));
    }
    log.debug("condition: " + condition.toString());
       log.debug("page:"+page);
       log.debug("row:"+pageSize);

    String courseType = "%";

    UserProfile userProfile = (UserProfile)session.getAttribute("userProfile");

    //////////////////////////////////////////////////////
    // Retrieve  Total Record first
    ///////////////////////////////////////////////////////
    RegisteredClassesSearch search = new RegisteredClassesSearch();
    search.setLanguage("ENU");
    search.setLoginRowId(userProfile.getContactRowId());
    search.setRegNo(null);
    search.setAction("1");
    search.setCourseType(courseType);
    search.setPage(null);
    search.setPageSize(null);
    search.setOrderBy(null);

    Integer recordCount = registeredClassesService.getTotalAccounts(search);
    log.debug("*****Training Controller Total record:"+recordCount);
    System.out.println("*****Training Controller Total record:"+recordCount);

    //////////////////////////////////////////////////////
    // Retrieve  Total Record first
    ///////////////////////////////////////////////////////
    if(recordCount>0){

        System.out.println("******** Login Id:"+userProfile.getContactRowId());
        System.out.println("******** Course Type:"+courseType);
        System.out.println("******** Page Size:"+pageSize);
        System.out.println("******** Page:"+page);
        System.out.println("******** Order By:"+condition);

        List<RegisteredClassesTest> registeredClassesView = registeredClassesService.getAccounts(search);

        paging.setRows(registeredClassesView);
    }else{
        paging.setRows(null);
    }

    paging.setRecords(String.valueOf(recordCount));
    paging.setPage(page);
    int total = recordCount % pageSize == 0 ? recordCount / pageSize : recordCount / pageSize + 1;
    paging.setTotal(String.valueOf(total));

    return paging;
}

A: I think you have a typo here in this case.
In your first controller you are setting the course id in request parameter like below.
request.setAttribute("courseId","courseId");

According to me it should be
request.setAttribute("courseId",some int value);

You are not adding some actual value in courseId.
Hope this helps you.
Cheers.


text:
Q: EC2 cant send SES mail behind an ELB We run a wiki in an EC2 that sits behind an Elastic Load Balancer, the EC2 does not have a public IP and traffic from internet is routed to the ELB through Route53.
We noticed that the wiki was not sending emails and while troubleshooting I realized that if I add an Elastic IP then the wiki does send emails just fine.
It's maybe worth noting that the database and EC2 are part of the same VPC, region and account, but the EC2 and the Simple Email Service belong to different AWS accounts.
I checked the security group of the EC2, the ELB security group and the VPC network ACL, they all allow outbound traffic everywhere, which leaves me at a loss as to why would it not be able to connect to SES
Ideally we wouldn't need a public IP on the EC2 in order to send email.
Is there anything I should check or is there a known way to make this work?

A: Since you can add a Elastic IP to your EC2 instance, I am assuming it is in a public subnet. In your setup, you can not reach the internet (the SES endpoint in another region) from your EC2 instance. Your Load Balancer (in the same public subnet) however can reach your EC2 instance, which is why your site is working.
The easiest solution would be, to place your EC2 instance in your private subnet (e.g. the one where your database is). Then you can route via your NAT Gateway to the internet, and should be able to send mails via SES just fine.
A workaround would be, to assign any public IP to the instance. It does not need to be an elastic IP.


text:
Q: How to dynamically traverse through all fields of a class in kotlin? I'd like to dynamically traverse through all fields of a class in kotlin. The purpose is that I'd like to convert the class object to TSV by joining all fields. As there will be a lot of subclasses, it would be great to do this dynamically. After some investigation, I found a solution below. It did work but the order of the fields is not consistent with the order each field was declared.
I think annotation could work, but not sure how. Any idea? Thanks!
abstract class BaseModel {
    fun toTSV(): String {
        return this::class.memberProperties.map {
            it.getter.call(this).toString()
        }.joinToString("\t")
    }
}
class Model (
    val model_id: String,
    val name: String,
    val version: Int,
    val desc: String
) : BaseModel()

fun main(args : Array<String>) {
    val model = Model(
            model_id = "mid",
            name = "model name",
            version = 1,
            desc = "some desc"
    )
    println(model.toTSV())
}

The code above produces:
some_desc   mid model_name  1

but I am expecting:
mid  model_name  1   some_desc

Just like the order of fields in the class.

A: I suggest you to override toString on each model, to get the tab separated values in each field :)
class MyModel {
var id: Long = 0L
...
override fun toString(): String {
    val sb = StringBuilder()
    sb.append("class MyModel {\n")
    sb.append("    id: ").append(toIndentedString(id)).append("\n")
    sb.append("\n}")
    return sb.toString()
    }

    /**
     * Convert the given object to string with each line indented by 4 spaces
     * (except the first line).
     */
    private fun toIndentedString(o: Any?): String {
        return o?.toString()?.replace("\n", "\n    ") ?: "null"
    }

}

this works for me everytime.

A: Using generics and extension properties we can achieve this like so
val <T> T.fields: List<String>
    get() {
        return this!!::class.java.declaredFields.map { it.name }
    }

val <T> T.fieldsString: String
    get() {
        return this!!::class.java.declaredFields.map { it.name }.joinToString(", ")
    }

 fun toTSV2(): String {
    val name2value = this::class.memberProperties.map {
        it.name to it.getter.call(this).toString()
    }.toMap()
    return this!!::class.java.declaredFields.map {
        name2value[it.name] }.joinToString("\t")
}

A: OK, combined with Brandon's answer, I finally got this. It worked:
    fun toTSV2(): String {
    val name2value = this::class.memberProperties.map {
        it.name to it.getter.call(this).toString()
    }.toMap()
    return this!!::class.java.declaredFields.map {
        name2value[it.name] }.joinToString("\t")
}


text:
Q: After adding a variable to framework.jar it still not accessible I'm trying to modify frameworks.jar by adding a static boolean variable(just for tests)
To do it I extracted frameworks.jar from emulator decompiled it and added to LocationManager this line:
.field public static TEST:Z = 0x0

And to test this variable I created a small app where I'm trying to access to this variable using this line of code
sget-boolean v1, Landroid/location/LocationManager;->TEST:Z

But it gives me an exception.
I checked if modified framework.jar doesn't replace original by pulling it and decompiling. I found this variable in framework.jar which I pulled from phone.
If this variable exists, why it still tells me that it is not
The exception
06-30 02:16:53.388 E/AndroidRuntime(10801): FATAL EXCEPTION: main
06-30 02:16:53.388 E/AndroidRuntime(10801): Process: com.greedycat.smalitest, PID: 10801
06-30 02:16:53.388 E/AndroidRuntime(10801): java.lang.IllegalStateException: Could not execute method for android:onClick
06-30 02:16:53.388 E/AndroidRuntime(10801):     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
06-30 02:16:53.388 E/AndroidRuntime(10801):     at android.view.View.performClick(View.java:6302)
06-30 02:16:53.388 E/AndroidRuntime(10801):     at android.view.View$PerformClick.run(View.java:24782)
06-30 02:16:53.388 E/AndroidRuntime(10801):     at android.os.Handler.handleCallback(Handler.java:790)
06-30 02:16:53.388 E/AndroidRuntime(10801):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-30 02:16:53.388 E/AndroidRuntime(10801):     at android.os.Looper.loop(Looper.java:164)
06-30 02:16:53.388 E/AndroidRuntime(10801):     at android.app.ActivityThread.main(ActivityThread.java:6518)
06-30 02:16:53.388 E/AndroidRuntime(10801):     at java.lang.reflect.Method.invoke(Native Method)
06-30 02:16:53.388 E/AndroidRuntime(10801):     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
06-30 02:16:53.388 E/AndroidRuntime(10801):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
06-30 02:16:53.388 E/AndroidRuntime(10801): Caused by: java.lang.reflect.InvocationTargetException
06-30 02:16:53.388 E/AndroidRuntime(10801):     at java.lang.reflect.Method.invoke(Native Method)
06-30 02:16:53.388 E/AndroidRuntime(10801):     at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
06-30 02:16:53.388 E/AndroidRuntime(10801):     ... 9 more
06-30 02:16:53.388 E/AndroidRuntime(10801): Caused by: java.lang.NoSuchFieldError: No static field TEST of type Z in class Landroid/location/LocationManager; or its superclasses (declaration of 'android.location.LocationManager' appears in /system/framework/framework.jar)
06-30 02:16:53.388 E/AndroidRuntime(10801):     at com.greedycat.smalitest.MainActivity.click(MainActivity.java:20)
06-30 02:16:53.388 E/AndroidRuntime(10801):     ... 11 more
06-30 02:16:53.392 W/ActivityManager( 1237):   Force finishing activity com.greedycat.smalitest/.MainActivity

A: Variable name is TEST, exception mentions IS_MOCKING so    you did not recompile app properly or something like that.


text:
Q: PostgreSQL not in path after installation I installed PostgreSQL using the interactive installer by EnterpriseDB following this link. It defaulted the installation directory to /Library/PostgreSQL/9.6. After successful install, psql is not in the $PATH. I have to navigate to the installation directory or enter the full path execute it:
cd /Library/PostgreSQL/9.6/bin
./psql -d template1

Must I add this path to .profile or .bash_profile, create a symlink to /usr/bin? What approach is more suitable for the Mac?
Because this is not working:
# ln -s /Library/PostgreSQL/9.6/bin/psql /usr/bin/psql
ln: /usr/bin/psql: Operation not permitted

Temporary solution:
sh-3.2# ln -s postgres /usr/local/bin/postgres
sh-3.2# ln -s createdb /usr/local/bin/createdb
sh-3.2# ln -s createuser /usr/local/bin/createuser
sh-3.2# ln -s dropdb /usr/local/bin/dropdb
sh-3.2# ln -s dropuser /usr/local/bin/dropuser
sh-3.2# ln -s initdb /usr/local/bin/initdb
sh-3.2# ln -s pg_ctl /usr/local/bin/pg_ctl
sh-3.2# ln -s pg_dump /usr/local/bin/pg_dump
sh-3.2# ln -s pg_dumpall /usr/local/bin/pg_dumpall

A: In contrary to other PostgreSQL installers (e.g. Homebrew), the EnterpriseDB installer doesn't install the PostgreSQL executables in a path covered by your default $PATH.
So either add it to your .bash_profile file
...
export PATH="/Library/PostgreSQL/9.6/bin:$PATH"
...

or
...
export PATH="$PATH:/Library/PostgreSQL/9.6/bin"
...

or symlink the executables to /usr/local/bin:
ln -s /Library/PostgreSQL/9.6/bin/* /usr/local/bin

You can't link them to /usr/bin/ because this path is protected by SIP and - after disabling SIP - a sudoer would have to prepend sudo  to link the files. /usr/local/bin is the default path for user installed executables anyway, so stay with this one.


text:
Q: Events and signals in Qt's QGraphicsItem: How is this *supposed* to work? Like other primitives in Qt, QGraphicsItems can handle mouse events and the like. Sweet! Now say I need for an event on one QGraphicsItem to be propagated to some other QGraphicsItems in the same scene. I can think of two ways that one might approach this:

(A) The Naive Approach - Signaling
Concept : Connect sibling QGraphicsItems together with signals. Event handlers on QGraphicsItem call emit()s that evoke coordinated responses on other QGraphicItems. This follows the general design pattern established throughout the Qt framework.
Implementation : For reasons that I do not fully grasp, QGraphicsItems cannot emit() signals. It has been suggested that derived classes that also inherit from QGraphicsObject may be able to work around this. It seems to me, though, that the exclusion of emit() on QGraphicsItems was probably an intentional design decision on the part of the Qt devs and, therefore, multiple inheritance is probably not the Right Solution.
(B) Container-Level Event Handling
Concept : QGraphicsItems always exist in the context of a container of type QGraphicsScene. Events that in (A) were handled at the level of the QGraphicsItem are instead handled by an object inheriting from QGraphicsScene. This object also implements the logic for coordinating responses between sibling QGraphicsItems.
Implementation : QGraphicsScene definitely has the ability to handle events that would otherwise make their way down to QGraphicsItems. QGraphicsScene also provides the itemsAt() method for determining which of the things in it are affected by positional events, like mouse clicks. Still, building up considerable logic within a container class for coordinated action among containees feels like a failure to encapsulate properly. Bad practice? Maybe, but this seems to be the way it's done in at least one official example.

Questions

*

*What's the Right Solution here? If not A or B, then is it something else that I haven't thought of?

*Why did the Qt devs allow QGraphicsItems to receive events but not send signals? This seems like a major exception to the design pattern used throughout the framework.

*An extension of this problem is communication between QGraphicsItems and higher-order container classes, like the main application. How is that meant to be addressed?

A: Signaling is not part of QGraphicItem because they do not inherit from QObjects. This was a design decision for performance reasons, to allow very large and fast scenes. If you decide you really need special cases for signals, QGraphicsWidget was created to fill this gap. It does inherit from QObject and lets you have a mixture of QWidget and QGraphicsItem functionality. Though it is recommended that you avoid this if your scenes are even moderately sizable.
Another option which might be relevant to your situation is to make use of the sceneEventFilter method. You can set one item to receive events for another and decide if they should be propagated or not:
http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qgraphicsitem.html#sceneEventFilter
One item can be set as the filter for multiple objects. And it can identify each individual item and event to respond to.
Generally though you should make use of the scene for coordination across its objects. That is already the pattern being used for events (the scene coordinating delivery of all events to the items).
Also, it seems that your option A is not possible because QGraphicsItem does not even have an emit method. You would need to compose a QObject instance inside it as a member and use that to emit signals. Something along the lines of myItem.qobject.emit(). Otherwise, you would have to inherit your own completely custom one from QGraphicsObject
Update 1: Addressing your main comment update
Your specific situation is a rectangle with "hot corners". I would see this being a custom QGraphicsItem. You would probably subclass QGraphicsRectItem, and then compose the child hot corner items inside as children items (setParentItem()). Now your rectangle item knows about its children and can act on them directly. You could set the rectangle item to be the sceneEventFilter for the children and handle their events directly. No need to go back up to the scene. Let all this logic live in the class.
Update 2: Addressing your added question #3
Propagating communications up beyond the scene to QWidget's has a couple approaches I can think of:

*

*This is a situation where you can consider if you want to use a QGraphicsObject subclass as your root item, and then compose the rest of your objects as children (the rect, then the hot corners as children of the rect). This would allow the object to emit signals. For clarity they would probably still be connected to the scene, and then the higher order container of the scene would connect to the scene. You would have to choose this approach on a case by case, depending on the complexity of your scene and whether the QGraphicsObject has any performance impact on it. You should probably avoid this if you will have a great number of these instances.

*You could define a callback for your rect class, for which the scene can set. Either something like: graphicsRect.resizedCallback as an attribute, or a setter graphicsRect.setResizedCallback(cbk). In your rect class, you would just call that when appropriate. If the callback it set, it can be used to call something on your scene directly. The rect class still has no knowledge of that logic. It just calls a callback.

Those are just some suggestions. I'm sure there are other ways.

A: I suggest B unless you have relatively few QGraphicsItems. I believe QGraphicsItems are not QObjects because there is a certain amount of overhead associated with QObjects. The QGraphicsView framework was designed to allow fast insertion and deletion of many (e.g., thousands) QGraphicsItems into a scene, so a lighter-weight approach was preferred.
I would look to the concept of parenting in QGraphicsItems. QGraphicsItems can have parents and children, and this has several effects similar to parenting amongst QObjects. For example, if you move a parent QGraphicsItem, its children will move with it, and if you delete a parent, its children will be deleted. You can access a QGraphicsItem's parent using QGraphicsItem::parentItem(), and children using QGraphicsItem::childItems(). So, you can easily access sibling items like this:
QList<QGraphicsItem *> mySiblings = this->parentItem()->childItems();

Note that mySiblings includes this.


text:
Q: How to resize a widget so it size is fit to its text in kivy When I add a widget, namely Label, sometimes its size cannot fit it's text height. Changing its height manually doesn't helped because i can type a text so its height will exceed the label's height. Here is the example of the code
.py file
#testing.py
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.button import Button
import random
import GlobalVariable
from GlobalVariable import *
import time

class ScreenOne(Screen):
    pass

class WindowManager(ScreenManager):
    pass

kv = Builder.load_file("testing.kv")

class testing(App):
    def build(self):
        return kv

if __name__ == "__main__":
    testing().run()

.kv file
#testing.kv
WindowManager:
    ScreenOne:

<ScreenOne>:
    ScrollView:
        size: self.size
        GridLayout:
            size_hint_y: None
            size: root.height, root.width
            cols: 2
            Label:
                text: "boom\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nboom"
            Label:
                text: "boom\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nboom"
            Label:
                text: "boom\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nboom"
            Label:
                text: "boom\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nboom"
            Label:
                text: "boom\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nboom"
            Label:
                text: "boom\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nboom"

When you run the code, you will see that there is text that exceed it's label height. I expect to make those label always fit the text (not shorter but also not longer than its text) whatever the text is, and is scrollable. Any help or suggestion is appreciated. Thanks.

A: Use these properties for your Label
Label:
    text_size: self.width, None
    size_hint: 1, None
    height: self.texture_size[1]


text:
Q: Как обыграть z-index Нужно что бы при заходе на .wrapper линия ( #main-top .line ) оказалась под ним и не виднелась. Задавать background нельзя. Нужно для мобильной версии, что бы при уменьшении экрана линия не заходила на контент.

.wrapper {
    position: relative;
    box-sizing: border-box;
    display:block;
    margin: 0 auto;
    width: 100px;
     height: 100px;
    max-width: 1300px;
    z-index: 100;
    margin-left:-0px;
    border:1px solid black;
}
#main-top {
    position: relative;
    margin-bottom: 180px;
    margin-top: 90px;
}

#main-top .line {
    width: 150px;
    height: 1px;
    display: block;
    position: absolute;
    z-index:1;
    top: 5px;
    left: 0;
    background: rgba(178,37,63,1);
    background: -moz-linear-gradient(left, rgba(178,37,63,1) 0%, rgba(219,59,56,1) 100%);
    background: -webkit-gradient(left top, right top, color-stop(0%, rgba(178,37,63,1)), color-stop(100%, rgba(219,59,56,1)));
    background: -webkit-linear-gradient(left, rgba(178,37,63,1) 0%, rgba(219,59,56,1) 100%);
    background: -o-linear-gradient(left, rgba(178,37,63,1) 0%, rgba(219,59,56,1) 100%);
    background: -ms-linear-gradient(left, rgba(178,37,63,1) 0%, rgba(219,59,56,1) 100%);
    background: linear-gradient(to right, rgba(178,37,63,1) 0%, rgba(219,59,56,1) 100%);

A: @media screen and (max-width: npx) { // где n - длина wrapper
  #main-top .line {
    display: none;
  }
}


text:
Q: racecondition between put_page and pci_unmap_sg I am working on a device driver that includes dma. If I just use get_user_pages_fast and put_page everything is working. As soon as I add calls to pci_(un)map_sg it seems to become racy.
After the test program finishes I sometimes get a BUG, however i do not always get the BUG.
The BUG reads:
[ 7202.183324] BUG: Bad page state in process dma  pfn:f20ea8
[ 7202.183327] page:ffffea003c83aa00 count:0 mapcount:-30705 mapping:          (null) index:0xc0054000d3431e41
[ 7202.183329] page flags: 0x2ffff000008000c(referenced|uptodate|swapbacked)

And has the following trace:
[ 7202.183442] Call Trace:
[ 7202.183447]  [<ffffffff8171e0be>] dump_stack+0x45/0x56
[ 7202.183453]  [<ffffffff8171aa88>] bad_page.part.61+0xcf/0xe8
[ 7202.183459]  [<ffffffff81155ce8>] free_pages_prepare+0x148/0x160
[ 7202.183463]  [<ffffffff81156651>] free_hot_cold_page+0x31/0x150
[ 7202.183467]  [<ffffffff811567b6>] free_hot_cold_page_list+0x46/0xa0
[ 7202.183473]  [<ffffffff8115c210>] release_pages+0x80/0x210
[ 7202.183478]  [<ffffffff8118b725>] free_pages_and_swap_cache+0x95/0xb0
[ 7202.183483]  [<ffffffff81174c5c>] tlb_flush_mmu.part.56+0x4c/0x90
[ 7202.183486]  [<ffffffff811757d5>] tlb_finish_mmu+0x55/0x60
[ 7202.183491]  [<ffffffff81180c0b>] exit_mmap+0xcb/0x170
[ 7202.183497]  [<ffffffff810646cc>] mmput+0x5c/0x120
[ 7202.183502]  [<ffffffff81069b1c>] do_exit+0x26c/0xa50
[ 7202.183506]  [<ffffffff811bef1e>] ? ____fput+0xe/0x10
[ 7202.183511]  [<ffffffff8106a37f>] do_group_exit+0x3f/0xa0
[ 7202.183515]  [<ffffffff8106a3f4>] SyS_exit_group+0x14/0x20
[ 7202.183520]  [<ffffffff8172ec2d>] system_call_fastpath+0x1a/0x1f

Are there any additional locks that I have to hold for any of the functions (there is no hint for the pci-dma api, and where I see put_page in other drivers there are no locks near it). Is there another point where I could go wrong?
I currently pass the same pointer to pci_unmap_sg as the one I used for pci_map_sg, which seems ok, after looking at other drivers and use the actual page count rather than the count returned from the mapping for unmapping.
I think I am missing some locking or synchronisation, as this post might hint, however my understanding of linux memory subsystem is to bad to follow.
Also [release_pages](http://lxr.free-electrons.com/source/mm/swap.c#L899) seems to be an alternative, however I see spin_unlock_irqrestore(&zone->lru_lock, flags); in a view paths without a prior lock, do I need to hold the lock before calling this?

A: I initialized the scatter/gather list wrong, I thought calls to sg_set_page would suffice, however an initial call to sg_init_table is needed.
Since I found many drivers NOT doing so, AND ldd3 is not mentioning sg_init_table anywhere, I figured it might be helpful if I leave this here.


text:
Q: how to free vImage buffers after operation completed in IOS I try to make some histogram calculations using vImage buffers in Accelerate framework and I supply camera image as UIimage converted from CVpixelbuffer. Algorithm works with no error however  processed camera image data on the screen is very slow. I read some info in Apple documentation about freeing the buffers when task is completed. I wrote two lines of code after grab the buffer data. However nothing changes. Please see attached screenshot of buffers data after they are freed.SourceBuffer and histogramSourceBuffer are seems not freed. I don't know how a free buffer has to be seen in debugger but mine are shown with height, width and data info. Any recommendation how to free the buffer and how can I ensure it is freed. Many thanks indeed
  if let finalImage =  try? sourceBuffer.createCGImage(format: format) {
            sourceBuffer.free()
            histogramSourceBuffer.free()
            return UIImage(cgImage: finalImage)

A: You need to call free() on the vImage_Buffer.data pointer to free the memory. The struct itself is a different allocation.
The histogram itself is an array of pointers to arrays of vImagePixelCounts.  That should be freed according to how you allocated the arrays of vImagePixelCounts. vImage isn't involved in that part, so it is between you and you.


text:
Q: How can I open a new z shell in a tab and run a command? I'm on macOS which is currently using the zshell.
I would like to run a command in one shell which opens another shell preferably in another tab in the same window and then runs a given command.  For example:
> openTab

would open another tab and run a basic command like ls.
Is this possible to do?
It appears that the open command will open new window, but I want it to be opened as a new tab in the current window.  See here
Osascript appears a bit messy, is there way to do this natively with zshell?

A: You can use AppleScript, via osascript to do exactly that:
function runInNewTab() {
    osascript >/dev/null <<EOF
    tell application "System Events"
    tell process "Terminal" to keystroke "t" using command down
        end tell
    tell application "Terminal" to do script "$*" in front window
EOF
}

Run it like this:
runInNewTab ls -l ~


text:
Q: Custom Errors Work Locally Not Once Deployed On IIS I have the following:
Web.config
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<customErrors mode="On" defaultRedirect="~/Error/ShowError">
  <error redirect="~/Error/ShowError/400" statusCode="400" />
  <error redirect="~/Error/ShowError/401" statusCode="401" />
  <error redirect="~/Error/ShowError/403" statusCode="403" />
  <error redirect="~/Error/ShowError/404" statusCode="404" />
</customErrors>
</system.web>

ErrorController
[AllowAnonymous]
public class ErrorController : Controller
{
    public ViewResult ShowError(int id)
    {
        Response.StatusCode = id;
        switch (id)
        {
            case 400:
                return View("~/Views/Error/400.cshtml");
            case 401:
                return View("~/Views/Error/401.cshtml");
            case 403:
                return View("~/Views/Error/403.cshtml");
            case 404:
                return View("~/Views/Error/404.cshtml");
            default:
                return View("~/Views/Error/404.cshtml");
        }
    }
}

FilterConfig
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        //filters.Add(new HandleErrorAttribute());
    }

Locally everything works fine, I get a custom error page and am happy, however as soon as I deploy the site to my web server, I no longer get my custom error messages and only the generic:

Do I need to add anything specific for the IIS configuration in my online environment?
I've compared the local Web.config with the deployed Web.config and there isn't anything different (that I can see).

A: Your error is overwritten by IIS custom error.
Try:
Response.TrySkipIisCustomErrors = true


text:
Q: Shutdown, suspend require authentication when scheduled in at I'd like to suspend my laptop using at:
echo "systemctl suspend" | at now + 5 minutes

Suspension does not happen, instead I find a mail from at in /var/spool/mail/me:
Failed to set wall message, ignoring: Interactive authentication required.
Failed to suspend system via logind: Interactive authentication required.
Failed to start suspend.target: Interactive authentication required.
See system logs and 'systemctl status suspend.target' for details.

Alright, logind requires authentication when at runs systemctl suspend. This is interesting since when I run systemctl suspend directly, without at, no authentication is required and the machine goes into suspension.
I've made sure that the commands executed with at are run by the same non-root user as the commands run directly using echo "echo $(who) > who.txt" | at now.
Suspecting that authentication is required in at because it runs the commands via /bin/sh (which is an alias for bash), I executed systemctl suspend after starting /bin/sh: Suspending happens immediately without authentication, indicating that the nested shell is not the reason why suspending fails when done with at.
I get the same behavior and very similar mails when doing echo "reboot" | at now and echo "shutdown now" | at now.
My question is: How does logind figure out that it's at that tries to suspend, reboot, or shut down the machine and how can I tell logind that it should allow at to execute those commands without authentication?

I'm on Arch Linux 4.18.1 with at version 3.1.19.

A: Presumably the commands run by at are in a different environment, without access to your tty device and dbus settings and so on.
Systemd has its own version of the at command. You can use it to run your command in an environment that seems to be ok for further systemd commands.
So use the equivalent command:
systemd-run --user --on-active=5min /bin/systemctl suspend

For perfect accuracy in the wait time of 5 minutes, you need to add option --timer-property=AccuracySec=1.