text:
Q: Trying to connect to sqlite file using constructor include ("db.php");
    $db = new CMSDB();
    if ($db->connect_error) {
    die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "INSERT INTO cases (case_id, case_type, priority, postalCode, status, location) VALUES (NULL, 'pending', 'low', 33, 'help', 'singapore')";

        if($db->exec($sql) == TRUE){
            echo "New record created successfully";
        }

        else {
        echo "Error: " . $sql . "<br>" . mysqli_error($db);
        }

//Cant seem to connect to the database with the constructor
//Cant seem to connect to the database with the constructor
//Cant seem to connect to the database with the constructor
    class CMSDB extends SQLite3{
     function __construct(){
      $this->open('DB.sqlite');
    }
 }

This is the Database constructor.


text:
Q: Express/Postgres User registration controller To simplify the situation I'll just post the following controller for an express route which interactions with a Postgres Database. My question is about error handling. If an error occurs it will be caught within the catch clause. But how can I access the errors thrown by the database queries itself. If I make several await several queries and one of them fails I need probably to restore stuff in the database? For example if the insertion of the user in the user table is a success, but the following query of inserting the user in another table fails, I need to delete the user from the user table again. How does one model such flows?
    //
    // Register User
    //
    export const registerUser = async (request, response, next) => {
        try {
          const usersWithSameMail = await client.query(`SELECT * FROM public.users WHERE email = '${user.email}'`);
          if(usersWithSameMail.rows.length > 0){
            return response.status(403).json({"code": "ERROR", "message": "Email is already registered"})
          } else {
            await client.query(`
                INSERT INTO public.users(first_name, last_name, email, password)
                VALUES ('${user.first_name}', '${user.last_name}', '${user.email}', crypt('${user.password}', gen_salt('bf', 8)));
            `);

            // more await statements...

            return response.status(200).json({"code": "INFO", "message": "Verification mail sent to user"});
          }
        } catch (error) {
            return response.status(500).json({"code": "ERROR", "message": "Error occured while registering the user. Please try again."});
        }
    }```

A: based on transaction documentation in node.js you can use rollback
export const registerUser = async (request, response, next) => {
  try {
    let error = null;
    const client; // create a client, connect to the db
    try {
      await client.query("begin");

      await client.query("first query");
      await client.query("second query");
      await client.query("third query");

      await client.query("commit"); //do commit when is finished all queries
    } catch (error) {
      error = error;
      await client.query("rollback");
    } finally {
      client.release(); // close the connection
    }
    if (error) {
      return response.status(500).json({ message: error }); // error message
    }
    return response.status(200).json({ message: "My message" }); // success message
  } catch (err) {
    return response.status(500).json({ message: err });
  }
}

A: You can use middlewares chaining your routes handler. In order to it work, you will have to change  your current working code to use Single-responsibility principle. Do only one responsability per middleware and chain all handlers to work as one.
Lets say you want to insert new user, to perform this operation we should:

*

*lookup if email is unique

*hash password

*Insert new user

*return inserted data in postgres back as a response

Following the middleware chaining we should implement a function for each action and chain each action in route definition:
const postgres = require('../../lib/postgres');
const crypto = require('crypto');

exports.insertedData = (req, res) => {
    res.status(200).json(req.employee);
};

exports.hashPassword = (req, res, next) => {
    crypto.scrypt(req.body.password.toString(), 'salt', 256, (err, derivedKey) => {
        if (err) {
            return res.status(500).json({ errors: [{ location: req.path, msg: 'Could not hash password'}] });
        }
        req.body.kdfResult = derivedKey.toString('hex');
        next();
    });
};

exports.lookupEmailUnique = (req, res, next) => {
    const sql = 'SELECT e.email FROM public.users e WHERE e.email=$1';
    postgres.query(sql, [req.body.email], (err, result) => {
        if (err) {
            return res.status(500).json({ errors: [{ location: req.path, msg: 'Could not query database' }] });
        }
        if (result.rows.length > 0) {
            return response.status(403).json({"code": "ERROR", "message": "Email is already registered"})
        }
        next()
    });
}

exports.insertNewUser = (req, res, next) => {

    const sql = 'INSERT INTO public.users(first_name, last_name, email, password) VALUES ($1,$2,$3,$4} RETURNING *';
    postgres.query(sql, [req.body.first_name, req.body.last_name, req.body.email,  req.body.kdfResult], (err, result) => {
        if (err) {
            return res.status(500).json({ errors: [{ location: req.path, msg: 'Could not query database'}] });
        }
        req.employee = result.rows[0];
        next();
    });
};

here is your route declaration:
const router = require('express').Router();
const userService = require('../controllers/user.controller');

router.post('/register', userService.lookupEmailUnique, userService.hashPassword, userService.insertNewUser, userService.insertedData);

module.exports = router;

Here in routes you are using the middeware to do the chaning, you only pass the control to next middleware if all conditions are met and has full control from database erros.
In my example I do not used the async/await but I can change my example to have a version using async/await.
example middleware with transaction
exports.deletePostagem = async (req, res, next) => {
    try {
        await postgres.query('BEGIN');
        const sql2 = 'UPDATE comentario SET postagem = null WHERE postagem = $1';
        await postgres.query(sql2, [req.params.id]);
        const sql3 = 'DELETE FROM postagem WHERE id = $1';
        await postgres.query(sql3, [req.params.id]);
        await postgres.query('COMMIT');
        res.status(204).json();
        res.end();
    } catch (err) {
        await postgres.query('ROLLBACK');
        return res.status(500).json({ errors: [{msg: 'Could not perform operation' }]})
    }
}

I used this only as an example, but in my projects I always have a middeware for validate/sanitize the data that comes in request before using in database  query prepared statements.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why I get SocketException when downloading a page if I don't open Fiddler? I'm experiencing a weird situation.I have a method that downloads a page like following:
public static bool DownloadPageContent(string url,
                                       out string content,
                                       ref int statusCode,
                                       CookieContainer cookie = null,
                                       int maxAttempt = 1,
                                       Encoding encoding = null)
{
      int i = 0;
      using (var client = new CookieAwareWebClient())
      {
            if (encoding != null)
                client.Encoding = encoding;

            while (i < maxAttempt)
            {
                try
                {
                      i++;
                      if (cookie != null)
                           client.CookieContainer = cookie;
                      client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
                      content = client.DownloadString(url);
                      statusCode = 200;
                      return true;
                 }
                 catch(WebException ex)
                 {
                       /* some error handling code*/
                        _logger.Log(LogLevel.Error, ex);

                  }
                  catch (Exception ex)
                  {
                       _logger.Log(LogLevel.Error, ex);
                  }
            }
            content = "";
            return false;
}

And this is the StackTrace, it happens in line content = client.DownloadString(url):

System.Net.WebException: Can't connect to remote server --->
  System.Net.Sockets.SocketException: An attempt was made to access a
  socket in a way forbidden by its access permissions xxx.xxx.xxx:80]
  System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot,
  SocketAddress socketAddress) +208ı xxx.xxx.xxx:80
         konum: System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
         konum: System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress&
  address, ConnectSocketState state, IAsyncResult asyncResult,
  Exception& exception)
         --- İç özel durum yığını izlemesinin sonu ---
         konum: System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request)
         konum: System.Net.WebClient.DownloadString(Uri address)
         konum: System.Net.WebClient.DownloadString(String address)
         konum: Kokoshome_Product_Downloader.Helpers.SiteHelpers.DownloadPageContent(String
  url, String& content, Int32& statusCode, CookieContainer cookie, Int32
  maxAttempt, Encoding encoding)

The weird thing is, if I open Fiddler2 and run the program, it just works well! This code used to work, and I have been using Fiddler for some time and as far as I remember I haven't changed any options.But now there is something wrong and I can't figure out. So what can be the problem?
Note: I have no other problem about my internet connection.I can connect the internet without Fiddler. And my operation system is Windows 8.1.
UPDATE
I got the same exception when I try to connect MySQL database and the FTP server.And that didn't work with Fiddler either. I have done some research and find the info about the error in Windows Sockets Error Codes

WSAEACCES
  10013
Permission denied. An attempt was made to access a socket in a way
  forbidden by its access permissions. An example is using a broadcast
  address for sendto without broadcast permission being set using
  setsockopt(SO_BROADCAST). Another possible reason for the WSAEACCES
  error is that when the bind function is called (on Windows NT 4.0 with
  SP4 and later), another application, service, or kernel mode driver is
  bound to the same address with exclusive access. Such exclusive access
  is a new feature of Windows NT 4.0 with SP4 and later, and is
  implemented by using the SO_EXCLUSIVEADDRUSE option.

But I still have no idea how to fix it.

A: In virtually all cases, this means that your Firewall is blocking your program's access to the network. When you use Fiddler, the request bypasses the Firewall on the way to Fiddler, and then bypasses the Firewall because you have a Firewall exemption allowing Fiddler access to the Internet.


text:
Q: tkinter: Making a 3x3 grid with an image I have these lines of code:
def initialize_board(self):
    for i in range(2):
        self.canvas.create_line((i + 1) * size / 3, 0, (i + 1) * size / 3, size)

    for i in range(2):
        self.canvas.create_line(0, (i + 1) * size / 3, size, (i + 1) * size / 3)

This makes two vertical lines and two horizontal lines.
But I want to replace it with a 3x3 grid of an image of a square to represent the same thing. I'm making a tic tac toe game for reference.
This is the image I want to use:
self.empty_image = PhotoImage(file = 'book/pybook/image/empty.gif')

Can anyone help me?

A: If you want to make a tic tac toe game you would be better off creating a 3x3 grid of buttons, then displaying the image of the X/O on the button.
Either way, your best bet is to create the widget and then call it onto the canvas with the grid method.
See Python grid() method in Tkinter.

A: To display images on a Canvas you need to create a separate Canvas image object for each one (in addition to a BitmapImage or Photoimage widget). Laying them out in a grid can easily be accomplish via nested for loops — one iterating each row and the other each column in a row.
Note how the integer ID number of the image object that's returned from each Canvas.create_image() call gets stored in a list-of-lists named self.board. Saving them this way will allow the image attribute of the associated Canvas image object to be changed later as the game is being played (via the itemconfigure() Canvas graphical object method).
Below is an example of implementing it as described.
import tkinter as tk
WHITE = '#ffffff'

class Game:
    EMPTY_CELL_IMAGE_FILE_PATH = './ttt_empty.gif'

    def __init__(self, parent):
        self.empty_cell_image = tk.PhotoImage(file=self.EMPTY_CELL_IMAGE_FILE_PATH)
        self.width = 3 * self.empty_cell_image.width()
        self.height = 3 * self.empty_cell_image.height()
        self.canvas = tk.Canvas(parent, width=self.width, height=self.height,
                                background=WHITE)
        self.canvas.pack()
        self.initialize_board()

    def initialize_board(self):
        self.board = [[None for _ in range(3)] for _ in range(3)]  # Pre-allocate.
        width, height = self.empty_cell_image.width(), self.empty_cell_image.height()
        empty_cell_image = self.empty_cell_image
        for i in range(3):
            for j in range(3):
                self.board[i][j] = self.canvas.create_image(i*width, j*height,
                                                            anchor='nw',
                                                            image=empty_cell_image)

if __name__ == '__main__':
    root = tk.Tk()
    root.title('Tic-Tac-Toe')
    game = Game(root)
    root.mainloop()

Result:


text:
Q: SQL Developer SQL Tuning Advisor not all variables bound I'm trying to use the SQL tuning advisor with SQL Developer (versions 4.1.3.20 and 17.2.0.188).  Queries using more than one instance of a bind variable, for example:
select * from dual where :one = :one;

are causing an error in the SQL Tuning Advisor:
-------------------------------------------------------------------------------
ERRORS SECTION
-------------------------------------------------------------------------------
- ORA-01008: not all variables bound

-------------------------------------------------------------------------------

Is there a workaround or some other method to get the same SQL tuning info for queries that have multiple instances of one or more bind variables?

A: Basically, the Tuning Advisor binds by position (not by name). So the workaround would be to rename all the repeated variable instances. Adding a numbered suffix would be enough. In your example, you would have to name your variables :one and :one_1.
select * from dual where :one = :one_1;

I know, it's not ideal, but it should work.

A: Not sure why you want to use ":one = :one", you can replace it as "1 = 1", or add one more variable assigned by the same value, select * from dual where :one = :two;


text:
Q: Create a set of android API objects I need to create a set of android objects (BluetoothDevice objects). Of course, I chose a Set because I don't want any duplicate in my Collection.
My problem is the following :
When I do a bluetooth discovery in Android I receive twice the same device (for e.g. device WINIE7, with mac 80:22:00:22:00), and the references are not the same, so both of them are added in the Set.
Would it be possible to create a kind of "Comparator" to my Set, which would tell to compare the mac addresses ?
Thanks.

A: Override the equals method of your BluetoothDevice object to return true if the hashes are equal. Also override the hashCode method to comply with its specification, see this question.


text:
Q: How to position two images side by side in svg I would like to position two loaded images side by side in svg without absolute position.
I tried the position with help of an container and float: left or display: flex. But it doens´t work.
Here is my codepen: http://codepen.io/anon/pen/LWeBRv
Thanks in advance.

A: Adjust the width of the first image, and they will fit ok:

#iconOne {
  width: 120px;
}
 <svg width="200" height="200">
       <g>
            <image id="iconOne" width="30" height="30" xlink:href="iconOne.svg" />
            <image id="iconTwo" width="50" height="30" xlink:href="iconTwo.svg" />
        </g>
    </svg>

Otherwise, if you want to use standard HTML positioning, you must (as far as I know) rely on this, I mean, make separate HTML entities:

.image {
  width: 70px;
}
<svg class="image">
            <image id="iconOne" width="30" height="30" xlink:href="iconOne.svg" />
    </svg>
<svg class="image">
            <image id="iconTwo" width="50" height="30" xlink:href="iconTwo.svg" />
    </svg>
<svg class="image">
         <image id="iconThree" width="60" height="30" xlink:href="iconTwo.svg" />
    </svg>


text:
Q: Spreadsheets on Shared Drive Sometimes Revert Cells Back to Old Values Currently experiencing an issue with our shared drive giving us old/deleted values back into our spreadsheets.
Example: One user has removed an email address from a spreadsheet but that same email address has reappeared the day after.
We access our shared drive via OneDrive so no on-site shared drive.
Not sure where to start with troubleshooting. All user accounts seem to be working fine on OneDrive and the spreadsheets are being synced. I'm thinking maybe it's a OneDrive issue but not sure where to start with that.
Anyone experienced similar issues?
Thanks.

A: I have not personally done this, but from a pure file management point of view can see how this happens if two users have the same workbook open, makes changes and save. Most basic file systems do not handle conflicting changes out of the box (other than overwrite, skip or rename). At best something like dropbox or onedrive will keep a file history or backup (although both of these do support co-authoring in some way... read on).
To handle concurrent updates, the software editing the file must handle or be aware of the multi-user access. Something like google sheets does this out of the box. In Excel you must specifically enable the sharing features. See this article https://www.ablebits.com/office-addins-blog/2017/08/02/excel-shared-workbook-share-file-multiple-users/.
The first part of the article deals with old school sharing via a network drive. Near the end it addresses sharing via onedrive. I guess (and hope) that you must specifically share the file from within Excel. Simply copying the file to onedrive doesn't enable the internal multi-user "track changes" required.


text:
Q: Why would app crash if delegate uses assign instead of weak? I have seen report that if a delegate uses assign instead of weak, the app crashes.  Why?
Example: RestKit

A: With ARC a weak ivar will be automatically set to nil when the ivar object is deallocated.  That means that if your delegate is destroyed and you try to message the delegate you'll just message nil, which has no effect.  If the delegate ivar was merely assign then you would message some chunk of memory that no longer contained a valid object.

A: The only difference between assign and weak is that weak does extra work to avoid some common crashing bugs. The drawback, however, is that assign has much better performance than weak.
Specifically, when an object is released, any weak property pointing to it will be set to nil. Any assign property pointing to it will be left pointing at the object that is no-longer used.
And some other object is likely to be placed at the same location in memory as the old object, so suddenly instead of an instance of MyDelegate you might have a UIImage object in the same location in memory, or perhaps a float value, or anything at all.
So you should always use weak, for everything. But if you run into performance problems, check if weak is the cause, and consider switching to assign after learning how to avoid those crashing bugs.
For a delegate you should pretty much always use weak. Normally you'd only pick assign if you are dealing with millions of objects. Typically that doesn't happen with delegates.


text:
Q: What is the difference between AF_INET and PF_INET in socket programming? What is the difference between AF_INET and PF_INET in socket programming?
I'm confused between using AF_INET and PF_INET in socket() and bind().
Also, how to give ip-address in sin_addr field?

A: I found in Linux kernel source code that PF_INET and AF_INET are the same.
The following code is from file include/linux/socket.h, line 204 of Linux kernel 3.2.21 tree.
/* Protocol families, same as address families. */
...
#define PF_INET     AF_INET

A: AF_INET = Address Format, Internet = IP Addresses
PF_INET = Packet Format, Internet = IP, TCP/IP or UDP/IP
AF_INET is the address family that is used for the socket you're creating (in this case an Internet Protocol address). The Linux kernel, for example, supports 29 other address families such as UNIX sockets and IPX, and also communications with IRDA and Bluetooth (AF_IRDA and AF_BLUETOOTH, but it is doubtful you'll use these at such a low level).
For the most part sticking with AF_INET for socket programming over a network is the safest option.
Meaning, AF_INET refers to addresses from the internet, IP addresses specifically.
PF_INET refers to anything in the protocol, usually sockets/ports.

A: Checking the header file solve's the problem.
One can check for there system compiler.
For my system , AF_INET == PF_INET
AF == Address Family  And PF == Protocol Family
Protocol families, same as address families.

A: *

*AF = Address Family

*PF = Protocol Family

Meaning, AF_INET refers to addresses from the internet, IP addresses specifically. PF_INET refers to anything in the protocol, usually sockets/ports.
Consider reading the man pages for socket(2) and bind(2). For the sin_addr field, just do something like the following to set it:
struct sockaddr_in addr;
inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);

A: There are situations where it matters.
If you pass AF_INET to socket() in Cygwin, your socket may or may not be randomly reset. Passing PF_INET ensures that the connection works right.
Cygwin is self-admittedly a huge mess for socket programming, but it is a real world case where AF_INET and PF_INET are not identical.

A: Beej's famous network programming guide gives a nice explanation:

In some documentation, you'll see mention of a mystical "PF_INET".
  This is a weird etherial beast that is rarely seen in nature, but I
  might as well clarify it a bit here. Once a long time ago, it was
  thought that maybe a address family (what the "AF" in "AF_INET" stands
  for) might support several protocols that were referenced by their
  protocol family (what the "PF" in "PF_INET" stands for).
  That didn't happen. Oh well. So the correct thing to do is to use AF_INET in your
  struct sockaddr_in and PF_INET in your call to socket(). But
  practically speaking, you can use AF_INET everywhere. And, since
  that's what W. Richard Stevens does in his book, that's what I'll do
  here.

A: In fact, AF_ and PF_ are the same thing. There are some words on Wikipedia will clear your confusion

The original design concept of the socket interface distinguished between protocol types (families) and the specific address types that each may use. It was envisioned that a protocol family may have several address types. Address types were defined by additional symbolic constants, using the prefix AF_ instead of PF_. The AF_-identifiers are intended for all data structures that specifically deal with the address type and not the protocol family. However, this concept of separation of protocol and address type has not found implementation support and the AF_-constants were simply defined by the corresponding protocol identifier, rendering the distinction between AF_ versus PF_ constants a technical argument of no significant practical consequence. Indeed, much confusion exists in the proper usage of both forms.


text:
Q: Can't get Rails Action Text in console When I save a model with action text, the content saves to the database, but it's not accessible through the console.
I have a Section model with has_rich_text :content
When I try to create a new record, it creates a rich text association, but the body is always blank.
section.content = '
Hello world
'
section.save
=> true
section.content
=> #<ActionText::RichText id: 6, name: "content", body: #<ActionText::Content " ">, record_type: "Section", record_id: 2, created_at: "2020-05-07 13:49:58", updated_at: "2020-05-07 14:00:36">
section.content.to_s
=> " "
section.content.body
=> #<ActionText::Content " ">

It properly sets in the database, and the value is being accessed by my code in a serializer and sending the proper content. However, I would like to gain access to this content through the console.

A: It seems like there is a problem with ActionText when using API only setup.
See: https://github.com/rails/rails/issues/39266
The following code returns " " which should not be the case.
section.content.to_s
 => " "

section.content.body.to_s
 => " "

As an alternative, you can use the following:
section.content.body.to_html
 => "
Hello world
"

EDIT:
I just noticed that the OP of this question and OP of the issue in Rails repository is the same. I will just put the answer to this for visibility as I encountered this problem myself and took me a while to found the issue in the Rails repository.


text:
Q: Connecting records [SQL] I have a table "Table"
id_document , merge , merge_order ,name

records with same merge , need to by under
merge_order is specific order(in one merge)
Etc.
ID123456 , 400 , 1 , Coral
ID654321 , 200 , 2 , Deril
ID654322 , 400 , 2 , Rick
ID654323 , 200 , 1 , Maggie

Output in select will be, for example:
ID654323 , 200 , 1 , Maggie
ID654321 , 200 , 2 , Deril
ID123456 , 400 , 1 , Coral
ID654322 , 400 , 2 , Rick

Here is my select
SELECT
   MERGE_ORDER,ID_DOCUMENT,NAME,MERGE
FROM(select * from Table order by name)-trying to order table before main select
WHERE MERGE IS NOT NULL
CONNECT BY NOCYCLE PRIOR MERGE = MERGE
order SIBLINGS by MERGE_ORDER,NAME)

The select works, but now I need to order the result by name, but save records connection (merge).
I need to order rows where merge_order = 1. But under ordered rows, put second record with same merge, and where merge_order = 2.
ID654323 , 200 , 1 , Maggie
ID123456 , 400 , 1 , Coral

A: I would do this with a simple self join:
select t1.*
from table t1
inner join table t2 on t1.merge=t2.merge  --self join
where t2.merge_order=1   --relate the 1st of each merge to each record in the merge
order by t2.name ASC, t1.merge_order ASC   --the name in t2 will be the name from the 1st record, see where clause

You may be able to do it with connect by as well, however, you have not updated your product tags and mysql does not have connect by clause. So, I have not considered connect by clause as valid solution.


text:
Q: Python Opencv, don't put circle on the video I wrote the following script with OpenCV
import cv2
import numpy as np

cap = cv2.VideoCapture(0)
ix, iy = -1, -1

def draw_circle(event, x, y, flags, param):
    global ix
    global iy
    ix,iy = x,y

    if event == cv2.EVENT_LBUTTONDOWN:
        cv2.circle(img, (200, 399), 10, (0, 255, 255), -1)
        print("Text Put")
    elif event == cv2.EVENT_LBUTTONUP:
        print("EVENT_LBUTTONUP")
    elif event == cv2.EVENT_RBUTTONDOWN:
        print("Appuyé Droite")
    elif event == cv2.EVENT_RBUTTONUP:
        print("EVENT_RBUTTONUP")
    elif event == cv2.EVENT_MOUSEMOVE:
        print("Move on", x, y)

while(1):
    ret, img = cap.read()
    cv2.setMouseCallback('image', draw_circle)
    cv2.imshow('image', img)
    if cv2.waitKey(20) & 0xFF == 27:
        break

cv2.destroyAllWindows()

But when I do a right button click, no circle appears on the display. What is wrong with my code ?

A: This code snippet may help you get started:
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
ix, iy = -1,-1

def mouseCallback(event,x,y,flags,param):
    global ix
    global iy

    if event == cv2.EVENT_LBUTTONDOWN:
        ix = x # saves the position of the last click
        iy = y

    elif event == cv2.EVENT_LBUTTONUP:
        print("EVENT_LBUTTONUP")

    elif event == cv2.EVENT_RBUTTONDOWN:
        print("Appuyé Droite")

    elif event == cv2.EVENT_RBUTTONUP:
        print("EVENT_RBUTTONUP")

def draw_circle_onscreen(frame, x,y):
    cv2.circle(frame, (x,y), 10,(0, 0, 255),-1)

cv2.namedWindow('frame')
cv2.setMouseCallback('frame',mouseCallback) # mouse callback has to be set only once

while(1):
    ret, img = cap.read()
    draw_circle_onscreen(img,ix,iy) # draws circle on screen
    cv2.imshow('frame',img)
    if cv2.waitKey(20) & 0xFF == 27:
        break

cv2.destroyAllWindows()


text:
Q: Authenticate Microsoft Teams Tab against external API I'm working on a Teams Tab that requires access to my own external API, however I'm having difficulty understanding the best way to achieve authentication in the context of a Tab.
My API uses the standard OAuth2.0 workflow for getting an access token, but from the Teams Tab context it's unclear where I can safely store the access token after completing the OAuth flow. Also, I need to safely store the client secret for my API so that it's not visible in the client-side code.
So far I've tried using ADAL.js and the examples in https://github.com/OfficeDev/microsoft-teams-sample-complete-node without any luck.
I'm assuming I need to authenticate my API through the Azure AD but I'm unable to find where I'd register the my API's client id/client secret to be used by the above libraries. Is there a standard pattern used by Teams developers to safely + securely handle this type of authentication?


text:
Q: What's the large version of the word "cookie"? So the word "cookie" derives from the Dutch "koekje" and points to a specific kind of small, one-person sized sweet baked good. But in Dutch the word "koekje" is the small-word version of the word "koek", which can refer to a much larger block of sweets.
For example, I made one yesterday which weighs around 1kg. It doesn't seem to be a cake or pie or any kind of pastry, as it's just a large, tough, crispy block of chocolate and grains.
So what would I call the whole thing in English?

A:
So the word "cookie" derives from the Dutch "koekje" and points to a specific kind of small, one-person sized sweet baked good. But in Dutch the word "koekje" is the small-word version of the word "koek", which can refer to a much larger block of sweets.The culinary sense is supported by the etymology of cookie, where "Dutch koekje" is a "diminutive of koek cake" (from OED Online).

It really does not matter what your cake or cookie looked like or how big it is. "Koek" is the US origin of "cookie"
Koken = to cook. Koek - a cake, i.e. that which is cooked - koekje - the small and likeable thing that is cooked, -> cookie
OED

Etymology: probably < Dutch koekje /ˈkuːkjə/ diminutive of koek cake: this is apparently certain for U.S.; but for Scotland historical evidence has not been found.

It is worth noting that British English uses "biscuit" - from the French "cooked twice" (hence the idea of crispness of a cookie/biscuit), and that (the consistency and method of cooking) is what distinguishes a cake from a biscuit/cookie.
For the legal difference between cakes and biscuits, the leading case on the borderline is that concerning Jaffa cakes: United Biscuits (LON/91/0160). https://en.wikipedia.org/wiki/Jaffa_Cakes

A: In culinary uses, depending on the region of use (deviating in Scotland, where a 'cookie' is a type of bun, and in the UK, where what is called a 'cookie' in the US is called a 'biscuit'), a cookie is a usually a type of cake, distinguished from other types of cake by being small, flat, crisp, dry and sometimes sweet. As the core definition ('a little cake') suggests, in cookery the correct term for an oversized 'cookie' is cake. The type of cake is dry, sweet, flat, and crisp, but not small.
The culinary sense is supported by the etymology of cookie, where "Dutch koekje" is a "diminutive of koek cake" (from OED Online).

cook·ie also cook·y  (ko͝ok′ē)
  1. A small, usually flat and crisp cake made from sweetened dough.

[cookie. (n.d.) American Heritage® Dictionary of the English Language, Fifth Edition. (2011). Retrieved December 13 2015 from http://www.thefreedictionary.com/cookie .]

cookie (ˈkʊkɪ) or cooky
  1. (Cookery) US and Canadian a small flat dry sweet or plain cake of many varieties, baked from a dough. Also called (in Britain and certain other countries): biscuit
  2. (Cookery) a Scot word for bun

[cookie. (n.d.) Collins English Dictionary – Complete and Unabridged. (1991, 1994, 1998, 2000, 2003). Retrieved December 13 2015 from http://www.thefreedictionary.com/cookie .]

cook•ie or cook•y (ˈkʊk i)
  1. a small, flat, sweetened cake, often round, made from stiff dough baked on a large, flat pan (cook′ie sheet`).

[cookie. (n.d.) Random House Kernerman Webster's College Dictionary. (2010). Retrieved December 13 2015 from http://www.thefreedictionary.com/cookie .]

cookie, n.
  Chiefly Sc. and N. Amer.
  1. In Scotland the usual name for a baker's plain bun; in U.S. usually a small flat sweet cake (a biscuit in U.K.), but locally a name for small cakes of various form with or without sweetening. Also S. Afr. and Canad.

["cookie, n.". OED Online. December 2015. Oxford University Press. http://www.oed.com/view/Entry/40961?redirectedFrom=cookie (accessed December 13, 2015).]

A: How about Pizookie?
[Urban Dictionary]
The word itself is a portmanteau of pizza and cookie and pizookie is apparently a popular dessert in the US.


text:
Q: How to display image on google search results - in the left side of the screen hello, as you can see, in the left side of the screen there are some images, after searching on google. How can this be done in code?

A: You should try this example of structured-data/recipe, see this LINK
<html>
  <head>
    <title>Party Coffee Cake</title>
    <script type="application/ld+json">
    {
      "@context": "https://schema.org/",
      "@type": "Recipe",
      "name": "Party Coffee Cake",
      "image": [
        "https://example.com/photos/1x1/photo.jpg",
        "https://example.com/photos/4x3/photo.jpg",
        "https://example.com/photos/16x9/photo.jpg"
      ],
      "author": {
        "@type": "Person",
        "name": "Mary Stone"
      },
      "datePublished": "2018-03-10",
      "description": "This coffee cake is awesome and perfect for parties.",
      "prepTime": "PT20M",
      "cookTime": "PT30M",
      "totalTime": "PT50M",
      "keywords": "cake for a party, coffee",
      "recipeYield": "10",
      "recipeCategory": "Dessert",
      "recipeCuisine": "American",
      "nutrition": {
        "@type": "NutritionInformation",
        "calories": "270 calories"
      },
      "recipeIngredient": [
        "2 cups of flour",
        "3/4 cup white sugar",
        "2 teaspoons baking powder",
        "1/2 teaspoon salt",
        "1/2 cup butter",
        "2 eggs",
        "3/4 cup milk"
        ],
      "recipeInstructions": [
        {
          "@type": "HowToStep",
          "name": "Preheat",
          "text": "Preheat the oven to 350 degrees F. Grease and flour a 9x9 inch pan.",
          "url": "https://example.com/party-coffee-cake#step1",
          "image": "https://example.com/photos/party-coffee-cake/step1.jpg"
        },
        {
          "@type": "HowToStep",
          "name": "Mix dry ingredients",
          "text": "In a large bowl, combine flour, sugar, baking powder, and salt.",
          "url": "https://example.com/party-coffee-cake#step2",
          "image": "https://example.com/photos/party-coffee-cake/step2.jpg"
        },
        {
          "@type": "HowToStep",
          "name": "Add wet ingredients",
          "text": "Mix in the butter, eggs, and milk.",
          "url": "https://example.com/party-coffee-cake#step3",
          "image": "https://example.com/photos/party-coffee-cake/step3.jpg"
        },
        {
          "@type": "HowToStep",
          "name": "Spread into pan",
          "text": "Spread into the prepared pan.",
          "url": "https://example.com/party-coffee-cake#step4",
          "image": "https://example.com/photos/party-coffee-cake/step4.jpg"
        },
        {
          "@type": "HowToStep",
          "name": "Bake",
          "text": "Bake for 30 to 35 minutes, or until firm.",
          "url": "https://example.com/party-coffee-cake#step5",
          "image": "https://example.com/photos/party-coffee-cake/step5.jpg"
        },
        {
          "@type": "HowToStep",
          "name": "Enjoy",
          "text": "Allow to cool and enjoy.",
          "url": "https://example.com/party-coffee-cake#step6",
          "image": "https://example.com/photos/party-coffee-cake/step6.jpg"
        }
      ],
      "aggregateRating": {
        "@type": "AggregateRating",
        "ratingValue": "5",
        "ratingCount": "18"
      },
      "video": {
        "@type": "VideoObject",
        "name": "How to make a Party Coffee Cake",
        "description": "This is how you make a Party Coffee Cake.",
        "thumbnailUrl": [
          "https://example.com/photos/1x1/photo.jpg",
          "https://example.com/photos/4x3/photo.jpg",
          "https://example.com/photos/16x9/photo.jpg"
         ],
        "contentUrl": "http://www.example.com/video123.mp4",
        "embedUrl": "http://www.example.com/videoplayer?video=123",
        "uploadDate": "2018-02-05T08:00:00+08:00",
        "duration": "PT1M33S",
        "interactionStatistic": {
          "@type": "InteractionCounter",
          "interactionType": { "@type": "WatchAction" },
          "userInteractionCount": 2347
        },
        "expires": "2019-02-05T08:00:00+08:00"
      }
    }
    </script>
  </head>
  <body>
  </body>
</html>


text:
Q: share data between fragments using ModelFactory I've successfully implemented repository based MVVM. However I need to pass a class object between fragments. I've implemented a sharedViewModel between multiple fragments but the set value always gives null. I know this is due to me not passing the activity context to the initialization of the viewmodels in fragments. I am working with ModelFactory to make instances of my viewmodel yet I can't figure out a way to give 'applicationActivity()' .
Here's my modelFactory:
class MyViewModelFactory  constructor(private val repository: MyRepository): ViewModelProvider.Factory {

override fun <T : ViewModel> create(modelClass: Class<T>): T {
    return if (modelClass.isAssignableFrom(MyOwnViewModel::class.java)) {
        MyOwnViewModel(this.repository) as T
    } else {
        throw IllegalArgumentException("ViewModel Not Found")
    }
}

and this is how I intialize my viewmodel:
  viewModel=ViewModelProvider(this, MyViewModelFactory(
        MyRepository(MyServices() ) )).get(MyOwnViewModel::class.java)

fetching data and everything else works, but I need to be able to share data between fragments and i can't do that with this architecture. I'm not using dagger or Hilt.
Thank you for any pointers.

A: You can also write viewmodelfactory this way
class MyViewModelFactory(internal var viewModel: ViewModel) : ViewModelProvider.Factory {
override fun  create(modelClass: Class): T {
return viewModel as T
}
}
And for share data between fragment you can use bundle

A: You can use by activityViewModels() and pass the factory
private val myViewModel: MyViewModel by activityViewModels(factoryProducer = {
    MyViewModelFactory(<your respository instance>)
})

It would be good idea to get your repository instance from a singleton or from a field in Application class. If you choose to get from an Application class you can do it like this;
class MyApp: Application() {

    val service by lazy { MyService() }
    val repository by lazy { MyRepository(service) }
}

by defining them lazy, it ensures that they are not initialized until its necessary
With your application class, your viewmodel call should look like this
private val myViewModel: MyViewModel by activityViewModels(factoryProducer = {
    MyViewModelFactory((activity?.application as MyApp).repository)
})


text:
Q: Using malloc and free in C/C++ and getting error HEAP CORRUPTION DETECTED I am having a problem when free(position) is run.
void printTree(nodeT node, int hieght)
{
    int *position;
    position = (int*)malloc(hieght * sizeof(int*));
    for (int i = 0; i <= hieght; i++)
    {
        position[i] = 0;
    }
    BOOLEAN DONE = FALSE;
    while (DONE == FALSE)
    {
        printMoveDown(&node, position);
        printLEAFNode(&node, position);
        DONE = printMoveUp(&node, position);
        printSingleKey(&node, position);
    }
    free(position);
    position = NULL;
}

The full error message I get from VS2010 is HEAP CORRUPTION DETECTED: after normal block (#64) at 0x00031390. CRT detected that the application wrote to memory after end of heap.
The debugger says the problem occurs while at in: dbgheap.c
extern "C" void __cdecl _free_dbg_nolock
line 1376:  if (!CheckBytes(pbData(pHead) + pHead->nDataSize, _bNoMansLandFill, nNoMansLandSize))
                if (pHead->szFileName) {..}
                else { this is where the program stops }

I tried setting up the same situation with less stuff going on to see if I could narrow the problem down.
void function (int y)
{
    int *x;
    x = (int*)malloc(y * sizeof(int*));
    free(x);
    x = NULL;
}

This is the same thing as above without the for loop and while loop. This works. Removing the for loop is what made it work. I don't know why. I looked up what the CRT was but it was all pretty new concepts to me and I assume that I can solve this problem without knowing about these CRTs.
The for loop assigns values to the memory allocated for position, beyond that I can't think of why this causes a problem.... actually now that I think about it. I changed the loop to be height + 1 which fixed the problem.

A: It should be:
position = malloc(hieght * sizeof(int));

or:
position = malloc(hieght * sizeof *position);

It's undefined behavior the way you have it.  You're probably just getting lucky because int and int* are the same size.
And the typical correct way to write the loop is:
for (int i = 0; i < hieght; i++)
{
    position[i] = 0;
}

You can also use calloc here:
position = calloc(hieght, sizeof *position);

and the memory will be zeroed for you, so you don't have to loop.
Also, if this is really C, the cast is superfluous.

A: I think the problem in the loop is the <= which really should be <.
Consequently the loop goes round one time too many and corrupts the next item on the heap!


text:
Q: can you tell me the way of finding the location of any post of some other user in facebook? can you tell me the way of finding the location of any post of some other user in facebook???

A: Go to there personal account. there you will get all there Posts


text:
Q: Converting from FSDataInputStream to FileInputStream I'm kind of new to Hadoop HDFS and quite rusty with Java and I need some help. I'm trying to read a file from HDFS and calculate the MD5 hash of this file. The general Hadoop configuration is as below.
private FSDataInputStream hdfsDIS;
private FileInputStream FinputStream;
private FileSystem hdfs;
private Configuration myConfig;

myConfig.addResource("/HADOOP_HOME/conf/core-site.xml");
myConfig.addResource("/HADOOP_HOME/conf/hdfs-site.xml");

hdfs = FileSystem.get(new URI("hdfs://NodeName:54310"), myConfig);

hdfsDIS = hdfs.open(hdfsFilePath);

The function hdfs.open(hdfsFilePath) returns an FSDataInputStream
The problem is that i can only get an FSDataInputStream out of the HDFS, but i'd like to get a FileInputStream out of it.
The code below performs the hashing part and is adapted from something i found somewhere on StackOverflow (can't seem to find the link to it now).
FileInputStream FinputStream = hdfsDIS;   // <---This is where the problem is
MessageDigest md;
    try {
        md = MessageDigest.getInstance("MD5");
        FileChannel channel = FinputStream.getChannel();
        ByteBuffer buff = ByteBuffer.allocate(2048);

        while(channel.read(buff) != -1){
            buff.flip();
            md.update(buff);
            buff.clear();
        }
        byte[] hashValue = md.digest();

        return toHex(hashValue);
    }
    catch (NoSuchAlgorithmException e){
        return null;
    }
    catch (IOException e){
        return null;
    }

The reason why i need a FileInputStream is because the code that does the hashing uses a FileChannel which supposedly increases the efficiency of reading the data from the file.
Could someone show me how i could convert the FSDataInputStream into a FileInputStream

A: Use it as an InputStream:
MessageDigest md;
try {
    md = MessageDigest.getInstance("MD5");
    byte[] buff = new byte[2048];
    int count;

    while((count = hdfsDIS.read(buff)) != -1){
        md.update(buff, 0, count);
    }
    byte[] hashValue = md.digest();

    return toHex(hashValue);
}
catch (NoSuchAlgorithmException e){
    return null;
}
catch (IOException e){
    return null;
}

the code that does the hashing uses a FileChannel which supposedly increases the efficiency of reading the data from the file

Not in this case. It only improves efficiency if you're just copying the data to another channel, if you use a DirectByteBuffer. If you're processing the data, as here, it doesn't make any difference. A read is still a read.

A: You can use the FSDataInputStream as just a regular InputStream, and pass that to Channels.newChannel to get back a ReadableByteChannel instead of a FileChannel. Here's an updated version:
InputStream inputStream = hdfsDIS;
MessageDigest md;
try {
    md = MessageDigest.getInstance("MD5");
    ReadableByteChannel channel = Channels.newChannel(inputStream);
    ByteBuffer buff = ByteBuffer.allocate(2048);

    while(channel.read(buff) != -1){
        buff.flip();
        md.update(buff);
        buff.clear();
    }
    byte[] hashValue = md.digest();

    return toHex(hashValue);
}
catch (NoSuchAlgorithmException e){
    return null;
}
catch (IOException e){
    return null;
}

A: You can' t do that assignment because:
java.lang.Object
  extended by java.io.InputStream
      extended by java.io.FilterInputStream
          extended by java.io.DataInputStream
              extended by org.apache.hadoop.fs.FSDataInputStream
FSDataInputStream is not a FileInputStream.
That said to convert from FSDataInputStream to FileInputStream,
you could user FSDataInputStream FileDescriptors to create a FileInputStream according to the Api
new FileInputStream(hdfsDIS.getFileDescriptor());

Not sure it will work.


text:
Q: How can i prevent duplication of copied / pasted image name in web editor? When users use the boards on my website, they usually paste the image with writing.
The thing is, when user A pastes the image named 'aaa', and after user A saved and finished the writing on boards, user B pastes the same named image on his board, the user A's saved image updated to user B's image.
How can i prevent duplication of this copied / pasted image's name in web editor?
and i'm using daum web editor(https://github.com/kakao/DaumEditor/wiki).
i asked this question to my friend developer, but he said there is no way to solve this problem.


text:
Q: Regex expression to remove house number unless it has letters as well I have two addresses

*

*226 W 750 S should equal W 750 S

*5th Avenue East Unit#B32c should equal 5th Avenue East
With this Regex ^\d+|Unit.+|(.+)|or\s.+|#.+|,.+|.$ I get

*

*W 750 S - Correct

*th Avenue East - Incorrect
With this Regex s-\d+|Unit.+|(.+)|or\s.+|#.+|\d+\s|\d+\w{1}\s|\d+\w{1}$ I get

*

*W S - Incorrect

*5th Avenue East - Correct
Can anyone help adjust either expression to fit both situations.
Thanks for any help!!

A: This would work:
^\d+(?![a-zA-Z])\s*|\s*Unit.+

https://regex101.com/r/F0PjEN/1

A: I appreciate the suggestions. This is what I went with and works with several other address formats.  I probably have extra stuff in here but it works.
^[^#th]\d+|Unit.+|.-|\(([^)]+)\)|or\s.+|#.+|\d+\w{1}$


text:
Q: How to extract 8 integers from a 256 vector using intel intrinsics? I'm trying to enhance the performance of my code by using the 256bit vector (Intel intrinsics - AVX).
I have an I7 Gen.4 (Haswell architecture) processor supporting SSE1 to SSE4.2 and AVX/AVX2 Extensions.
This is the code snippet that I'm trying to enhance:
/* code snipet */
kfac1 = kfac  + factor;  /* 7 cycles for 7 additions */
kfac2 = kfac1 + factor;
kfac3 = kfac2 + factor;
kfac4 = kfac3 + factor;
kfac5 = kfac4 + factor;
kfac6 = kfac5 + factor;
kfac7 = kfac6 + factor;

k1fac1 = k1fac  + factor1;  /* 7 cycles for 7 additions */
k1fac2 = k1fac1 + factor1;
k1fac3 = k1fac2 + factor1;
k1fac4 = k1fac3 + factor1;
k1fac5 = k1fac4 + factor1;
k1fac6 = k1fac5 + factor1;
k1fac7 = k1fac6 + factor1;

k2fac1 = k2fac  + factor2;  /* 7 cycles for 7 additions */
k2fac2 = k2fac1 + factor2;
k2fac3 = k2fac2 + factor2;
k2fac4 = k2fac3 + factor2;
k2fac5 = k2fac4 + factor2;
k2fac6 = k2fac5 + factor2;
k2fac7 = k2fac6 + factor2;
/* code snipet */

From the Intel Manuals, I found this.

*

*an integer addition ADD takes 1 cycle (latency).

*a vector of 8 integers (32 bit) takes 1 cycle also.
So I've tried ton make it this way:
fac  = _mm256_set1_epi32 (factor )
fac1 = _mm256_set1_epi32 (factor1)
fac2 = _mm256_set1_epi32 (factor2)

v1   = _mm256_set_epi32 (0,kfac6,kfac5,kfac4,kfac3,kfac2,kfac1,kfac)
v2   = _mm256_set_epi32 (0,k1fac6,k1fac5,k1fac4,k1fac3,k1fac2,k1fac1,k1fac)
v3   = _mm256_set_epi32 (0,k2fac6,k2fac5,k2fac4,k2fac3,k2fac2,k2fac1,k2fac)

res1 = _mm256_add_epi32 (v1,fac) ////////////////////
res2 = _mm256_add_epi32 (v2,fa1) // just 3 cycles  //
res3 = _mm256_add_epi32 (v3,fa2) ////////////////////

But the problem is that these factors are going to be used as tables indexes ( table[kfac] ... ). So i have to extract the factor as seperate integers again.
I wonder if there is any possible way to do it??

A: A smart compiler could get table+factor into a register and use indexed addressing modes to get table+factor+k1fac6 as an address.  Check the asm, and if the compiler doesn't do this for you, try changing the source to hand-hold the compiler:
const int *tf = table + factor;
const int *tf2 = table + factor2;   // could be lea rdx, [rax+rcx*4]  or something.

...

foo = tf[kfac2];
bar = tf2[k2fac6];     // could be  mov r12, [rdx + rdi*4]

But to answer the question you asked:
Latency isn't a big deal when you have that many independent adds happening.  The throughput of 4 scalar add instructions per clock on Haswell is much more relevant.
If k1fac2 and so on are already in contiguous memory, then using SIMD is possibly worth it.  Otherwise all the shuffling and data transfer to get them in/out of vector regs makes it definitely not worth it.  (i.e. the stuff compiler emits to implement _mm256_set_epi32 (0,kfac6,kfac5,kfac4,kfac3,kfac2,kfac1,kfac).
You could avoid needing to get the indices back into integer registers by using an AVX2 gather for the table loads.  But gather is slow on Haswell, so probably not worth it.  Maybe worth it on Broadwell.
On Skylake, gather is fast so it could be good if you can SIMD whatever you do with the LUT results.  If you need to extract all the gather results back to separate integer registers, it's probably not worth it.

If you did need to extract 8x 32-bit integers from a __m256i into integer registers, you have three main choices of strategy:

*

*Vector store to a tmp array and scalar loads

*ALU shuffle instructions like pextrd (_mm_extract_epi32).  Use _mm256_extracti128_si256 to get the high lane into a separate __m128i.

*A mix of both strategies (e.g. store the high 128 to memory while using ALU stuff on the low half).

Depending on the surrounding code, any of these three could be optimal on Haswell.
pextrd r32, xmm, imm8 is 2 uops on Haswell, with one of them needing the shuffle unit on port5.  That's a lot of shuffle uops, so a pure ALU strategy is only going to be good if your code is bottlenecked on L1d cache throughput.  (Not the same thing as memory bandwidth).  movd r32, xmm is only 1 uop, and compilers do know to use that when compiling _mm_extract_epi32(vec, 0), but you can also write int foo = _mm_cvtsi128_si32(vec) to make it explicit and remind yourself that the bottom element can be accessed more efficiently.
Store/reload has good throughput.  Intel SnB-family CPUs including Haswell can run two loads per clock, and IIRC store-forwarding works from an aligned 32-byte store to any 4-byte element of it.  But make sure it's an aligned store, e.g. into _Alignas(32) int tmp[8], or into a union between an __m256i and an int array.  You could still store into the int array instead of the __m256i member to avoid union type-punning while still having the array aligned, but it's easiest to just use C++11 alignas or C11 _Alignas.
 _Alignas(32) int tmp[8];
 _mm256_store_si256((__m256i*)tmp, vec);
 ...
 foo2 = tmp[2];

However, the problem with store/reload is latency.  Even the first result won't be ready for 6 cycles after the store-data is ready.
A mixed strategy gives you the best of both worlds: ALU to extract the first 2 or 3 elements lets execution get started on whatever code uses them, hiding the store-forwarding latency of the store/reload.
 _Alignas(32) int tmp[8];
 _mm256_store_si256((__m256i*)tmp, vec);

 __m128i lo = _mm256_castsi256_si128(vec);  // This is free, no instructions
 int foo0 = _mm_cvtsi128_si32(lo);
 int foo1 = _mm_extract_epi32(lo, 1);

 foo2 = tmp[2];
 // rest of foo3..foo7 also loaded from tmp[]

 // Then use foo0..foo7

You might find that it's optimal to do the first 4 elements with pextrd, in which case you only need to store/reload the upper lane.  Use vextracti128 [mem], ymm, 1:
_Alignas(16) int tmp[4];
_mm_store_si128((__m128i*)tmp,  _mm256_extracti128_si256(vec, 1));

// movd / pextrd for foo0..foo3

int foo4 = tmp[0];
...

With fewer larger elements (e.g. 64-bit integers), a pure ALU strategy is more attractive.  6-cycle vector-store / integer-reload latency is longer than it would take to get all of the results with ALU ops, but store/reload could still be good if there's a lot of instruction-level parallelism and you bottleneck on ALU throughput instead of latency.
With more smaller elements (8 or 16-bit), store/reload is definitely attractive.  Extracting the first 2 to 4 elements with ALU instructions is still good.  And maybe even vmovd r32, xmm and then picking that apart with integer shift/mask instructions is good.

Your cycle-counting for the vector version is also bogus.  The three _mm256_add_epi32 operations are independent, and Haswell can run two vpaddd instructions in parallel.  (Skylake can run all three in a single cycle, each with 1 cycle latency.)
Superscalar pipelined out-of-order execution means there's a big difference between latency and throughput, and keeping track of dependency chains matters a lot.  See http://agner.org/optimize/, and other links in the x86 tag wiki for more optimization guides.


text:
Q: React Native app crashes immediately on iOS TestFlight I hate to ask a question this open-ended, but I'm asking after 4 straight days of trial, error and pure desperation.
My question is:
Are there any un-obvious "gotchas" for bundling a React Native app for TestFlight? Because my app crashes on launch, but only in TestFlight. The crash reports only show RCTFatal (screenshot below).
My RN (0.54) build includes CodePush for my JS bundle, I use a Release scheme / Production certificate scheme when archiving follow all of the directions from CodePush/React Native. The app works, but not when packaged. Any idea, or best guesses what could be the case?
Update:
It's throwing an error when I run my Release Scheme on simulator:
Update (2):
The conversation has been moved to chat: https://chat.stackoverflow.com/rooms/170610/discussion-on-question-by-user1791914-react-native-app-crashes-immediately-on-io
Update (3):
This issue is still relevant, but I've opened up a separate question as debugging as revealed more info: React Native bundle error for Release, Babel not working?
React Native / Babel isn't compiling spread operators correctly, so this is a config issue that needs sorted.

Unhandled JS Exception: Unexpected token '...'.

Is this a Babel spread operator error?

A: So this turned out to be a syntax/js issue after all and had nothing to do with my build. I had an instance with
{...props.children} which should have been {props.children}

in one of my jsx files. This was causing really inconsistent results with the app crashing in some cases and not in others. It also led me on a wile goose chase trying to reconfigure babel and my release build as the Debug build was handling the error silently.


text:
Q: Computing UTM Zone from lat/long point I am trying to convert a latitude/longitude point to UTM.
To define UTM projection, I need to calculate zone for the point.
I am trying to figure out the best way to do this.
One way to do this would be use longitude values to find the proper zone.
This would require lot of coding.
I am curious if there is a better way of doing this?

A: It's not that difficult, even if you handle the zones around Svalbard and Norway. Here's an example:
ZoneNumber = floor((LongTemp + 180)/6) + 1;

if( Lat >= 56.0 && Lat < 64.0 && LongTemp >= 3.0 && LongTemp < 12.0 )
    ZoneNumber = 32;
endif
// Special zones for Svalbard
if( Lat >= 72.0 && Lat < 84.0 )
  if  ( LongTemp >= 0.0  && LongTemp <  9.0 )
    ZoneNumber = 31;
  elseif( LongTemp >= 9.0  && LongTemp < 21.0 )
    ZoneNumber = 33;
  elseif(LongTemp >= 21.0 && LongTemp < 33.0 )
    ZoneNumber = 35;
  elseif(LongTemp >= 33.0 && LongTemp < 42.0 )
    ZoneNumber = 37;
  endif
 endif

Convert Latitude/Longitude to UTM (attributed to Chuck Gantz).
I haven't tried this specific code, but the algorithm looks correct.

A: So I had this problem today, that I needed to find the UTM zone from lat/long. I needed to do it in R, but this was one of the top google hits. So here's my R script, with tests at the end for some of the curly edge cases like Svalbard, Norway, and the poles:
require(tidyverse)
require(purrr)
require(testthat)

find_one_utm_zone <- function(longitude, latitude) {

  # Special zones for Svalbard
  if (latitude >= 72.0 && latitude <= 84.0 ) {
    if (longitude >= 0.0  && longitude <  9.0)
      return("31X");
    if (longitude >= 9.0  && longitude < 21.0)
      return("33X")
    if (longitude >= 21.0 && longitude < 33.0)
      return("35X")
    if (longitude >= 33.0 && longitude < 42.0)
      return("37X")
  }
  # Special zones for Norway
  if (latitude >= 56.0 && latitude < 64.0 ) {
    if (longitude >= 0.0  && longitude <  3.0)
      return("31V");
    if (longitude >= 3.0  && longitude < 12.0)
      return("32V")
  }

  # North + South Poles

  if (latitude > 84.0){
    if ((longitude+180)%%360-180 < 0) {return("Y")}
    if ((longitude+180)%%360-180 > 0) {return("Z")}
  } else if (latitude < -80.0){
    if ((longitude+180)%%360-180 < 0) {return("A")}
    if ((longitude+180)%%360-180 > 0) {return("B")}
  }

  # Everything in the middle

  if ( (latitude>-80.0) && (latitude<=84.0) ){

    mid_zones <- LETTERS[c(3:8,10:14,16:24)] # C to X, skip I and O
    utm_letter <- mid_zones[ min(floor( (latitude + 80) / 8 )+1 , 20) ]
    utm_number <- (floor( (longitude + 180) / 6 ) %% 60) + 1 # modulo in case longitude is 0 to 360 instead of -180 to 180
    utm_zone <- paste0(utm_number, utm_letter)
    return(utm_zone)

  } else {
      stop("lat long not valid (or something else broke)")
    }
}
find_utm_zone <- function(lon, lat){
  purrr::map2_chr(.x = lon, .y = lat, .f = find_one_utm_zone)
}

Example of use
locs <-
  tibble(lon = c(-100,30,150, 4, 7, 22, 0, 12, -34),
         lat = c(-45, 85, 12, 57, 81, 83, 5, -81, 85),
         desired_utm_zone = c("14G","Z","56P", "32V" ,"31X","35X","31N", "B","Y"))

locs2 <-
  locs %>%
  mutate(utm_zone = find_utm_zone(lon = lon,lat = lat))

Test that it worked:
testthat::expect_equal(locs2$utm_zone, locs2$desired_utm_zone)


text:
Q: rgdal error when connecting to postgres I'm working with a Mac Os 10.9.2 and a R version 3.0.2.
I used dbDriver() and dbConnect() to initiate the connection to my database. Next, I tried to connect to my postgres database using
c = readOGR("PG:dbname=OB", layer="geo.countries")

This does not work, and always returns a "Cannot open file" error.
I understood from https://stat.ethz.ch/pipermail/r-sig-geo/2010-January/007519.html that the reason for this is the absence of a driver for PostgreSQL. As can be seen by using the command ogrDrivers()
Does anybody can help me on how to install the driver? Or how I can make this work? Any help is much appreciated!
Thanks!

A: In the absence of the right driver, gdal/ogr usually throws and error like
Unable to find driver PostgreSQL
First, make sure that the database and layer exist. If it's true that the driver for Postgres isn't installed, you'll have to re-install gdal. Using homebrew:
brew uninstall gdal
brew install gdal --with-postgresql

See also this question.

A: If you are really sure that gdal is properly installed, make sure that your dns is fully specified (it has more parameters than dbname)
dsn="PG:dbname=DB host=HOST user=USER password=PSSWD port=5432"

Moreover, if your table contains more than one spatial columns (layers), you have to specify the one you want:
layer = "DB.TABLE(YOUR_SPATIAL_COLUMN)"

Took me a while to find out. But it was obvious after calling function

ogrListLayers()

It works for me. Just one issue, if you have some raster column in you table, it will not be excluded (as all other layers/spatial columns). Instead, it will be loaded into spatialobject@data dataframe as text column. Quite annoying in case of big rasters. I have posted question for this.


text:
Q: Logo not showing on tablet I have an app and the logo shows on my Samsung Galaxy 4 but not on a ASUS Tablet. i've tried using  and everything
How can I fix this?
Here's the Android Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.xxx.xxx"
    android:versionCode="1"
    android:versionName="1.0" >
<compatible-screens>
    <!--no small size screens -->

    <!--all normal size screens -->
    <screen android:screenSize="normal" android:screenDensity="ldpi" />
    <screen android:screenSize="normal" android:screenDensity="mdpi" />
    <screen android:screenSize="normal" android:screenDensity="hdpi" />
    <screen android:screenSize="normal" android:screenDensity="xhdpi" />

    <!-- all large size screens -->
    <screen android:screenSize="large" android:screenDensity="ldpi" />
    <screen android:screenSize="large" android:screenDensity="mdpi" />
    <screen android:screenSize="large" android:screenDensity="hdpi" />
    <screen android:screenSize="large" android:screenDensity="xhdpi" />

    <!-- all xlarge size screens -->
    <screen android:screenSize="xlarge" android:screenDensity="ldpi" />
    <screen android:screenSize="xlarge" android:screenDensity="mdpi" />
    <screen android:screenSize="xlarge" android:screenDensity="hdpi" />
    <screen android:screenSize="xlarge" android:screenDensity="xhdpi" />

    <!-- Special case for Nexus 7 -->
    <screen android:screenSize="large" android:screenDensity="213" />

</compatible-screens>
    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="19" />
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:logo="@drawable/logons"
        android:label="@string/app_name"

So I have no idea why tho logo is showing on my phone but not on the tablets, it was like this before I added the compatible screens too.
Strings.xml
<style name="ActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">#FFFFFF</item>

        <item name="android:titleTextStyle">@style/myTheme.ActionBar.Text</item>
        <item name="android:displayOptions">useLogo|showHome</item>

    </style>

A: You have to put ic_launcher in every drawable folders with the right size.
After that the logo gonna show itself.
For Samsung Galaxy S4 you have to put logo in drawable-xxhdpi folder.


text:
Q: How to proof this upper bound in a tree with limited degree Hope someone will know the answer.
Say I have a tree T with maximum degree d >=2.
Proof there exist an egde e such as by removing e from T you'll get two trees T1 and T2 that each one of them contains maximum
⌈ |V|*(d-1)/d⌉ vertices.
Where |V| is the numbers of vertices in the tree T


text:
Q: bash regexp that match to character sequence I am writing a bash script that receives <task> ID strings as a parameter and then executes the specified tasks. At the end of the execution, it must show the total execution time. The code must be flexible, and easy to add new conditions.
Usage: build.sh <task><task><task>...
The task id is a little bit tricky:

*

*if it is only a character [a-z] then it represents all subtasks of the given task

*if it is a character + a number, it represents only the specific subtask

Let me give you some examples:

*

*build.sh a1a2: execute tasks of a1 and a2, but not a3

*build.sh a: execute all tasks starts with char a (all subtasks of a)

*build.sh a1b: run only task a1 and all subtasks of b

*build.sh a1b3: run only task a1 and b3

*build.sh ab: run all subtasks of a and b

*build.sh *: run all tasks defined is the build script (all subtasks), like a + b + c
The execution order of the tasks is pre-defined, so actually b1a1 will execute a1b1.
This is my bash script:
#!/bin/bash -ue

# show help
function show_help() {
    if [ "$1" -eq 0 ]; then
        printf "..."
        exit 0
    fi
}

# does the build
function build {
    local title dir
    title="$1"
    dir="$2"
    printf "\n%b> building '%s'...%b\n" "$COLOR_YELLOW" "$title" "$COLOR_DEFAULT"
    cd "$WORKSPACE/../$dir"
    ./build.sh
    cd "$WORKSPACE"
}

# group A build
function build_group_a {
    if [[ "$1" == *a1* ]]; then build "task A.1" "base/xxx"; fi
    if [[ "$1" == *a2* ]]; then build "task A.2" "base/yyy"; fi
    if [[ "$1" =~ $(getRegexp a) ]]; then
      build "task A.1" "base/xxx"
      build "task A.2" "base/yyy"
    fi
}

# group B build
function build_group_b {
   # same with 'build_group_a' only conditions are different
}

# REGEXP THAT DOES NOT WORK PROPERLY
function getRegexp() {
    printf ".*%s[a-z].*" "$1"
}

show_help "$#"
START_TIME=$(date +%s)

# 'all' works but '*' not
if [[ "$1" == all ]]; then
    build_group_a a
    build_group_b b
else
    build_group_a "$1"
    build_group_b "$2"
fi

ELAPSED=$(($(date +%s) - START_TIME))
printf "build time: %s\n" "$(date -d@$ELAPSED -u +%H\ hour\ %M\ day\ %S\ sec)"

Everything works fine, tasks are executed properly in order but if I use build.sh a then nothing is executed. If I use build.sh ab, only tasks a are executed. I do not know why. It seems that the last task-ID is not processed by my regexp.
Another issue is that if I say build.sh aa1 then all tasks for a are executed but task a1 twice. Task a1 must only be executed once when a is called.
That could be great if you can guide me on how to fix the problem in my regular expression.

A: On the regex part, you can try this :
#!/usr/bin/env bash

input="$1"
pattern='(\*|[[:alpha:]][[:digit:]]?)'
while [[ $input =~ $pattern ]]; do
    echo "Argument passed : ${BASH_REMATCH[1]}"
    input="${input:${#BASH_REMATCH[0]}}" # next iteration
done

test with :
bash build.sh a1b
bash build.sh "*"

A: Thanks a lot for your comments. Based on your help I was able to fix the issue.
In the final version I use a little bit different approach for the regexp than before.
And in the meanwhile I simplified everything.
This is the code with the regexp:
#!/bin/bash -ue

function build {
    local arg id title dir group regexp
    arg=$(printf "%sz" "$1")
    id="$2"; title="$3"; dir="$4"; group=${id:0:1}
    regexp=$(printf "(0|%s|%s[a-z])" "$id" "$group")
    if [[ "$arg" =~ $regexp ]]; then
        printf "%b> building '%s'...%b\n" "$COLOR_YELLOW" "$title" "$COLOR_DEFAULT"
        cd "$WORKSPACE/.../$dir"
        ./build.sh
        cd "$WORKSPACE"
    fi
}

function show_help() {
    if [ "$1" -eq 0 ]; then
        printf "..."
        exit 0
    fi
}

...
show_help "$#"
START_TIME=$(date +%s)

build "$1" "a1" "task A.1" "aa/xxx"
build "$1" "a2" "task A.2" "aa/yyy"
build "$1" "b1" "task B.1" "bb/vvv"
build "$1" "b2" "task B.2" "cc/www"

ELAPSED=$(($(date +%s) - START_TIME))
printf "build time: %s\n\n" "$(date -d@$ELAPSED -u +%H\ hour\ %M\ day\ %S\ sec)"

This works like a charm and I think that it is enough simple.
I use 0 to run all of the tasks because unfortunately, the asterisk(*) was not working for me in my regexp.
Another trick that I had to do is to add an extra character (in my case it is an z) at the end of the user input. That was necessary, otherwise, the last command won't be executed.


text:
Q: Oracle 11g: SQLDeveloper |status: failure-test failed: IO error. connection reset| part 1
new / select database connection
info
 connection name: ziv
 username:oracle
 password: xxxxxxx
 connection type: basic role: sysdba
 host name : localhost.localdomain
 port: 1158
 sid: orcl

quest is to make new connection  what to do?
i trying to connect a database from sqldeveloper
but im get the follow error
error:
 status: failure-test failed: IO error. connection reset

part 2
i change the port to 1521 and im get other error
status failure test failed IO error the nestwork adapter could not
establish the connection
  [oracle@localhost Desktop]$ lsnrctl status
  LSNRCTL for Linux: Version 11.2.0.1.0 - Production on 08-DEC-2015 09:16:27
  Copyright (c) 1991, 2009, Oracle.  All rights reserved.
  Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))
  TNS-12541: TNS:no listener
  TNS-12560: TNS:protocol adapter error
  TNS-00511: No listener
  Linux Error: 111: Connection refused
  Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)
  (HOST=localhost.localdomain)(PORT=1521)))
  TNS-12541: TNS:no listener
  TNS-12560: TNS:protocol adapter error
  TNS-00511: No listener
  Linux Error: 111: Connection refused

part 3
  [oracle@localhost Desktop]$ lsnrctl start
  LSNRCTL for Linux: Version 11.2.0.1.0 - Production on 08-DEC-2015 09:39:16
  Copyright (c) 1991, 2009, Oracle.  All rights reserved.
  Starting /u01/app/oracle/product/11.2.0/db_1/bin/tnslsnr: please wait...
  TNSLSNR for Linux: Version 11.2.0.1.0 - Production
  System parameter file is
  /u01/app/oracle/product/11.2.0/db_1/network/admin/listener.ora
  Log messages written to
  /u01/app/oracle/diag/tnslsnr/localhost/listener/alert/log.xml
  Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1521)))
  Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)
  (PORT=1521)))
  Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))
  STATUS of the LISTENER
  ------------------------
  Alias                     LISTENER
  Version                   TNSLSNR for Linux: Version 11.2.0.1.0 -
  Production
  Start Date                08-DEC-2015 09:39:18
  Uptime                    0 days 0 hr. 0 min. 0 sec
  Trace Level               off
  Security                  ON: Local OS Authentication
  SNMP                      OFF
  Listener Parameter File
  /u01/app/oracle/product/11.2.0/db_1/network/admin/listener.ora
  Listener Log File
  /u01/app/oracle/diag/tnslsnr/localhost/listener/alert/log.xml
  Listening Endpoints Summary...
  (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1521)))
  (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521)))
  The listener supports no services
  The command completed successfully

  [oracle@localhost Desktop]$ lsnrctl status
  LSNRCTL for Linux: Version 11.2.0.1.0 - Production on 08-DEC-2015 09:39:40
  Copyright (c) 1991, 2009, Oracle.  All rights reserved.
  Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))
  STATUS of the LISTENER
  ------------------------
  Alias                     LISTENER
  Version                   TNSLSNR for Linux: Version 11.2.0.1.0 -
  Production
  Start Date                08-DEC-2015 09:39:18
  Uptime                    0 days 0 hr. 0 min. 22 sec
  Trace Level               off
  Security                  ON: Local OS Authentication
  SNMP                      OFF
  Listener Parameter File
  /u01/app/oracle/product/11.2.0/db_1/network/admin/listener.ora
  Listener Log File
  /u01/app/oracle/diag/tnslsnr/localhost/listener/alert/log.xml
  Listening Endpoints Summary...
  (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1521)))
  (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521)))
  Services Summary...
  Service "orcl.localdomain" has 1 instance(s).
  Instance "orcl", status READY, has 1 handler(s) for this service...
  Service "orclXDB.localdomain" has 1 instance(s).
  Instance "orcl", status READY, has 1 handler(s) for this service...
  The command completed successfully

PART 4
okey so im try again and other error ^^ this time
status: failure- test failed : ora-01031 insufficient privileges
okey so now it work after the last step
   **before**
   connection name: ziv
   username: sys
   password: xxxxxxx
   connection type: basic
   role: sysdba
   host name : localhost.localdomain
   port: 1521
   sid: orcl

change the username from oracle to sys and it worked...
  **after**
  connection name: ziv
  username: oracle
  password: xxxxxxx
  connection type: basic
  role: sysdba
  host name : localhost.localdomain
  port: 1521
  sid: orcl

tnx for all for the help

A: 1158 is the default port for Enterprise Manager Database Console, not the database listener, and you can not log in there using SQL*Net or JDBC.
The default port for the database listener is 1521, try connecting using that port. You can check the listener port by:
lsnrctl status


text:
Q: generate random binary number in perl I want to generate 64 iteration of non-repetitive 6 digits that only consist of 0 and 1 (eg. 111111, 101111, 000000) by using perl.
I found code that can generate random hex and try to modify it but I think my code is all wrong. This is my code:
use strict;
use warnings;

my %a;

foreach (1 .. 64) {
    my $r;
    do {
        $r = int(rand(2));
    }
until (!exists($a{$r}));
printf "%06d\n", $r;
$a{$r}++;
}

A: Do you mean that you want 64 six-bit numbers, all distinct from each other?  If so, then you should just shuffle the list (0, 1, 2, 3, …, 63), because there are exactly 64 six-bit numbers — you just want them in a random order.
And if you want to print them as base-two string, use the %06b format.
use List::Util;

my @list = List::Util::shuffle 0..63;
printf "%06b\n", $_ for @list;

A: From the comments:

I am actually want to generate all possible 6-bit binary number. Since writing all the possible combination by hand is cumbersome and prone to human error, I think it will be good idea to just generate it by using rand() with no repetition and store it into array.

This is a horribly inefficent approach to take, thanks to random number collisons.
You get the same result with:
printf ( "%06b\n", $_ ) for 1..63;

If you're after a random order (although, you don't seem to suggest that you do):
use List::Util qw ( shuffle );
printf ( "%06b\n", $_ ) for shuffle (0..63);

A: If you want 64 x 6-bit integers you can call int(rand(64)); 64 times, there's no need to generate each bit separately.
Your code can be modified to work like this:
#!/usr/bin/perl
# your code goes here

use strict;
use warnings;

my %a;

foreach (1 .. 64) {
    my $r;
    do
    {
        $r = int(rand(64));
    } until (!exists($a{$r}));
    printf "%06b\n", $r;
    $a{$r}++;
}

The results are stored in a array of integers. The %06b format specifier string prints out a 6 bit binary number.


text:
Q: Keyboard input for a game in Java I'm writing a game in Java, right now it's Swing + JOGL - a JFrame with a GLCanvas.
I handle input using keyPressed etc. events (jframe.addKeyListener(...)) and it doesn't seem to work properly:

*

*when I have 3+ keys down at the same time, they don't register properly - apparently this is keyboard's fault, I have to find an alternate control scheme.

*after the window loses, then regains focus, input stops working completely...

What am I doing wrong?
Is there a better way of handling keyboard input in Java?
(I'd rather not switch to another library, like LWJGL... unless I have no choice).

A: To keep dependencies down, I would go for the "built-in" keyboard handling. It works just fine if you know what your doing. I'll paste some code from my games:
It handles key-repeats with custom repeat-delay / rate and has no issues with in which component keyboard focus lies.
public class GameKeyController implements KeyEventDispatcher {

    private final int MAX_REPEAT_RATE = 100; // Hz

    private final LocalGame game;
    private final GamingContext context;
    private final Account account;
    Timer keyRepeatTimer;
    Map<Move, TimerTask> repeatingTasks = new EnumMap<Move, TimerTask>(Move.class);

    public GameKeyController(LocalGame game, GamingContext context,
            Account account) {
        this.game = game;
        this.context = context;
        this.account = account;
    }

    public boolean dispatchKeyEvent(KeyEvent e) {

        assert EventQueue.isDispatchThread();

        int kc = e.getKeyCode();

        if (e.getID() == KeyEvent.KEY_PRESSED) {

            // If repeat is activated, ignore KEY_PRESSED events.
            // Should actually not occur, since KEY_RELEASED *should* have been
            // intercepted since last KEY_PRESSED.
            if (kc == account.getInt(KC_MOVE_LEFT)  && !isRepeating(LEFT))      move(LEFT);
            if (kc == account.getInt(KC_MOVE_RIGHT) && !isRepeating(RIGHT))     move(RIGHT);
            if (kc == account.getInt(KC_SOFT_DROP)  && !isRepeating(SOFT_DROP)) move(SOFT_DROP);

            // Regular moves
            if (kc == account.getInt(KC_ROT_CW))        move(ROT_CW);
            if (kc == account.getInt(KC_ROT_CW2))       move(ROT_CW);
            if (kc == account.getInt(KC_ROT_CCW))       move(ROT_CCW);
            if (kc == account.getInt(KC_ROT_CCW2))      move(ROT_CCW);
            if (kc == account.getInt(KC_HARD_DROP))     move(HARD_DROP);
            if (kc == account.getInt(KC_SLIDE_DROP))    move(SLIDE_DROP);
            if (kc == account.getInt(KC_FULL_LEFT))     move(FULL_LEFT);
            if (kc == account.getInt(KC_FULL_RIGHT))    move(FULL_RIGHT);
            if (kc == account.getInt(KC_HOLD))          move(HOLD);

            if (kc == account.getInt(KC_SEND_TO_ME))    useSpecial(0);
            if (kc == account.getInt(KC_SEND_TO_1))     useSpecial(1);
            if (kc == account.getInt(KC_SEND_TO_2))     useSpecial(2);
            if (kc == account.getInt(KC_SEND_TO_3))     useSpecial(3);
            if (kc == account.getInt(KC_SEND_TO_4))     useSpecial(4);
            if (kc == account.getInt(KC_SEND_TO_5))     useSpecial(5);
            if (kc == account.getInt(KC_SEND_TO_6))     useSpecial(6);
            if (kc == account.getInt(KC_SEND_TO_7))     useSpecial(7);
            if (kc == account.getInt(KC_SEND_TO_8))     useSpecial(8);
            if (kc == account.getInt(KC_SEND_TO_9))     useSpecial(9);

            // Reported bug: Key repeat "lags on releases", that is, the key
            // continues to repeat a few ms after it has been released.
            // The following two lines gives one "upper" approximation of
            // when someone really wants to release the key.
            if (kc == account.getInt(KC_MOVE_RIGHT)) stopRepeating(LEFT);
            if (kc == account.getInt(KC_MOVE_LEFT)) stopRepeating(RIGHT);
        }

        if (e.getID() == KeyEvent.KEY_RELEASED) {
            if (kc == account.getInt(KC_MOVE_LEFT)) stopRepeating(LEFT);
            if (kc == account.getInt(KC_MOVE_RIGHT)) stopRepeating(RIGHT);
            if (kc == account.getInt(KC_SOFT_DROP)) stopRepeating(SOFT_DROP);
        }

        return false;
    }

    private synchronized void stopRepeating(Move m) {
        if (!isRepeating(m))
            return;
        repeatingTasks.get(m).cancel();
        repeatingTasks.remove(m);
    }

    private synchronized boolean isRepeating(Move m) {
        return repeatingTasks.get(m) != null;
    }

    private synchronized void move(Move move) {
        assert EventQueue.isDispatchThread();

        context.notIdleSinceStart();

        PlayfieldEvent pfe = game.move(move);

        // Fake wall kicks
        if ((move == ROT_CW || move == ROT_CCW) &&
                account.getBool(USE_FAKE_WALL_KICKS) && !pfe.pfChanged) {

            // Try RIGHT and ROT, then LEFT and ROT.
            Playfield pf = game.getPlayfield();
            if (pf.isFakeRotPossible(true, move == ROT_CW)) {
                game.move(RIGHT);
                game.move(move);
            } else if (pf.isFakeRotPossible(false, move == ROT_CW)) {
                game.move(LEFT);
                game.move(move);
            }
        }

        // Initiate key repeats
        int delay = account.getInt(KEY_REPEAT_DELAY);
        int rate = account.getInt(KEY_REPEAT_RATE);
        if (delay > 0 && rate > 0 && isRepeatable(move))
            startRepeating(move);
    }

    private boolean isRepeatable(Move m) {
        return m == LEFT || m == RIGHT || m == SOFT_DROP;
    }

    private synchronized void startRepeating(Move move) {
        assert EventQueue.isDispatchThread();

        if (isRepeating(move))
            return;

        long delay = account.getInt(KEY_REPEAT_DELAY);
        int rate = account.getInt(KEY_REPEAT_RATE);

        Move repeatMove = move;
        if (rate >= MAX_REPEAT_RATE) {
            rate = MAX_REPEAT_RATE;
            repeatMove = move == LEFT      ? FULL_LEFT
                       : move == RIGHT     ? FULL_RIGHT
                       : move == SOFT_DROP ? SLIDE_DROP
                       : null; // not a repeatable move!
        }

        long period = (long) (1000.0 / rate);

        if (move == SOFT_DROP)
            delay = period;

        final Move m = repeatMove;
        TimerTask tt = new TimerTask() {

            // Should only be executed by keyRepeatTimer thread.
            public void run() {

                // Remove the if-branch below and you get old school GB behavior
                // With the if-branch it's more TDS-ish.
                // TODO: Make this depend on an account-setting
                if (m == SOFT_DROP && game.getPlayfield().isTetOnSurface()) {
                    stopRepeating(SOFT_DROP);
                    return;
                }

                game.move(m);

                // Attempt to make it more responsive to key-releases.
                // Even if there are multiple this-tasks piled up (due to
                // "scheduleAtFixedRate") we don't want this thread to take
                // precedence over AWT thread.
                Thread.yield();
            }
        };
        repeatingTasks.put(move, tt);
        keyRepeatTimer.scheduleAtFixedRate(tt, delay, period);
    }

    public synchronized void init() {
        if (!isInited()) {
            keyRepeatTimer = new Timer("Key Repeat Timer");
            KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this);
        }
    }

    public synchronized boolean isInited() {
        return keyRepeatTimer != null;
    }

    public synchronized void uninit() {
        if (isInited()) {
            KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(this);

            keyRepeatTimer.cancel();
            keyRepeatTimer = null;
        }
    }

    private void useSpecial(int target) {
        context.notIdleSinceStart();
        context.useSpecial(target);
    }

}

A: Some of the tips in this article on global event listeners include catching key events with the KeyboardFocusManager, and might help with coming back from losing focus.
Regarding the 3+ keys, that's going to be tricky since the KeyEvent accounts for modifiers but not for multiple (regular) keys in its API. You might have to manage the press state yourself, in that if you get a KEY_PRESSED you store that key and build up the set of keys that are currently pressed. But if you simply don't get events at all when 3 or more keys are pressed, I'm not sure there's much you can do.
Edit: Also, the JGame library has a JOGL target. Looking at how it handles key events might help. I know it can handle at least 2 keys simultaneously.


text:
Q: Identifying subject specific outliers in the presence of between subject heterogeneity I have a simple dataset of people's heights, many people with measurements on multiple days (once a year for 10 years, say).  I have the date of each measurement.
Some of the height values are absurd.  I already drop values that are 'impossible' (e.g. height values above 3m).  However, I'd like to identify unusual values within a patient.  If a patient has 5 records at around 1.8m, I'd like a red flag if there's a value for 2.1m
I am considering trying the ESD test for outliers - it seems straightforward to implement - but I thought I'd ask if there are better ideas before I get started.
Thanks.
EDIT:
The ESD test I refer to is the [[Generalized] 'Extreme Studentized Deviate'][1] test; similar to the Grubbs Test, it 'is used to detect one or more outliers in a univariate data set that follows an approximately normal distribution'.
I'll have measurements for over 100,000 people - however, each person will only have between 0 and around 20 measurements.
I'm hoping to generalise this to other measurements such as BMI, lab tests (Eosinophils, White Blood Counts), respiratory tests (FEV1), etc.  I suspect the latter ones will be difficult as they're more varied, rising and falling with little dependency on time - hence my starting with height!

A: I think you will have to take a look at random effects (see How to account for participants in a study design?).
The idea is that you have, for a number of people $N$, a number of height measurements in different years $y$, so $h_{iy},i=1, 2 \dots, N, y=1, 2, \dots 10$. Each $h_{iy}$ depends on the height in the first year (which depends on the person $i$) and increases with the years (the rate of increase can also depend on the person $i$), so you have something like $h_{iy} = \beta_{1i} + \beta_{2i} y + \epsilon$, where the coefficients $\beta_{1i}, \beta_{2i}$ depend on the person (hence the subscipt $i$), but if you can estimate such an equation, then you have one regression line for each person and you can look, for that single person, which points are 'far away' from that individual person's own regression line.
A reference book is Fitzmaurice, Laird, Ware, "Applied longitudinal analysis" where you can find all the details, so I will just explain the main lines of the reasoning:
It is assumed that the $\beta_{1i}$ and $\beta_{2i}$ are normally distributed with a mean $\beta_1$ (resp. $\beta_2$) and a standard deviation $\sigma_1$ (resp. $\sigma_2$) (so the assumption is that the heights in the first year are normally distributed, just as the growth rates).  So we can re-write $\beta_{ki}$ as $\beta_{ki}=\beta_k + b_{kj}$ where $\beta_k$ is the mean of all $\beta_{ki}$ and $b_{ki} \sim N(0;\sigma_i), k=1,2$.
So your regression becomes $h_{iy}=\beta_1+b_{1i} + (\beta_2+b_{2i})y+\epsilon$, this is the form that you find in the reference Fitzmaurice et al.
the $b_{ki}$ are called the random effects. The $\beta_{k}$ are the fixed effects.
To illustrate this let me use some simulated data:
# this is just for simuating data, you have the data, the simulation generates heights
# for N=500 people for 10 years.

library(reshape2)

# simulation for 500 persons
N<-500

#simulate the heights in the first year, mean 1.7, sd 0.2,
# generate a random number of each of the N persons
h0<-rnorm(n=N, mean=1.7, sd=0.2)

#generate a random growth rate for each of the N persons
ch1<-rnorm(n=N, mean=0.01, sd=0.01)

# simulate h_iy:  the height in the first year + (annual growth x year) + error term
h<-h0 + ch1 %*% t(1:10) + rnorm(n=N, mean=0, sd=0.02)

# reformat it a bit so that it is useable later on
colnames(h)<-1:10
df<-cbind( data.frame(subject=1:nrow(h)),
           as.data.frame(h) )

df.molten<-melt(data=df, id.vars="subject", value.name="height", variable.name="year")
df.molten$year<-as.numeric(df.molten$year)

After simulating the data, we will now estimate the above mentioned equation as a linear mixed effects model (with the nlme package in R):
library(nlme)
library(ggplot2)

lme.h<-lme(height  ~ year + 1,       # we estimate height as function of year
           data=df.molten,           # on the simulated data
           random= ~ 1 + year | subject,  # we use a random effect on the intercept and on the coeffcient of year
           control=lmeControl(opt="optim"),
           method="REML")

The values that are estimated for your data can be found with the following calls:
lme.fix<-fixed.effects(lme.h)
lme.blup<-random.effects(lme.h)

The first one gives you the fixed effects $\beta_k$ (compare them to the values used in the simulation), the second one gives you the best linear unbiased prediction (blup) of the random effect for each person of your dataset.
Compare now the 'estimated fixed effects + the blup predictors of the random effects' for each person to your input (in this case simulated) data, first for the intercept:
df.plot<-data.frame(sim=h0, estim=lme.blup[[1]]+lme.fix[1])

ggplot(df.plot, aes(x=sim,y=estim))+
  coord_fixed()+
  geom_abline(intercept=0, slope=1, colour="red")+
  geom_point()

I can not upload plots from here but if you execute the code then you get a graph with on the horizontal axis the simulated initial (i.e. in the first year) heights and on the vertical axis the estimated/predicted values for each person in the first year, the red line is the bisector.
Similar, but for the coefficient of the year:
df.plot<-data.frame(sim=ch1, estim=lme.blup[[2]]+lme.fix[2])

ggplot(df.plot, aes(x=sim,y=estim))+
  coord_fixed()+
  geom_abline(intercept=0, slope=1, colour="red")+
  geom_point()

With these results you have a regression line for each inidivual person, you can also estimate the variance around the line and then find ''outliers'' for each person's line.  For details I refer to Fitzmaurice et al.
so for person $i$ you will find the regression line $h_{iy}=\hat{\beta}_1+\hat{b}_{1i} + (\hat{\beta}_2+\hat{b}_{2i})y$ where $\hat{\beta}_1$ is in lme.fix[1], $\hat{b}_{1i}$ in lme.blup[[1]][i] and $\hat{\beta}_2$ is in lme.fix[2], $\hat{b}_{2i}$ in lme.blup[[2]][i]
For the details on the nlme package you can use this pdf

A: Since you have a measurement that is very well known, why not define deviation based on your knowledge of measurement technology rather than use a statistical measure of deviance.  For example, if you have experience making height measurements and you know height easily can be measured accurately to within 1" (about .05 m), then you might simply discard all measures more deviant than 1" as flawed. Statistical analysis is about finding meaning in data.  If you have a definition of a deviant measure based on logical evaluation of the limits of height measurement technology, why look to statistical analysis for a measure of deviance?


text:
Q: Different rewrite rules in apache for different subdomains currently I get mad on Apache rewrite rules again. My problem is, that I want to have different rewrite rules for different subdomains, but I only have one .htaccess file (limited by my provider).
What I mean is: I have subdomain A and I want to define some rewrite rules that only match if the subdomain matched beforehand. Same for subdomain B, C, ... (doesn't matter how much subdomains I have).
I tried it on two ways: first I tried it with a combination of <If> directives and mod_rewrite, second I tried it by setting an enviroment variable that is set differently related to the matching subdomain.
First version (the readable one):
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /

  RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  <If "%{HTTP_HOST} == 'example.org'">
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
  </If>

  <If "%{HTTP_HOST} == 'blog.example.org'">
    # /autor/{author name}
    RewriteRule ^/autor/([^/]+)/?$ /index.php?author_name=$1 [L]

    # /{blog name}
    RewriteRule ^/([^/]+)/?$ /index.php?blog=$1 [L]

    # /{blog name}/{year}/{article name}
    RewriteRule ^/([^/]+)/([0-9]{4})/([^/]+)/?$ /index.php?blog=$1&year=$2&name=$3 [L]

    # /
    RewriteRule ^/?$ /index.php?post_type=post [L]
  </If>
</IfModule>

Second version (the ugly one):
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /

  RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  # set enviroment variable SUBDOMAIN for different subdomains
  # subdomain: example.org
  RewriteCond %{HTTP_HOST} "=example.org"
  RewriteRule . - [ENV=SUBDOMAIN:main]

  # subdomain: assets.roter-baum.de
  RewriteCond %{HTTP_HOST} "=assets.roter-baum.de"
  RewriteRule . - [ENV=SUBDOMAIN:assets]

  # subdomain: blog.example.org
  RewriteCond %{HTTP_HOST} "=blog.example.org"
  RewriteRule . - [ENV=SUBDOMAIN:blog]

  # rules for main
  RewriteCond %{ENV:SUBDOMAIN} "=main"
  RewriteRule ^index\.php$ - [L]

  RewriteCond %{ENV:SUBDOMAIN} "=main"
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.php [L]

  # rules for blog
  # /autor/{author name}
  RewriteCond %{ENV:SUBDOMAIN} "=blog"
  RewriteRule ^/autor/([^/]+)/?$ /index.php?author_name=$1 [L]

  # /{blog name}
  RewriteCond %{ENV:SUBDOMAIN} "=blog"
  RewriteRule ^/([^/]+)/?$ /index.php?blog=$1 [L]

  # /{blog name}/{year}/{article name}
  RewriteCond %{ENV:SUBDOMAIN} "=blog"
  RewriteRule ^/([^/]+)/([0-9]{4})/([^/]+)/?$ /index.php?blog=$1&year=$2&name=$3 [L]

  # /
  RewriteCond %{ENV:SUBDOMAIN} "=blog"
  RewriteRule ^/?$ /index.php?post_type=post [L]

The point is: it works as long as I don't point to the index.php. When I link to index.php I get a 500 Internal Server Error and I don't know why. Any ideas? I mean, I would also use the ugly version if I have to and if it works. But currently none are working.


text:
Q: Passing multiple selections from selectizeInput to MySQL query I am trying to pass multiple values of a selectizeInput to a MySQL query.
The question is what is the right syntax for this kind of operation in a shiny app ?
What I tried and is working with one value
  library(shiny)
  library(DBI)
  library(RMySQL)

  server <- shinyServer(function(input, output, session) {
            con <- dbConnect(MySQL(), user='user', port = 3306,
   password='pwd', dbname='db', host='host' )

           on.exit(dbDisconnect(con), add = TRUE)

  output$textview <- renderUI({

         con <- dbConnect(MySQL(), user='user', port = 3306, password='pwd',
               dbname='db', host='host' )

         on.exit(dbDisconnect(con), add = TRUE)

       text <- reactive({
                dbGetQuery(con, statement =
                paste0(" SELECT author,  title, publicationDate,  FROM publications
               WHERE publications.year LIKE %'",input$year,"'% ")
             )
               })

                text <-text()
                HTML(text)

          })

   session$onSessionEnded(function() { dbDisconnect(con) })
     })

 ui_panel <-
      tabPanel("Multi-Select Input Test",
        sidebarLayout(
           sidebarPanel(

         selectizeInput('year', 'Select Year of publication:', choices =
         publications.year, multiple = TRUE  options = list(maxOptions = 5)
         ),

                   br(),
                   submitButton("Update Text View"),
                   br()
       ),
       mainPanel(
       tabsetPanel(tabPanel("Text",htmlOutput("textview"))

       )
     )
))

 ui <- shinyUI(navbarPage(" ",ui_panel))

 runApp(list(ui=ui,server=server))

What is the correct syntax in the MySQL command that will allow me to pass more than one value from selectizeInput (input$year)?
I tried using IN instead of LIKE as below but it did not work
    text <- reactive({
                dbGetQuery(con, statement =
                paste0(" SELECT author,  title, publicationDate,  FROM
                publications WHERE publications.year IN %'",input$year,"'% ")
             )
               })

A: You need to construct a SQL similar to this:
SELECT * FROM publications WHERE year IN (2016, 2017)

This should generate that:
text <- reactive({
  year_selected <- paste(input$year, collapse = ',')
  sql = paste("SELECT * FROM publications WHERE year IN (",year_selected,")")
  dbGetQuery(con, statement = sql)
})

A minimal Shiny App:
library(shiny)
ui <- fluidPage(
   sidebarLayout(
      sidebarPanel(
        selectizeInput('year', 'Select Year of publication:',
                       choices = c(2017L, 2018L),
                       multiple = TRUE,
                       options = list(maxOptions = 5)
        )
      ),
      mainPanel(
        verbatimTextOutput('text')
      )
   )
)

server <- function(input, output) {
   output$text <- renderText({
     library(glue)
     year_selected <- paste(input$year, collapse = ',')
     glue("SELECT * FROM publications WHERE year IN ({year_selected})")
   })
}

shinyApp(ui = ui, server = server)