text:
Q: file streaming to object store through ibm-cos-sdk I have seen the sample code in the site https://www.npmjs.com/package/ibm-cos-sdk :
function doCreateObject() {
    console.log('Creating object');
    return cos.putObject({
        Bucket: 'my-bucket',
        Key: 'foo',
        Body: 'bar'
    }).promise();
}

Is it possible to supply stream as a body (e.g. file being uploaded) instead of supplying the entire body as once?

A: Try:
var stream = fs.createReadStream('/Users/paulcarron/Desktop/image.jpeg');

function doCreateObject() {
  console.log('Creating object');
  return cos.putObject({
    Bucket: bucket,
    Key: 'foo.jpg',
    Body: stream
  }).promise();
}


text:
Q: Making an ImageView follow touchpoint on screen I am working on an Android app where I would like the user to be able to drag their finger on the screen and have an object I have set up as an Image View (a plane) follow it. I have a somewhat working model of this right now where the image will go to a point that is touched on the screen, but this is not exactly what I am looking to do. Also each time the user touches a new point, my image goes back to its starting spot then go to the users touch point. This is the relevant code:
public boolean onTouch(View v, MotionEvent e){
    switch (e.getAction()){
        case MotionEvent.ACTION_DOWN:
        {

        }
        case MotionEvent.ACTION_UP:
        {
            float x = e.getX();
            float y = e.getY();
            movePlane(x, y);
        }
        case MotionEvent.ACTION_MOVE:
        {

        }
    }
    return true;
}

private boolean movePlane(float endX, float endY){
    ImageView plane = (ImageView) findViewById(planeID);
    float startX = plane.getX();
    float startY = plane.getY();
    TranslateAnimation animation = new TranslateAnimation(startX, endX, startY, endY);
    animation.setDuration(3000);
    animation.setFillAfter(true);
    animation.setFillEnabled(true);
    plane.startAnimation(animation);

    return true;
}

So I know I am probably going to be working inside of the ACTION_DOWN case but I am not sure exactly how I should be handling the event and ImageView accordingly. Any help is really appreciated.

A: you have to set the x and y values after your animation with an AnimationListener -> onAnimationFinished, to avoid the "Also each time the user touches a new point, my image goes back to its starting spot then go to the users touch point" thing.

A: Hi try this link here you can use the params.x and params.y as the x,y co-ordinates you are passing to the method movePlane. Hope it helps.
There is a lot to read on that link, so thought its better i post the important code here. Below is the code you  can use
plane.setOnTouchListener(new View.OnTouchListener() {
  private int initialX;
  private int initialY;
  private float initialTouchX;
  private float initialTouchY;

@Override public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
  case MotionEvent.ACTION_DOWN:
    initialX = params.x;
    initialY = params.y;
    initialTouchX = event.getRawX();
    initialTouchY = event.getRawY();
    return true;
  case MotionEvent.ACTION_UP:
    return true;
  case MotionEvent.ACTION_MOVE:
    params.x = initialX + (int) (event.getRawX() - initialTouchX);
    params.y = initialY + (int) (event.getRawY() - initialTouchY);
    movePlane(params.x, params.y);
    return true;
}
return false;
}
});

Plane is ofcourse the ImageView which you want to be dragged. You can refer the link if you want i took reference from it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Nginx redirect problems params I would like to redirect example.com/e/DownSys/report?classid=123&id=456
to
example.com/e/public/report/?classid=123&id=456
rewrite ^/e/DownSys/report?classid=(\d+)&id=(\d+) /e/public/report/?classid=$1&id=$2 permanent;

but this is not working...

A: A question mark in regular expressions is a special character. If you want to match a question mark, escape it with a backslash. The report part in your regular expression now reads :
"repor followed by an optional t followed by classid"
Aside from that, unless you want to only match this specific classid / id combo, you can condense the expression to:
rewrite /e/DownSys/(. *)  /e/public/$1 permanent ;


text:
Q: Problem installing psi4 environment in jupyter I recently tryed to install psi4 into  a new jupyter environment on.
It worked for ten minuts at first and afterwards told me that py3.6 where missing gen.py files.
After some un-/reinstalling the environment it just stoped working all together.
Atm i'm using a bash script to install the environment.
if  i'm inside the activated environment after the psi4 installation and open python i'm able to import psi4.
However after deactivating the environment and starting a jupyter-notebook i'm unable to import psi4.
content of the bash file i curently use:
conda create --yes -n p4env python=3.6
conda activate p4env (p4env)
which python3.6
conda install --yes python=3.6 psi4 psi4-rt -c psi4
python3.6 "import psi4
print(psi4.__version__)
"
conda install --yes python=3.6 matplotlib
conda install --yes python=3.6 ipykernel
python3.6 -m ipykernel install --user --name p4env
jupyter kernelspec list
conda deactivate
conda env list

Thank you for your help !

A: Since the server already had preinstalled conda packages and i hadn't got sudo priveleges to the server, psi4  isn't persistently stored.
To work arround that you have to make a folder in your jupyter directory the folder of the package.
I paste what worked for me below.

    conda_dir=$HOME/conda-psi4
    mkdir $conda_dir
    conda create --yes python=3.6 -p $conda_dir
    . /opt/conda/etc/profile.d/conda.sh
    conda activate $conda_dir
    conda install --yes python=3.6 psi4 psi4-rt -c psi4 -p $conda_dir
    conda install --yes p ython=3.6 matplotlib -p $conda_dir
    conda install --yes python=3.6 ipykernel -p $conda_dir
    python3.6 -m ipykernel install --user --name p4env
    jupyter kernelspec list
    conda deactivate
    conda env list


text:
Q: How to Count unique values in a column of a datagridview? I need to count the rows of a column except the duplicate ones
House Number
123
124
11
12
11
11
Total House Number: 4
I have searched and can't find the right syntax for my code.
I tried dictionary but it seems that it is not right for my code.
I am a complete beginner in c#
                //Total House
            int House = 0;
            for (int row = 0; row < dataGridView1.Rows.Count; ++row)
            {
                if ((string)dataGridView1.Rows.[row].Cells("House_Number").Distinct())
                {
                    House++;
                }
            }

            TotalHouse.Text = "Total Houses   " + $"{House}";

I tried the above code but it has an error Identifier expected.

A: Your code has a few potential problems, but let's start with the ones that will prevent it from compiling.
if ((string)dataGridView1.Rows.[row].Cells("House_Number").Distinct())

One problematic bit here is Rows.[row].  There shouldn't be a period there.  If you have a period like that, C# will expect an identifier to follow it, not another operator.  In this case, you have the [] operator following it, which is invalid.  It should probably look like this:
if ((string)dataGridView1.Rows[row].Cells("House_Number").Distinct())

We're getting closer.  However, the test inside an if statement must evaluate to a bool--that's true or false.  Yours evaluates to a string because you're casting the whole thing to a string.  That's because this part runs first:
dataGridView1.Rows[row].Cells("House_Number").Distinct()

Then this part runs:
(string)

So the whole thing becomes a string.  We'll have to remove that (string) bit.
Let's take a closer look at dataGridView1.Rows[row].Cells("House_Number").Distinct().  Cells isn't a method--it's a property.  That means you can't use the syntax Cells("House_Number").  However, the result of Cells is a DataGridViewCellCollection, which allows [] syntax, so you can do something like Cells["House_Number"].
Distinct() isn't going to give you a bool value--it will give you a collection of unique cells in the form of something called an IEnumerable.
dataGridView1.Rows[row].Cells.Distinct() isn't going to give you distinct cells in a column--it's going to give you distinct cells in a row.  That's probably not what you want.
You're probably going to want something that looks like this:
int houses = dataGridView1.Rows
    .Cast<DataGridViewRow>()
    .Select(r => (int)r.Cells["House_Number"].Value)
    .Distinct()
    .Count();

Walking through this:

*

*Start with dataGridView1.

*Get a DataGridViewCellCollection of rows: .Rows

*DataGridViewCellCollection is pretty old, so it implements IEnumerable instead of IEnumerable<DataGridViewRow>.  We need to turn it into an IEnumerable<DataGridViewRow>, so we call LINQ's Cast<DataGridViewRow>().

*Use LINQ to turn that into an IEnumerable<int>: .Select(r => (int)r.Cells["House_Number"].Value)
a. The argument to Select is a lambda expression.  It takes one argument, r, which is a DataGridViewRow.  It will return an int.
b. Get the cells for the row: .Cells
c. Get the specific cell we want: ["House_Number"]
d. Get the value of that cell
e. The value is returned as an object; we need to cast it to an int: (int)

*Use LINQ to turn that IEnumerable<int> into another one that only has distinct values: .Distinct()

*Count our results: .Count()
You'll need a reference to System.Linq for this to work.  Put this at the top of your file if it isn't already there:
using System.Linq;

A: You can achieve this easily by adding a nuget reference to System.Data.DataSetExtensions
and then using linq to select the distinct house numbers:
var count = dataGridView1.AsEnumerable().Select(dr => dr["House_Number"]).Distinct().Count();
Otherwise you could achieve this using a hashset:
var hs = new HashSet<string>();

foreach (DataRow dataRow in dataGridView1.Rows)
{
    hs.Add(dataRow["House_Number"].ToString());
}

TotalHouse.Text = "Total Houses   " + $"{hs.Count}";


text:
Q: Mac OS counterpart to Sysinternals and Powertoys As a developer coming from a Windows background, I'd always find the different Powertoys and Sysinternals apps as invaluable tools in aiding programming. Is there something similar for a developer to watch for in the Mac world?

A: Top 10 DTrace scripts for Mac OS X is an article that describes ten really useful tools that are Mac equivalents of some of the Sysinternals tools such as ProcessMon, FileMon, etc.
The post's author created some of the scripts when he made the DTraceToolkit, which he says Apple then customized and enhanced for inclusion by default in Mac OS X.
Some script names look like they end with the word "noop," which might be a bit confusing--it's actually "snoop." As in spying on system activity.

A: A lot of those types of tools are included with the Mac OS, and some are available separately from Apple.
There's no Mac equivalent of the registry - everything goes in the file system somewhere - and you can use fs_usage to watch that.  In a terminal:

sudo fs_usage

Check out Instruments, part of the Apple developer tools distribution.

A: Mac OS X comes with a lot of unix tools like sar, top, etc. What metrics are you looking for specifically?

A: Not as such. Some of the Powertoys implement features that are built-in to the OS, some are available as various utility programs.
As for Sysinternals, there are quite a lot of them. If you want specifics I'd need a better idea of what you use, but you could probably duplicate 90% of the functionality just from a terminal window. Learning how to use bash and the normal Unix utilities would be a very good skill to have.

A: http://newosxbook.com/index.php?page=downloads provide almost exact counterparts, albeit in CLI mode - with the upside that they also work on (jailbroken) iOS.


text:
Q: opacidad para fondo de div y no para el contenido Buenas noches
Tengo un div con un background-image pero quiero ponerle opacity (al menos su efecto) para esa imagen. Si se lo pongo al div, la opacidad afecta a todo lo que ponga en él. ¿Hay alguna forma de hacerlo sin modificar la imagen?
Muchas gracias

A: Si entendi bien, creo que quieres hacer algo como esto...
div {width: 500px; height: 500px; display: block; position: relative;}
div::after {content: ""; background: url(image.jpg); opacity: 0.5; top: 0; left: 0; bottom: 0; right: 0; position: absolute; z-index: -1; }

Espero te sirva

A: Para hacer lo que quieres, puedes utilizar la propiedad ::before de CSS.
En el ::before podrás mostrar la imagen y aplicar la opacidad que quieres sin afectar al div.
Este es un ejemplo:

body
{
  background: url(//image.freepik.com/free-vector/triangular-background_23-2147508098.jpg) center center;

  background-color: #ccc;
}
.myDiv {
  position: relative;
  z-index: 5;
  height: 250px;
  width: 300px;
  color: #FFF;
  font-size: 400%;
  padding: 20px;
}

.myDiv::before {
    content: "";
    position: absolute;
    z-index: -1;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: url(//files.ctctcdn.com/77be3546001/91b996da-b256-4ec5-9a6e-5bf92c3922d0.jpg) center center;
    opacity: .7;
}
<div class="myDiv">
    Hello, I am a DIV :)
</div>

A: Te recomiendo que proceses la imagen con Photoshop y le pongas la opacidad que quieras y la guardes como PNG que conserve el valor alpha (transparencia), a nivel sintáctico es más limpio.
Si no te gusta esta opción podrías crear dos  una para el fondo y una para el texto, y dar distintas "class" a cada div, y con CSS opacity: 0.5; a la del fondo.


text:
Q: ImageButton usage and changing pictures
*

*how do you change the image of an ImageButton during runtime?
for Button, you can say setText("some text")
for ImageButton is there any setImage() such that I can change the image  during runtime?

*where do you place the pictures? drawable hdpi,ldpi,mdpi..what exactly is the difference between all of them?

A: There's an API for this http://developer.android.com/reference/android/widget/ImageView.html#setImageResource%28int%29
You can go through the documentation for more details.
You can place the images in drawable folder. For more details, have a look at http://developer.android.com/guide/practices/screens_support.html


text:
Q: Which is the easy way to build login/registration/admin area type website in java I am php programmer but i am learning java now. i have finished the core java and build small projects using jdbc , mysql gui etc.
Now my boss wants to build the website where user will collect points  and they can shop based upon points left.
But the initial phase will be only the logs/registration/admin area etc.
Now i have two options
1)Do in php
2)DO in java
I really want to do in java thats why i was learning it. Now now the project came early.
I wanted to learn  spring , spring mvc , hibernate etc , design patterns but now i can't spend time first to learn.
i want to ask that what will be good solution to go at it. Initially was thinking of doing the website in JSP.Is that ok
O i am thinking of using Wicket and not using hibernate, is wicket enough to build ecommerce site. or i need anything else as well
I know only core java , what should i do

A: PHP development is very action/template-oriented, AFAIK. Wicket is a component-based framework, that heavily applies object-orientation concepts, and that may take some time to grasp. If you don't have much experience with OO, and your deadlines are tight, maybe you'll prefer an action-framework (Struts2, SpringMVC), which is far better than raw JSP. But, if you have some time to spend, and the will to learn, Wicket is definitely a great framework!
Spring is also nice, and while dependency injection is not something you see often in PHP, it's simple enough (Spring is well documented, its reference doc is actually useful, and you'll find many tutorials and examples on the Internet), and it's definitely worth learning.
Hibernate is a very good framework for persistence, but if all you know is plain SQL/JDBC, it takes some time to master it to the point that you don't get frustrated with mapping, and lazy-loading errors. Again, try it if you have some time to spare and the will to learn.
Wicket+Spring+Hibernate is a really nice combo, I use them a lot. It may or may not be the best stack for your case. As everything in IT, it depends on the context. But I think they are very sound technologies, individually or combined.

A: Consider Struts 2.  It is both effective and there is a good size community here if you have any questions.  I don't know wicket, but any web framework is better than straight JSP.
Hibernate is nice but since you have a lot on your plate you should probably stick with straight JDBC for now. Spring is also very nice, it is easy to integrate spring DI with struts2 (so easy as a matter of fact I would recommend you just start that way).

A: One of the fastest ways to get a Java webapp up and running is to use Play Framework.


text:
Q: how to display a 3-4-3 flexbox table? I'm trying to get my content to display like this
picture
But mine shows up like this picture
How do I make it so one row has 3 columns, the second one has 4 and the last has 3? with flexbox? Thank you
.flex-container {
    display: flex;
    flex-flow: row wrap;
    justify-content: center;
    background-color: white;
    align-items:baseline;
    width: 60em;
    margin: auto;
    padding: .5em;
    justify-content: space-between;
}

.flex-container div {

    flex: 1 0 30%;
    margin: .5em 0;
    text-align: center;
    line-height: 1.5em;
    font-size: 1em;
    border: 0.1em solid black;
    padding: 5px;
    box-sizing: border-box;
    justify-content: space-between;

}

A: You can accomplish this by placing the cells into rows which themselves are stacked using flex-direction: column.
The styling is crude, but try something like this:

.outer {
    display: flex;
    flex-direction: column;
}

.row {
    display: flex;
    flex-direction: row;
}

.cell {
    margin: 1.0em;
    padding: 1.0em;
    border: 1px solid black;
    flex-grow: 1;
}

Cell 1

Cell 2

Cell 3

Cell 3

Cell 4

Cell 5

Cell 6

Cell 7

Cell 8

Cell 9


text:
Q: How wrap a command that is interactive I am building an ftp wrapper that does some stuff before I spawn, I could easily do it in a shell script but wondering how I could do it in go
While exec.Command works for simple commands.
out, err := exec.Command("ls").Output() // Works

How do I wrap commands that are interactive e.g., ftp
out, err := exec.Command("ftp").Output()

It just exits. How do I deal with stdin ?
e.g., bash equivalent :
> ./t.sh
Welcome to myftp

ftp> open blahblah.com

> cat t.sh
#!/bin/bash
echo "Welcome to myftp "
#extra commands such as auth/authoriz.. etc.,
shift
echo "$@"
ftp

c++ equivalent :
int main() {
    system("ftp");
    return 0;
}

A: I would probably do something like this which is more native and doesn't involve an external package
package main
import (
    "os"
    "os/exec"
)

func main() {

    cmd := exec.Command("ls")
    // redirect the output to terminal
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr

    cmd.Run()

}

A: Traditionally these sorts of interactive scripting exercises are best done with expect.  May I suggest checking out a pure Go equivalent?
From the readme:
child, err := gexpect.Spawn("python")
if err != nil { panic(err) }
child.Expect(">>>")
child.SendLine("print 'Hello World'")
child.Interact()
child.Close()

A: To run any commands which will prompt for user input:
cmd := exec.Command("cf", "login")
cmd.Stdout = os.Stdout
cmd.Stdin = os.Stdin

cmd.Run()

A: A command can be "wrapped" using the following complete script, based on reticentroot's answer and this answer regarding obtaining exec command return codes (go 1.12+):
package main

import (
    "os"
    "os/exec"
)

var (
    bin = "py"
    args = []string{"-3.8"}
)

func main() {
    cmd := exec.Command(bin, append(args, os.Args[1:]...)...)
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    cmd.Stdin = os.Stdin
    if err := cmd.Run() ; err != nil {
        if exitError, ok := err.(*exec.ExitError); ok {
            os.Exit(exitError.ExitCode())
        }
    }
}


text:
Q: Feature Combination for Object Detection I am trying to combine LBP-HOG for object detection. This is actually a part of model free object tracker. I have extracted both features and fed them in to a Linear SVM. here is the code.
svm  = trainSVM( pos{j},neg{j} );  // for LBP features where pos{j} and neg{j} are mxn matrix.

svmHog=trainSVM( posHog{j},negHog{j} ); // for HOG features. i used VLFEAT for both LBP and HOG

The SVM light library was used for the purpose of training.
I have used firstly the LBP feature for classification of window using Sliding window approach with the stride of 4.
The top 100 predicted labels were then fed into HOG classifier. but the result i obtained stayed on top always like 44x1, 87x1, 202x1. Am i missin something? My code for detection follows:
function detect(im,model,modelHog,wSize)
%{
this function will take three parameters
    1.  im      --> Test Image
    2.  model   --> trained model
    3.  wStize  --> Size of the window, i.e. [24,32]
and draw rectangle on best estimated window
%}
topLeftRow = 1;
topLeftCol = 1;
[bottomRightCol bottomRightRow d] = size(im);
fcount = 1;
% this for loop scan the entire image and extract features for each sliding window
for y = topLeftCol:3:bottomRightCol-wSize(2)
    for x = topLeftRow:3:bottomRightRow-wSize(1)
        p1 = [x,y];
        p2 = [x+(wSize(1)-1), y+(wSize(2)-1)];
        po = [p1; p2];
        img = imcut(po,im);
        hog= vl_hog(single(img),8);
        hog = hog(:,:,1:9) ; % + hog(:,:,10:18);

        lbp= vl_lbp(single(img),16);
        %lbp = lbp(:,:,1:9)+ lbp(:,:,10:18);

        featureVector{fcount} =  lbp; %cat(3,lbp,hog); %HOG(double(img));
        featureVector{fcount}=featureVector{fcount}(:)';
        featureVector{fcount}=transpose(featureVector{fcount});

        featureVectorHOG{fcount} =  hog; %cat(3,lbp,hog); %HOG(double(img));
        featureVectorHOG{fcount}=featureVectorHOG{fcount}(:)';
        featureVectorHOG{fcount}=transpose(featureVectorHOG{fcount});

        boxPoint{fcount} = [x,y];
        fcount = fcount+1;
        x = x+1;
    end
end
lebel = ones(length(featureVector),1);
P = double(cell2mat(featureVector));
% each row of P' correspond to a window
[~, predictions] = svmclassify(P',lebel,model); % classifying each window
[sortedValues,sortIndex] = sort(predictions(:),'descend');
for j=1:100%length(sortedValues)
    bBox{j} = cell2mat(boxPoint(sortIndex(j)));
    fVectorHOG{j}=featureVectorHOG{sortIndex(j)};
end
lebel = ones(length(fVectorHOG),1);
P = double(cell2mat(fVectorHOG));
[~, predictions] = svmclassify(P',lebel,modelHog); % classifying each window
[a, indx]= max(predictions);
bBox = cell2mat(boxPoint(indx));
rectangle('Position',[bBox(1),bBox(2),24,32],'LineWidth',1, 'EdgeColor','r');
end


text:
Q: Javascript linking failed into HTML5 I have the following problems with linking a javascript file into a html5 project
I'm working with 2 js files for the project: one ( and the main js fail ) is in the same folder with html file. The other js file is in another folder.
So I link them both in my html file, but the second js file seems like not working.
I want to mention that if I put the code from the second js file into the first one, the function is working prefectly.
My folder structure:
FolderStructure here
HTML

<!DOCTYPE html>
<html>
<head>
    <title>HTML5 Puzzle</title>
    <script>

    </script>
</head>

<body onload="init();">
    <canvas id="canvas"></canvas>
</body>

</html>

proiect.js

const PUZZLE_DIFFICULTY = 4;
const PUZZLE_HOVER_TINT = '#009900';

var _canvas;
var _stage;

var _img;
var _pieces;
var _puzzleWidth;
var _puzzleHeight;
var _pieceWidth;
var _pieceHeight;
var _currentPiece;
var _currentDropPiece;

var _mouse;

function init(){
    _img = new Image();
    _img.addEventListener('load',onImage,false);
    _img.src = "mke.jpg";
}

xxs.js

const PUZZLE_DIFFICULTY = 4;
const PUZZLE_HOVER_TINT = '#009900';

var _canvas;
var _stage;

var _img;
var _pieces;
var _puzzleWidth;
var _puzzleHeight;
var _pieceWidth;
var _pieceHeight;
var _currentPiece;
var _currentDropPiece;

var _mouse;

function shufflePuzzle(){
    _pieces = shuffleArray(_pieces);
    _stage.clearRect(0,0,_puzzleWidth,_puzzleHeight);
    var i;
    var piece;
    var xPos = 0;
    var yPos = 0;
    for(i = 0;i < _pieces.length;i++){
        piece = _pieces[i];
        piece.xPos = xPos;
        piece.yPos = yPos;
        _stage.drawImage(_img, piece.sx, piece.sy, _pieceWidth, _pieceHeight, xPos, yPos, _pieceWidth, _pieceHeight);
        _stage.strokeRect(xPos, yPos, _pieceWidth,_pieceHeight);
        xPos += _pieceWidth;
        if(xPos >= _puzzleWidth){
            xPos = 0;
            yPos += _pieceHeight;
        }
    }
    document.onmousedown = onPuzzleClick;
}

A: Try using <script type="text/javascript" src="./proiect.js"></script>
where ./ means current folder.
No need to re-declare the variables you already declared. Erase this from the second .js file (the first .js file from the top in the HTML document must keep this declaration):
var imagine;
var piese;
var wJoc;
var hJoc;
var wPiesa;
var hPiesa;
var picked;
var dropped;

var mouseXY;

Just use them without declaration (in the file that comes last - declare the variables in proiect.js)
Also, xxs.js is in the same folder as index.html so that would make it:
<script type="text/javascript" src="lib/xxx.js"></script>

A: Try flipping the order of your javascript files in the HTML code. The order of includes can matter.
If that doesn't work, post the javascript code for review.


text:
Q: Trouble with Cron sending email after python script execution I have a python script I'm successfully executing every night at midnight. It's outputting the log file, however, I want it to also send an email with the log contents.
I've read this is pretty use to do, but I've had no luck thus far. I've tried this but it does not work. Does anyone else have some other suggestions?
I'm running Ubuntu 14.04, if that makes a difference with the mail smtp.
MAILTO=mcgoga12@wfu.edu

0 0 * * * /usr/bin/python /home/grant/Developer/Projects/StudyBug/Main.py > /home/grant/Desktop/Studybuglog.log 2>&1

A: Cron will send everything sent by the command to its standard output (what would be sent to the screen if you ran the command from the command line) in an email to the email address in MAILTO.
Unfortunately for you, you are changing the behaviour of this command using shell redirection.  If you ran the command exactly as written above, there would be nothing shown on the screen because everything is written to the file (because you redirect standard output to the file using the '>' operator).
If you want an email, remove the >, and everything after it and then test.
If you also want to write to a log file, you might try the 'tee' command, or changing your script to take a log file as a command line argument, and write to both the log file and the standard output.


text: Q: My question is about weird behavior of boot manager after installing Ubuntu I recently installed Ubuntu by freeing some space from I hard disk. It is working fine without any issues. But i see this weird behavior in boot manager. Every time i start ubuntu a new link is generating.


text:
Q: Palindrome that ignores spaces and special characters and converts all uppercase letters in the string to lowercase I'm going to make a palindrome which should ignore spaces and special characters and should convert all uppercase letters in the string to lowercase. I have done everything, but when I run my program, neither of these two functions work. Convert uppercase to lowercase and ignore all non-uppercase letters. Could any of you help me to solve what is the problem?
#include<stdio.h>
#define SIZE 1000
#include <ctype.h>
#include<string.h>

// function that checks if it is a palindrome
int isPalindrome(char inputString[]) {

    int l = 0;
    int r = strlen(inputString) - 1;

    while (r > l)
    {
        // will check all letters are equal to each other
        if (inputString[l++] != inputString[r--]) {
            return 0;
        }// return 0 if not palindrome
    }
    // palindrome

    return 1;

}

// function that ignores all non - letters
int no_special_characters(char inputString[])
{
    char temp[SIZE];
    int temp_index = 0;
    int abc = 0;
    int r = strlen(inputString);
    for (int i = 0; i < r; i++)
    {
        char abc = inputString[i];
        if (isalpha(abc) != 0)
        {
            temp[temp_index++] = abc;
        }
    }
    temp[temp_index] = '\0';

    return isPalindrome(temp);
}

// function that converts uppercase letters to lowercase

void to_lower(char inputstring[]) {

    int length = strlen(inputstring);

    for (int i = 0; i < length; i++)
    {
        if (isupper(inputstring[i]))
            inputstring[i] = tolower(inputstring[i]);
        else if (islower(inputstring[i]))
            inputstring[i] = toupper(inputstring[i]);
    }

    return 0;
}

int main(void) {

    int try_again = 1;
    int end_run = 0;

    while (try_again == 1) {
        int try_again;

        char inputString[SIZE] = "";

        printf("Enter a string to check if it is a palindrome!\n");
        //Scans the input string.
        scanf_s("%s", &inputString, SIZE);

        //Sends the string to the isPalindrome function. //If the return value is 1(true), the if statement is executed, otherwise the else statement.
        if (isPalindrome(inputString)) {
            printf("That is a palindrome!\n");
        }
        else {
            printf("This is not a palindrome!\n");
        }

        printf("Do you want to try again: 1 for yes 0 for No?");
        scanf_s("%d", &try_again);

        //Changes the value of running depending on whether you want to continue or not.
        if (try_again != 1) {
            end_run = 0;
        }
    }

    return 0;
}

A: 1 - Don't use scanf
You shouldn't use scanf to read input from the console, especially in a loop. I'm not an expert in scanf_s in particular, but that whole family of functions can cause weird bugs if you don't know how they work. I recommend you read this article, it explains it better that I can.
2 - Your loop doesn't work
You are defining try_again in function scope and then redefining it in block scope: they are two different variables.
Your code is essentially this:
int main(void) {
    int try_again = 1;
    while (try_again == 1) {
        int try_again;
        scanf_s("%d", &try_again);
    }
}

Which will run forever, since the while loop is checking the first variable, while you are assigning to the second one. It should look more like this:
int main(void) {
    int try_again = 1;
    while (try_again == 1) {
        // int try_again;
        // ^^ Don't refefine - use the one already defined
        try_again = some_function_to_read_input();
    }
}

3 - to_lower doesn't actually convert to lowercase
It converts uppercase to lowercase and lowercase to uppercase. This means "Aa" becomes "aA", which is not a palindrome even though it should be by your definition.
The function doesn't need to return anything, since it changes the string in place. You can simply call it like this:
int isPalindrome(char inputString[]) {
    to_lower(inputString);
    // Rest of code
}

4 - You aren't calling no_special_characters
You simply aren't calling it. Either you do it in your main, something like:
// main
if (no_special_characters(inputString)) {
    // Rest of code
}

Or you change it to return the modified string and call it from inside isPalindrome:
void no_special_characters(char inputString[]) {
  // Remove all special characters, in place
}

int isPalindrome(char inputString[]) {
    no_special_characters(inputString);
    to_lower(inputString);
    // Rest of code
}


text:
Q: C# Protobuf, submitting generic type information I want to serialize C# objects using Protobuf, send them via network and deserialize them on the "other" side.
So Client A has e.g. the following Code:
Serializer.Serialize<ClassA>(stream, instance);

Now, I want to be able to transmit the typeinformation being "ClassA", too. On the receiving side, Client B has to call:
ClassA instance = Serializer.Deserialize<ClassA>(stream);

Is there an elegant way to directly transmit the generic typeinformation? The only other way that I could think of is to define a gigantic enum, containing all types that can be serialized and put this Information together with the actual instance of ClassA in a wrapper class.
Hints or possible solutions are very much appreciated!

A: Json.Net can serialize the objects into json, and if you give it the correct hints, it will send through the binary information required to deserialize it on the other side.
If you look at the example here: http://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm
They use a List, where the T is the generic parameter. So in your case T would be something else, but the principle is the same.


text:
Q: Highcharts dynamically creating a primitives and setting position and size Is it possible to place the rectangles over the lines?
One rectangle should have one or more lines in yAxis.
Rectangles should be added, moved and resized dynamically depends on data.
Here's a FIDDLE.
HTML:

   <button id="create">Create serier and add</button>

JS:
var chart;
$(document).ready(function(){

var counter = 0;
var addRect = function (chart, x1, y1, x2, y2, r) {
    chart.renderer.rect(x1, y1, x2, y2, r)
        .attr({
            'stroke-width': 2,
            stroke: 'red',
            fill: new Highcharts.Color('#ff0000').setOpacity(0.4).get(),
            zIndex: 10
        })
        .add();
}

function randomData(len, counter){
    var arr = [];
    i = 0;
    var rand;
    while (i<len) {
        if (!(Math.floor(Math.random()*3))) {
            arr.push(null);
        }
        //else {
            rand = Math.random()*5;
            i += rand;
            arr.push(counter);
            rand = Math.random()*5;
            i += rand;
            arr.push(counter);
            arr.push(null);
        //}
    }
    return arr;
}

var options = {
    chart:{
        renderTo:'graph',
        type:'line'
    },
    title:{
        text:null
    },
    xAxis: {
    },
    plotOptions:{
        series:{
            animation:false,
        }
    }
}

chart = new Highcharts.Chart(options,
        function (chart) {
            addRect(chart, 70, 120, 250, 120, 5);
            addRect(chart, 500, 120, 400, 120, 5);
            addRect(chart, 1200, 120, 150, 120, 5);
        });
var i = 1, s1,s2,s3,s4;

   function createChart(){
    s1 = chart.addSeries({
        data:randomData(20, counter++),
        name:'Line'+counter,
        lineWidth: 20},false);
    chart.redraw();
}

$('#create').click(function(){  createChart() });

})


text:
Q: Multiple Intent flags for starting a new Activity in Android I'm trying to add more flags at an Intent for launching a new Activity inside a BroadcastReceiver, responding to a particular intent sent from another part of the app.
I've added as I noticed by the LogCat messages the FLAG_ACTIVITY_NEW_TASK flag at the Intent I created and then other ones but I get the same error in LogCat as the FLAG_ACTIVITY_NEW_TASK was not there.
Here's the code:
 public class actReceiver extends BroadcastReceiver {
 ...
    public void onReceive(Context context, Intent intent) {
    ...
     else if (intent.getAction().equals("something")) {
                Intent prefAct = new Intent(context, PreferencesActivity.class)
                prefAct.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                       .setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
                       .setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
                       .setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(prefAct);
            }
     ... }
... }

And the particular LogCat error:
Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

A: setFlags just assign the argument, as you can see from the snippet
public Intent setFlags(int flags) {
    mFlags = flags;
    return this;
}

so in your case you are just assign the last one. To fix it put it on or
 prefAct.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_SINGLE_TOP);

or use addFlags which does the same thing
public Intent addFlags(int flags) {
    mFlags |= flags;
    return this;
}

A: use addFlags() instead of setFlags() to add additional flags.
http://developer.android.com/reference/android/content/Intent.html#addFlags(int)
setFlags() sets the complete set of flags to be used, so you would have to | all flags to be used in here. addFlags() can be called multiple times, and does the | of flags for you.

A: simple way of doing it with kotlin and anko see snippet
see example snapshot
startActivity(intentFor().clearTask().newTask().noHistory())
hope this helps


text:
Q: Change each item of string in Ruby What I have
"path1/path2/path3"

what I want
"my_namespace:path1/my_namespace:path2/my_namespace:path3"

and I did:
a = "path1/path2/path3"
b = a.split("/").map{ |item| "my_namespace:"+ item}
puts b.join("/")

Of course, it works. But I'm curious if there is any other better way to do that.

A: a.gsub(/(?<=^|\/)/, "my_namespace:")
# => "my_namespace:path1/my_namespace:path2/my_namespace:path3"

A: Seems like a good use case for String#gsub:
a = "path1/path2/path3".gsub(%r{[^/]+/?}) { |m| "mynamespace:#{m}" }
p a #=> "mynamespace:path1/mynamespace:path2/mynamespace:path3"

A: Maybe you meant different namespaces for your paths. If so then you can use zip
"path1/path2/path3".split('/').zip(['namespace1','namespace2','namespace3']).
  map { |p,n| n + ':' + p }.join('/')

=> "namespace1:path1/namespace2:path2/namespace3:path3"


text:
Q: XML encoding is not returning HTML entities in SOAP I have the following test method.
public String ping(String xml) {
    return "<PingResult>Service is Live</PingResult>";
}

What I get back when I call it is the following:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <PingResponse xmlns="http://www.url.com/service">
        <PingResult>Service is Live</PingResult>
      </PingResponse>
   </soapenv:Body>
</soapenv:Envelope>

Substituting < with < does not help. Any idea how I can actually return those < and > symbols? It looks like no matter what I substitute them with it doesn't work.
EDIT
PingResponse.java
package user;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "PingResponse")
public class PingResponse implements java.io.Serializable {

    private String pingResult;

    @XmlElement(name = "PingResult")
    public String getPingResult() {
        return pingResult;
    }

    public void setPingResult(String pingResult) {
        this.pingResult = pingResult;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(PingResponse.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("user", "PingResponse"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("PingResult");
        elemField.setXmlName(new javax.xml.namespace.QName("", "PingResult"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://schemas.xmlsoap.org/soap/encoding/", "string"));
        elemField.setNillable(true);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
        java.lang.String mechType,
        java.lang.Class _javaType,
        javax.xml.namespace.QName _xmlType) {
        return
        new org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
        java.lang.String mechType,
        java.lang.Class _javaType,
        javax.xml.namespace.QName _xmlType) {
        return
        new org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }
}

ServicesSoapImpl.java
package user;

import user.PingResponse;

public class ServicesSoapImpl implements user.serviceSoap {

    public PingResponse ping(String xml) throws java.rmi.RemoteException {

        PingResponse response = new PingResponse();
        response.setPingResult("Service is Live");
        return response;

    }

}

And I do have an update, after adding all of the above I am able to get something different. It is not exactly what I need, but it is close to it.
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <soapenv:Body>
      <PingResponse xmlns="user" xmlns:ns1="user" xsi:type="ns1:PingResponse">
         <pingResult>Service is Live</pingResult>
      </PingResponse>
   </soapenv:Body>
</soapenv:Envelope>

So there is some extra stuff there that wasn't before and pingResult is lower case for some reason.

A: The schema class used in the response should look something like this:
@XmlRootElement(name = "PingResponse")
public class PingResponse {

private String pingResult;

@XmlElement(name = "PingResult")
public String getPingResult() {
    return pingResult;
}

public void setPingResult(String pingResult) {
    this.pingResult = pingResult;
}

}


text:
Q: Webpack won't compile if i use the dynamic import function I have a function that looks like this:
async importer ( path ) {
    const maxAttempts = 4;
    let p = Promise.reject();

    const rejectDelay = reason => {
        return new Promise((resolve, reject) => {
            setTimeout(reject.bind(null, reason), 1000);
            });
        };

    const attempt = () => {
        return new Promise((resolve, reject) => {
            import('../../src/pages/desktop/index.jsx').then(data => {
                resolve(data);
            }).catch(error => {
                reject(error);
            });
        });
    };

    for(let i = 0; i < maxAttempts; i++) {
      p = p.catch(attempt).catch(rejectDelay);
    }

    p = p.then(data => {
        console.log(data);
    }).catch(error => {
        console.error(error);
    });
}

If I include the import part my webpack won't compile and eventually will crash. Node then gives me this error:
<--- Last few GCs --->

[1864:00000260CFC24890]   242486 ms: Mark-sweep 1317.0 (1441.8) -> 1301.3 (1441.3) MB, 667.9 / 0.1 ms  (average mu = 0.316, current mu = 0.275) allocation failure scavenge might not succeed
[1864:00000260CFC24890]   243400 ms: Mark-sweep 1318.2 (1442.8) -> 1304.5 (1442.8) MB, 662.4 / 0.0 ms  (average mu = 0.296, current mu = 0.275) allocation failure scavenge might not succeed

<--- JS stacktrace --->

==== JS stack trace =========================================

    0: ExitFrame [pc: 000003DB79A50361]
    1: StubFrame [pc: 000003DB79A0DEF8]
Security context: 0x0369d989d949 <JSObject>
    2: /* anonymous */ [0000035D7180D9D1] [C:\Users\Rick\PhpstormProjects\witteveen_new_dev\node_modules\acorn\dist\acorn.js:~4658] [pc=000003DB7C8C0810](this=0x008c53a992d1 <Parser map = 000003D9D2615211>,2)
    3: /* anonymous */ [0000035D7180D7D1] [C:\Users\Rick\PhpstormProjects\witteveen_new_dev\node_modules\acor...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 00007FF7DCA221C5
 2: 00007FF7DC9FA056
 3: 00007FF7DC9FAA40
 4: 00007FF7DCE4499E
 5: 00007FF7DCE448D7
 6: 00007FF7DD11D804
 7: 00007FF7DD113444
 8: 00007FF7DD111B18
 9: 00007FF7DD11B487
10: 00007FF7DD11B506
11: 00007FF7DCCDC311
12: 00007FF7DD436DEA
13: 000003DB79A50361
events.js:167
      throw er; // Unhandled 'error' event
      ^

Error: EOF: end of file, write
    at Socket._write (internal/net.js:58:25)
    at doWrite (_stream_writable.js:410:12)
    at writeOrBuffer (_stream_writable.js:394:5)
    at Socket.Writable.write (_stream_writable.js:294:11)
    at compilerCallback (C:\Users\Rick\PhpstormProjects\witteveen_new_dev\node_modules\webpack-cli\bin\cli.js:512:30)
    at finalCallback (C:\Users\Rick\PhpstormProjects\witteveen_new_dev\node_modules\webpack\lib\Compiler.js:204:39)
    at hooks.done.callAsync.err (C:\Users\Rick\PhpstormProjects\witteveen_new_dev\node_modules\webpack\lib\Compiler.js:253:14)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (C:\Users\Rick\PhpstormProjects\witteveen_new_dev\node_modules\tapable\lib\HookCodeFactory.js:32:10), <anonymous>:6:1)
    at AsyncSeriesHook.lazyCompileHook (C:\Users\Rick\PhpstormProjects\witteveen_new_dev\node_modules\tapable\lib\Hook.js:154:20)
    at emitRecords.err (C:\Users\Rick\PhpstormProjects\witteveen_new_dev\node_modules\webpack\lib\Compiler.js:251:22)
    at Compiler.emitRecords (C:\Users\Rick\PhpstormProjects\witteveen_new_dev\node_modules\webpack\lib\Compiler.js:366:39)
    at emitAssets.err (C:\Users\Rick\PhpstormProjects\witteveen_new_dev\node_modules\webpack\lib\Compiler.js:245:10)
    at hooks.afterEmit.callAsync.err (C:\Users\Rick\PhpstormProjects\witteveen_new_dev\node_modules\webpack\lib\Compiler.js:352:14)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (C:\Users\Rick\PhpstormProjects\witteveen_new_dev\node_modules\tapable\lib\HookCodeFactory.js:32:10), <anonymous>:6:1)
    at AsyncSeriesHook.lazyCompileHook (C:\Users\Rick\PhpstormProjects\witteveen_new_dev\node_modules\tapable\lib\Hook.js:154:20)
    at asyncLib.forEach.err (C:\Users\Rick\PhpstormProjects\witteveen_new_dev\node_modules\webpack\lib\Compiler.js:349:27)
    at done (C:\Users\Rick\PhpstormProjects\witteveen_new_dev\node_modules\neo-async\async.js:2854:11)
    at C:\Users\Rick\PhpstormProjects\witteveen_new_dev\node_modules\neo-async\async.js:2805:7
    at C:\Users\Rick\PhpstormProjects\witteveen_new_dev\node_modules\graceful-fs\graceful-fs.js:43:10
    at FSReqCallback.oncomplete (fs.js:148:20)
Emitted 'error' event at:
    at onwriteError (_stream_writable.js:425:12)
    at onwrite (_stream_writable.js:456:5)
    at Socket._write (internal/net.js:62:14)
    at doWrite (_stream_writable.js:410:12)
    [... lines matching original stack trace ...]
    at FSReqCallback.oncomplete (fs.js:148:20)

The weird thing is, is that if I use the import function in another file it works perfectly but in this file it just won't work and the webpack compiler just gives up.


text:
Q: Slow array operation in python My question is probably very simple but I can't figure out a way to make this operation faster
  print a[(b==c[i]) for i in arange(0,len(c))]

where a,b and c are three numpy arrays. I'm dealing with arrays with millions of entry and the piece of code above is the bottleneck of my program.

A: Are you trying to get the values of a where b==c?
If so, you can just do a[b==c]:
from numpy import *

a = arange(11)
b = 11*a
c = b[::-1]

print a        # [  0   1   2   3   4   5   6   7   8   9  10]
print b        # [  0  11  22  33  44  55  66  77  88  99 110]
print c        # [110  99  88  77  66  55  44  33  22  11   0]
print a[b==c]  # [5]

A: You should probably look into broadcasting. I assume you are looking for something like the following?
>>> b=np.arange(5)
>>> c=np.arange(6).reshape(-1,1)
>>> b
array([0, 1, 2, 3, 4])
>>> c
array([[0],
       [1],
       [2],
       [3],
       [4],
       [5]])
>>> b==c
array([[ True, False, False, False, False],
       [False,  True, False, False, False],
       [False, False,  True, False, False],
       [False, False, False,  True, False],
       [False, False, False, False,  True],
       [False, False, False, False, False]], dtype=bool)
>>> np.any(b==c,axis=1)
array([ True,  True,  True,  True,  True, False], dtype=bool)

Well for large arrays you can try:
import timeit

s="""
import numpy as np
array_size=500
a=np.random.randint(500, size=(array_size))
b=np.random.randint(500, size=(array_size))
c=np.random.randint(500, size=(array_size))
"""

ex1="""
a[np.any(b==c.reshape(-1,1),axis=0)]
"""

ex2="""
a[np.in1d(b,c)]
"""

print 'Example 1 took',timeit.timeit(ex1,setup=s,number=100),'seconds.'
print 'Example 2 took',timeit.timeit(ex2,setup=s,number=100),'seconds.'

When array_size is 50:
Example 1 took 0.00323104858398 seconds.
Example 2 took 0.0125901699066 seconds.

When array_size is 500:
Example 1 took 0.142632007599 seconds.
Example 2 took 0.0283041000366 seconds.

When array_size is 5,000:
Example 1 took 16.2110910416 seconds.
Example 2 took 0.170011043549 seconds.

When array_size is 50,000 (number=5):
Example 1 took 33.0327301025 seconds.
Example 2 took 0.0996031761169 seconds.

Note I had to change which axis for np.any() so the results would be the same. Reverse order of np.in1d or switch axis of np.any for desired effect. You can take reshape out of example 1, but reshape is really quite fast. Switch to obtain the desired effect. Really interesting- I will have to use this in the future.

A: How about np.where() :
>>> a  = np.array([2,4,8,16])
>>> b  = np.array([0,0,0,0])
>>> c  = np.array([1,0,0,1])
>>> bc = np.where(b==c)[0] #indices where b == c
>>> a[bc]
array([4,8])

This should do the trick. Not sure if the timing is optimal for your purposes
>>> a = np.random.randint(0,10000,1000000)
>>> b = np.random.randint(0,10000,1000000)
>>> c = np.random.randint(0,10000,1000000)
>>> %timeit( a[ np.where( b == c )[0] ]   )
100 loops, best of 3: 11.3 ms per loop


text:
Q: External 2.5" enclosure SATA power only we have these mini-SAS PCIe SATA III controllers.  Mini-SAS enclosures seem to run about $500, but I can use a $10 mini-SAS-to-SATA adapter cable so then all I need is an external enclosure that provides SATA power and has a way to run the cables into the drives.  Should work?  Any suggestions?

A: Google tells me that they exist and can be purchased. Look for "SAS enclosure" and select something with the right connector - SFF-8470 (InfiniBand) is quite common but SFF-8086/7/8 (various mini-SAS) can be found too.
More cheaply, an "external disk array" (disk bays with power/SATA connectors) also exist.
Everything else will depend on your setup - ideally, get something rackmounted, running off your UPS, with a very neat cable connecting to your sever and hopefully it won't be accidentally pulled or lose power.


text:
Q: Does "GET search/tweets" return all tweets from past week? https://dev.twitter.com/rest/reference/get/search/tweets
From what I see in the twitter documentation, it only limits the number of requests per window from the past week. My question is there any limit on the number of tweets returned?
For example, I make ONE request call of search/tweets with a search term Trump. I believe there can be millions of tweets that contains the term Trump in the past week. Does this single request call return millions of tweets to me? Or does it sample according to some limits?

A: The documentation is pretty clear that you'll only get 15 Tweets by default, but you can increase that to 100 per page of results, step through the results page by page. It also says:

There are limits to the number of Tweets which can be accessed through
  the API.


text:
Q: Quartiles when all numbers are same I understand quartiles are to be used in large data sets. But for pedagogical purposes,
What would be the Quartile1,Median and Quartile3 for a set consisting of same numbers?
What would be the quartiles of 7 times 3?

A: For corner cases like this, you need to consult your definition.  All the definitions out there agree on large continuous data sets, but they differ in detail when individual observations matter.  Wikipedia gives three methods for computing the quartiles.  If your set is seven samples, each with a value 3, the only thing that makes sense to me is to have all three quartiles be 3 as well.  All three Wikipedia approaches agree in this case.

A: There are many different definitions of 'quantile', and thus of the three quartiles.  R statistical software supports nine of them. As the Question suggests, all the methods usually give about the same results for large samples, but they can give different results for certain small samples.
In the particular case of a sample with seven 3's, all nine of the methods give the result suggested in the answer by @RossMillikan. However, for a sample consisting of the integers 1 through 7, results are not the same. For some documentation and references, in R see
the page at help(quantile).
 > x = 1:7
 > x
 [1] 1 2 3 4 5 6 7
 > quantile(x, type=1)
   0%  25%  50%  75% 100%
    1    2    4    6    7
 > quantile(x, type=2)
   0%  25%  50%  75% 100%
    1    2    4    6    7
 > quantile(x, type=3)       # Used for discrete data by SAS
   0%  25%  50%  75% 100%
    1    2    4    5    7
 > quantile(x, type=4)
   0%  25%  50%  75% 100%
 1.00 1.75 3.50 5.25 7.00
 > quantile(x, type=5)
   0%  25%  50%  75% 100%
 1.00 2.25 4.00 5.75 7.00
 > quantile(x, type=6)       # Used by Minitab and SPSS
   0%  25%  50%  75% 100%
    1    2    4    6    7
 > quantile(x, type=7)       # Default method in R
   0%  25%  50%  75% 100%
  1.0  2.5  4.0  5.5  7.0
 > quantile(x, type=8)
       0%      25%      50%      75%     100%
 1.000000 2.166667 4.000000 5.833333 7.000000
 > quantile(x, type=9)
     0%    25%    50%    75%   100%
 1.0000 2.1875 4.0000 5.8125 7.0000


text:
Q: While loop breaks unintentionally I am in my second week of C# training, so I am pretty new to programming. I have to make a program that returns the smallest integer out of a series of random integer inputs. Once the input = 0, the program should break out of the loop. I am only allowed to use while and for loops. For some reason my program breaks out of loop after the second input and it looks like it doesn't even care if there is a "0" or not. Could you please see where I went wrong? I have been busting my head off with this. Sorry if this question has already been posted by somebody else but I did not find an answer to it anywhere.
PS: The zero input should be taken into account for the comparison.
So this is what I've got so far:
 class Program
 {
     static void Main()
     {
        int i = 0;
        int input = Int32.Parse(Console.ReadLine());
        int min = default;

        while (input != 0)
        {
            Console.ReadLine();
            if (i == 0)
            {
                min = input;
                break;
            }

            if (input < min && i !=0)
            {
                input = Convert.ToInt32(Console.ReadLine());
                min = input;
            }
            i++;
        }
        Console.WriteLine(min);
    }

A: First of all you will want to re-read the documentation for for- and while-loops. There are several useful pages out there.. e.g. for / while.
Problem
The reason why your loop breaks is that you initialize i with 0.
int i = 0;

Inside your loop you are using the if-statment to break the loop if the condition "i is 0" is met.
if (i == 0)
{
    min = input;
    break;
}

The input that the user has to provide each iteration of the loop is ignored by your program as you are never storing this kind of information to any variable.
while (input != 0)
{
    Console.ReadLine();
    // ...
}

Possible Solution
As a beginner it is helpful to tackle tasks step by step. Try to write down each of this steps to define a simple algorithm. As there are many solutions to this problem one possible way could be:

*

*Declare minimum value + assign max value to it

*Use a while loop and loop till a specific condition is matched

*Read user-input and try converting it to an integer

*Check whether the value is 0 or not

*

*4.1. If the value is 0, go to step 8

*4.2. If the value is not 0, go to step 5

*Check whether the value is smaller than the current minimum value

*

*5.1. If the value is smaller, go to step 6

*5.2. If the value is not smaller, go back to step 3

*Set the new minimum

*Go back to step 3

*Break the loop

*End program

A program that handles the above steps could look like:
using System;

namespace FindMinimum
{
    public class Program
    {
        static void Main(string[] args)
        {
            // Declare minimum value + assign initial value
            int minValue = int.MaxValue;

            // Loop until something else breaks out
            while (true)
            {
                Console.WriteLine("Please insert any number...");

                // Read io and try to parse it to int
                bool parseOk = int.TryParse(Console.ReadLine(), out int num);

                // If the user did not provide any number, let him retry
                if (!parseOk)
                {
                    Console.WriteLine("Incorrect input. Please insert numbers only.");
                    continue;
                }

                // If the user typed in a valid number and that number is zero, break out of the loop
                if (parseOk && num == 0)
                {
                    break;
                }

                // If the user typed in a valid number and that number is smaller than the minimum-value, set the new minimum
                if (parseOk && num < minValue)
                {
                    minValue = num;
                }
            }

            // Print the result to the console
            Console.WriteLine($"Minimum value: {minValue}.");

            // Keep console open
            Console.ReadLine();
        }
    }
}

A: Try This:
       int input;
       Console.Write("Enter number:");
       input = Int32.Parse(Console.ReadLine());
       int min = input;

       while(true)
       {
           if (input == 0)
               break;

           if (min > input)
               min = input;

           Console.Write("Enter number:");
           input = Int32.Parse(Console.ReadLine());
       }

       Console.WriteLine(min);
       Console.ReadKey();

I hope it helps.


text:
Q: How to change PKCS12 keystore file from RSA1024 to RSA2048 and be able to update the app in Play Store? More than 3 years ago we have started with our app on Play Store and we were using RSA1024 keystore .p12 file. However, since JDK 1.8_121 1024 bit keystore files are not supported by Oracle, so I cannot use newer java version to compile the app.
When I tried to create RSA2048 bit key file, it works, however I couldn't upload the update cause a "wrong developer information" or similar.
Any idea how to create 2048 bit key from 1024 bit key and to be recognized by Google Play Store?

A: Once you have a key to sign your app, you can't change it. This is a restriction with Android, and not specific to Google Play. Changing your key is known as "Key rotation". Key rotation may be coming in the future according to this article but doesn't exist yet. I'd wait.
If you really need to do this, a process which involves publishing a second app is described here.


text:
Q: Link Dataset with SQL server : Fail I've literally searched everything and everywhere but somehow this piece of code of mine just won't work no matter what I've tried.
So I have created a database on a SQL server and linked it, tested it, great it works. OK, so the problem is when I'm trying to insert data on a website textbox and have THAT data copied/transferred into my database table. So I only now get an error saying that 'Exception unhandeld and Must declare the scalar variable "@f_name".
I would appreciate it if anyone can assist? Thanks.
 private void Save(string hfname, string hlname, string hemail, string hcomment)
        {
            SqlConnection myConn = new SqlConnection(GetConnectionString());
            String sql = "INSERT INTO helpdesk (First_Name, Last_Name, Email, Comments) VALUES " + " (@f_name, @l_name, @email, @comment)";
            SqlCommand cmd = new SqlCommand(sql, myConn);
            ITDBDataset itdbDataSet = new ITDBDataset();
            SqlDataAdapter dataAdapter;
            try
            {

                myConn.Open();
                dataAdapter = new SqlDataAdapter(cmd);
                dataAdapter.Fill(itdbDataSet);
                myConn.Close();

                SqlParameter[] param = new SqlParameter[6];
                //para,[0]
                param[0] = new SqlParameter("@f_name", System.Data.SqlDbType.VarChar, 50);
                param[1] = new SqlParameter("@l_name", System.Data.SqlDbType.VarChar, 50);
                param[2] = new SqlParameter("@email", System.Data.SqlDbType.VarChar, 30);
                param[3] = new SqlParameter("@comment", System.Data.SqlDbType.VarChar, 600);

                param[0].Value = hfname;
                param[1].Value = hlname;
                param[2].Value = hemail;
                param[3].Value = hcomment;

                cmd.CommandType = System.Data.CommandType.Text;
                cmd.ExecuteNonQuery();
                //SqlDataReader reader = cmd.ExecuteReader();

            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                string msg = "Not Added, check context!";
                msg += ex.Message;
                throw new Exception(msg);
            }
            //finally
            //{
            //    myConn.Close();
            //}
        }

Any suggestions to what could have gone wrong?

A: You have forgotten to add the parameters to your command and you close the connection before the call of the method. I propose you using:
 private void Save(string hfname, string hlname, string hemail, string hcomment)
    {
        SqlConnection myConn = new SqlConnection(GetConnectionString());
        String sql = "INSERT INTO helpdesk (First_Name, Last_Name, Email, Comments) VALUES " + " (@f_name, @l_name, @email, @comment)";
        SqlCommand cmd = new SqlCommand(sql, myConn);
        ITDBDataset itdbDataSet = new ITDBDataset();
        SqlDataAdapter dataAdapter;
        try
        {

            myConn.Open();
            dataAdapter = new SqlDataAdapter(cmd);
            dataAdapter.Fill(itdbDataSet);

            SqlParameter[] param = new SqlParameter[6];
            //para,[0]
            param[0] = new SqlParameter("@f_name", System.Data.SqlDbType.VarChar, 50);
            param[1] = new SqlParameter("@l_name", System.Data.SqlDbType.VarChar, 50);
            param[2] = new SqlParameter("@email", System.Data.SqlDbType.VarChar, 30);
            param[3] = new SqlParameter("@comment", System.Data.SqlDbType.VarChar, 600);

            param[0].Value = hfname;
            param[1].Value = hlname;
            param[2].Value = hemail;
            param[3].Value = hcomment;

            cmd.Parameters.AddRange(param);//add the parameters
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.ExecuteNonQuery();
            //SqlDataReader reader = cmd.ExecuteReader();
           myConn.Close();
        }

A: I suggest you use AddWithValue eg
SqlConnection myConn = new SqlConnection(GetConnectionString());
String sql =
     "INSERT INTO helpdesk (First_Name, Last_Name, Email, Comments) VALUES " +
     " (@f_name, @l_name, @email, @comment)";
SqlCommand cmd = new SqlCommand(sql, myConn);

cmd.Parameters.AddWithValue("@f_name",hfname);
cmd.Parameters.AddWithValue("@l_name",hlname);
cmd.Parameters.AddWithValue("@email",hemail);
cmd.Parameters.AddWithValue("@comment",hcomment);

ITDBDataset itdbDataSet = new ITDBDataset();
SqlDataAdapter dataAdapter;
try
{
        myConn.Open();
        dataAdapter = new SqlDataAdapter(cmd);
        dataAdapter.Fill(itdbDataSet);
        myConn.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
        string msg = "Not Added, check context!";
        msg += ex.Message;
        throw new Exception(msg);
}


text:
Q: Silent renew in oidc-client.js when we have extra query params I am getting below error

I am having below UserManagerSettings
private getClientSettings(loginType?): UserManagerSettings {
    let logout;
    if (window.sessionStorage.getItem('loginType') === 'Internal') {
      logout = environment.post_logout_redirect_uri + 'biz-admin';
    } else {
      logout = environment.post_logout_redirect_uri;
    }

    return {
      authority: environment.authority,
      client_id: environment.client,
      redirect_uri: environment.redirectUri,
      post_logout_redirect_uri: logout,
      response_type: 'id_token token',
      scope: environment.scopes,
      filterProtocolClaims: true,
      silent_redirect_uri: 'http://localhost:4200/assets/silent-refresh.html',
      loadUserInfo: true,
      extraQueryParams: {
        loginType: loginType,
      },
    };
  }

Below adds an expiring event
this.manager.events.addAccessTokenExpiring(x => {
  this.renewToken().then(u => {
    this.user = u;
  });
});

Below functions call sign in silent
 public renewToken(): Promise<User> {
    return this.manager.signinSilent(this.getClientSettings('Internal'));
  }

Silent-refresh.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/oidc-client/1.7.0/oidc-client.js"></script>
<script>
  var mgr = new Oidc.UserManager();
  mgr.signinSilentCallback().catch(error => {
        console.error(error);
    });
</script>

URI, I have custom logic based on loginType
redirect_uri=http%3A%2F%2Flocalhost%3A4200%2Fassets%2Fsilent-refresh.html&response_type=id_token&scope=openid&state=307b01d8e3234027b92e0f2920364d4a&nonce=c8d110e677bd4fc8a993b77798893edf&prompt=none&loginType=undefined

Also, I have correct redirect URI in the database, still, renew do not work. renewtoken() gets called but never comes back to 'then' code.
Questions -

*

*How does silent renew manages to get access_token? does it take saved id password from somewhere?

*How can I send extra query params to signInSilent() it is undefined even after I am passing it as params, how does signInSilent() gets the user manager setting?

A: I managed to solve my issue by following steps-
Startup
 services.AddIdentityServer(options =>
            {
                options.Authentication.CookieLifetime = TimeSpan.FromDays(30);
                options.Authentication.CookieSlidingExpiration = true;
            })

services.AddAuthentication(x => x.DefaultAuthenticateScheme = IdentityServer4.IdentityServerConstants.DefaultCookieAuthenticationScheme);

Logout
public async Task<IActionResult> Logout(LogoutInputModel model) { await HttpContext.SignOutAsync(IdentityServer4.IdentityServerConstants.DefaultCookieAuthenticationScheme);}

There is nothing at the angular side, we need to configure the above setting at identity server code
Thanks to below user's comment
https://github.com/IdentityModel/oidc-client-js/issues/911#issuecomment-617724445


text:
Q: JPA Constraint for date year I have an entity representing Documents that looks like this:
Document
date_creation
doc_number
doc_origin
Documents are usually referred to as '2012/XY/005', that would be the fifth document in 2012 originated by XY.
So number has to be unique in the year it was created and for the same Origin, and I need to put a constraint for it.
What would be the best way to model and map this using JPA?
I think my options are:
Option 1: put another field the Document entity for the year in date creation, and make it unique(year,doc_number,doc_origin)
Option 2: create a field doc_ref and put a string like 'YEAR/ORIG/NUMBER' and make it unique(doc_ref)
Both options add another field duplicating the year, but Option 1 requires me to update field year consistently with date_creation and Option 2 requires me to update field doc_ref consistently with the rest, so I tend to think that Option 1 is best.
Is there another option that I am not seeing?
Thanks!

A: You could use a function-based unique index, if your database allows them. Example in Oracle:
CREATE UNIQUE INDEX YEAR_ORIGIN_NUMBER_IDX
on DOCUMENT (TRUNC(DT_CREATION, 'YEAR'), DOC_ORIGIN, DOC_NUMBER)


text:
Q: MaxListeners Exceeded when combining web3UIkit and React/Moralis I am continuously running into a MaxListeners Exceeded issue in my project and I cannot find the solution to it. The problem presents itself when browsing between pages in the navBar a few times and after a couple of clicks the console notifies the Maxlisteners issue. I find this weird as the coding is nothing special and I cannot find the rootcause of this.
I have created a seperate barebones project on Github that only has the minimum required packages on it to try and isolate the problem. It seems as though the web3UIKit, React, Moralis and/or Next don't play well with eachother however I lack the expertise to determine this 100%.
My question to you is: can you find the cause of this problem or do you know of a solution to counteract this problem all together.
I will share the code below and a GitHub close for your convenience. I will be forever in your debt if you can help me.
github clone: https://github.com/deAgora/maxlisteners.git
_app.js
import { MoralisProvider } from "react-moralis";
import "../styles/globals.css";

function MyApp({ Component, pageProps }) {
  return (
    <MoralisProvider initializeOnMount={false}>
      <Component {...pageProps} />
    </MoralisProvider>
  );
}

export default MyApp;

Index.js
import Head from "next/head";
import Header from "../components/Header";
import Navbar from "../components/Navbar";
import styles from "../styles/Home.module.css";

export default function Home() {
  return (

        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />

      <Navbar></Navbar>

This page is an example to illustrate the maxlisteners issue

  );
}

Page1.js
import Head from "next/head";
import Header from "../components/Header";
import Navbar from "../components/Navbar";
import styles from "../styles/Home.module.css";

export default function Home() {
  return (

        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />

      <Navbar></Navbar>

        Page 1: This page is an example to illustrate the maxlisteners issue

  );
}

Component Header.js
import { ConnectButton } from "@web3uikit/web3";

export default function Header() {
  return (

Maxlisteners Example

        <ConnectButton moralisAuth={false}></ConnectButton>

  );
}

Component: Navbar.js
import Link from "next/link";

export default function Navbar() {
  return (

          <Link href="/">
            Home
          </Link>

          <Link href="/page1">
            Page1
          </Link>

  );
}

Package.json
{
  "name": "maxlisteners",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@web3uikit/core": "^0.1.5",
    "@web3uikit/icons": "^0.1.5",
    "@web3uikit/web3": "^0.1.5",
    "magic-sdk": "^9.0.0",
    "moralis": "^2.0.3",
    "next": "12.2.5",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-moralis": "^1.4.1"
  },
  "devDependencies": {
    "eslint": "8.22.0",
    "eslint-config-next": "12.2.5"
  }
}

A: Hello you are trying to use Moralis 2.0 (2.0.3) which won't work with react-moralis - this is a new SDK compared to the previous SDK (which is now called moralis-v1).
You will need to use these versions - moralis@1.11.0 and react-moralis@1.4.0 in your Next.js project as there is an issue with the latest moralis-v1 and react-moralis.
If you have more questions or issues with this, please post on either:

*

*Moralis Discord: https://moralis.io/joindiscord

*Moralis forum: https://forum.moralis.io


text:
Q: Export SOLR data to CSV or EXCEL I need to export solr data to EXCEL or CSV.
I have SOLR code with millions of records and I need a way to export them by a certain query to CSV/EXCEL. In addition I need to control the headers inside the EXCEL.
What do you suggest?
Is there a 3rd party API that does it?
Should I use CSV format and just extract them and then manipulate the csv?

A: The best tool to export your Solr data is the /export request handler [1].
Unfortunately, from the official Solr documentation, csv is not supported as an output.
Json is the default.
If you can manage Json transformations to obtain the data format you want in CSV, the /export is definitely the best way to proceed.
If performance is not an issue, the standard select request handler using the CSV response writer should do the trick [2].
http:/localhost:8983/solr/collection1/select?q=*:*&wt=csv&indent=true&rows=N

[1] https://lucene.apache.org/solr/guide/6_6/exporting-result-sets.html
[2] http:/localhost:8886/solr/tech/select?q=:&wt=csv&indent=true

A: You may use Solr select endpoint to extract all documents with q=*:* and csv responseWriter.
Example:
http:/localhost:8886/solr/tech/select?q=*:*&wt=csv&indent=true

More details about csv ResponseWriter can be found here.

A: Since Solr 6.3, you can use the XLSX response writer.
With this you can control the result headers, customizing your own columns names and even column widths. It looks exactly what you want :)
Here's the documentation you need to follow : https://lucene.apache.org/solr/guide/6_6/response-writers.html#ResponseWriters-XLSXResponseWriter


text:
Q: Android. Error In Parse Query I am building a chat application in that I am using Firebase to store and transfer message and Parse to store all the users data like(User sign up, login, storing recent table and sending push).
In Parse I stored all the user login data in Usertable, and I am maintaining one Recent table to store all the recent chat.
User one to one chat will be saved under one GroupId(String). That group Id was formed by adding
GroupId = UserOneObjectId+UserTwoObjectId;

If someone made a new chat with particular person it will store the data about the recent chat in the Recent table, mainly it has to store the GroupId and members detail in array for exmp:
members = [UserOneObjectId, UserTwoObjectId]

for the next time if the user is making a chat again with the same person it has to query the table and look for the members array. if both person object id is already present it has to get that GroupId from that row.
for that I added these code. But this is not working kindly check and tell what mistake I am making...
And My full code is...
public class StartChat extends AppCompatActivity {

private String FIREBASE_URL = "https://craking-fire-base.cracked.com/";

private String user1ObjectId, user1Name;
private String user2ObjectId, user2Name;
private static String groupId;

private Firebase mFirebaseRef;
private Chat chat;
private ChatListAdapter mChatListAdapter;
private ValueEventListener mConnectedListener;
private PrefManager pref;
private Toolbar mtoolbar;

private ListView listView;
private EditText inputText;

String groupIdGot;

ParseObject entryToRecentChat;

ParseQuery<ParseObject> groupIdQuery;

public StartChat() {
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start_chat);

    mtoolbar = (Toolbar) findViewById(R.id.home_toolbar);
    setSupportActionBar(mtoolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(false);
    mtoolbar.setTitle(user2Name);

    pref = new PrefManager(getApplicationContext());

    user1ObjectId = pref.getObjectId();
    user1Name = pref.getUserName();

    Intent i = getIntent();
    user2ObjectId = i.getStringExtra("user2ObjectId");
    user2Name = i.getStringExtra("user2Name");

    listView = (ListView) findViewById(R.id.list);

    /*groupId = user1ObjectId + user2ObjectId;*/

    groupIdQuery = ParseQuery.getQuery("Recent");
    groupIdQuery.whereContainsAll("members", Arrays.asList(user1ObjectId, user2ObjectId));
    Log.d("objectArray", Arrays.asList(user1ObjectId, user2ObjectId).toString());
    groupIdQuery.findInBackground(new FindCallback<ParseObject>() {
        @Override
        public void done(List<ParseObject> list, ParseException e) {
            if (e == null)
            {
                for (ParseObject dealsObject : list) {
                    // use dealsObject.get('columnName') to access the properties of the Deals object.
                    String objId = dealsObject.getObjectId();
                    groupIdGot = (String) dealsObject.get("groupId");
                    Log.d("GroupId***Got", groupIdGot);
                    //String members = (String) dealsObject.get("members");
                    Toast.makeText(getApplicationContext(), "ObjectId: " + objId + "\n" + "GroupId: " + groupId + " value present", Toast.LENGTH_LONG).show();

                }

            }else{
                Toast.makeText(getApplicationContext(), " No Data present", Toast.LENGTH_LONG).show();
                groupId = user1ObjectId + user2ObjectId;

                entryToRecentChat = new ParseObject("Recent");
                entryToRecentChat.put("groupId", groupId);
                entryToRecentChat.put("lastUser", ParseObject.createWithoutData("_User", user1ObjectId));
                entryToRecentChat.put("user", ParseObject.createWithoutData("_User", user2ObjectId));
                entryToRecentChat.addAllUnique("members", Arrays.asList(user1ObjectId, user2ObjectId));
                entryToRecentChat.saveEventually(new SaveCallback() {
                    @Override
                    public void done(ParseException e) {
                        if (e == null) {
                            Toast.makeText(getApplicationContext(), "Value saved", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(getApplicationContext(), "Value not saved", Toast.LENGTH_LONG).show();
                            Log.d("exception", e.getMessage());
                        }
                    }
                });
            }
        }
    });
    //groupId = user1ObjectId + user2ObjectId;
    if(groupIdGot != null){
        groupId = groupIdGot;
    }else{
        groupId = user1ObjectId + user2ObjectId;
    }

    mFirebaseRef = new Firebase(FIREBASE_URL).child("Message").child(groupId);

    inputText = (EditText) findViewById(R.id.messageInput);
    inputText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
            if (actionId == EditorInfo.IME_NULL && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                sendMessage();
            }
            return true;
        }
    });

    //input = inputText.getText().toString();
    findViewById(R.id.sendButton).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sendMessage();
            sendPush();
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_start_chat, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
protected void onStart() {
    super.onStart();

    // Setup our view and list adapter. Ensure it scrolls to the bottom as data changes
    //final ListView listView = getListView();
    mtoolbar.setTitle(user2Name);
    mChatListAdapter = new ChatListAdapter(mFirebaseRef.limit(50), this, R.layout.chat_message, user1Name);
    listView.setAdapter(mChatListAdapter);
    mChatListAdapter.registerDataSetObserver(new DataSetObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
            listView.setSelection(mChatListAdapter.getCount() - 1);
        }
    });

    // Finally, a little indication of connection status
    mConnectedListener = mFirebaseRef.getRoot().child(".info/connected").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            boolean connected = (Boolean) dataSnapshot.getValue();
            if (connected) {
                Toast.makeText(StartChat.this, "Connected to ChatRoom", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(StartChat.this, "Disconnected from ChatRoom", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            // No-op
        }
    });

}

@Override
protected void onStop() {
    super.onStop();
    mFirebaseRef.getRoot().child(".info/connected").removeEventListener(mConnectedListener);
    mChatListAdapter.cleanup();
}

private void sendMessage() {
    String input = inputText.getText().toString();
    if (!input.equals("")) {
        // Create our 'model', a Chat object
        chat = new Chat(input, user1Name);
        // Create a new, auto-generated child of that chat location, and save our chat data there
        mFirebaseRef.push().setValue(chat);
        inputText.setText("");
    }
}

Particularly I am getting nullpointer error in this line
 mFirebaseRef = new Firebase(FIREBASE_URL).child("Message").child(groupId);

Because for me this query is not working for me.
    groupIdQuery = ParseQuery.getQuery("Recent");
    groupIdQuery.whereContainsAll("members", Arrays.asList(user1ObjectId, user2ObjectId));
    Log.d("objectArray", Arrays.asList(user1ObjectId, user2ObjectId).toString());
    groupIdQuery.findInBackground(new FindCallback<ParseObject>() {
        @Override
        public void done(List<ParseObject> list, ParseException e) {
            if (e == null)
            {
                for (ParseObject dealsObject : list) {
                    // use dealsObject.get('columnName') to access the properties of the Deals object.
                    String objId = dealsObject.getObjectId();
                    groupIdGot = (String) dealsObject.get("groupId");
                    Log.d("GroupId***Got", groupIdGot);
                    //String members = (String) dealsObject.get("members");
                    Toast.makeText(getApplicationContext(), "ObjectId: " + objId + "\n" + "GroupId: " + groupId + " value present", Toast.LENGTH_LONG).show();

                }

            }else{
                Toast.makeText(getApplicationContext(), " No Data present", Toast.LENGTH_LONG).show();
                groupId = user1ObjectId + user2ObjectId;

                entryToRecentChat = new ParseObject("Recent");
                entryToRecentChat.put("groupId", groupId);
                entryToRecentChat.put("lastUser", ParseObject.createWithoutData("_User", user1ObjectId));
                entryToRecentChat.put("user", ParseObject.createWithoutData("_User", user2ObjectId));
                entryToRecentChat.addAllUnique("members", Arrays.asList(user1ObjectId, user2ObjectId));
                entryToRecentChat.saveEventually(new SaveCallback() {
                    @Override
                    public void done(ParseException e) {
                        if (e == null) {
                            Toast.makeText(getApplicationContext(), "Value saved", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(getApplicationContext(), "Value not saved", Toast.LENGTH_LONG).show();
                            Log.d("exception", e.getMessage());
                        }
                    }
                });
            }
        }
    });
    //groupId = user1ObjectId + user2ObjectId;
    if(groupIdGot != null){
        groupId = groupIdGot;
    }else{
        groupId = user1ObjectId + user2ObjectId;
    }

A: In your question you say:

Particularly I am getting nullpointer error in this line

 mFirebaseRef = new Firebase(FIREBASE_URL).child("Message").child(groupId);

A NullPointerException is thrown when you try to call a method on a null value.
"SO".toString(); // works
null.toString(); // throws a NullPointerException

I always remember this as:

a NullPointerException is thrown when you have a null value before a dot

There are two dots in your statement, so two places where NullPointException can be thrown. Let's split the statement over a few lines:
 mFirebaseRef =
     new Firebase(FIREBASE_URL) // can this be null?
         .child("Message")      // can this be null?
         .child(groupId);

So either new Firebase(FIREBASE_URL) returns null, or child("Messages") returns null. Given how Firebase works, it is most likely that child("Message") returns null. So your database doesn't had a child node called Message.


text:
Q: Comparing two columns in excel to find non-duplicates I have two columns of numbers, column A and column B.  Column A is where a numbered tag is entered when it leaves and Column B is where the numbered tag is entered when it returns. There are spaces in both of these columns. I am having trouble finding a proper formula or way to display in two additional columns tag numbers that were sent but not returned, and tags that were returned but not sent, essentially numbers that don't appear on both columns.

A: Look into MATCH() - it will display N/A for not found, IF(ISNA(...),...) will help for those if you wish to display something else. Example sheet below.
-- Untitled.csv --

Left,Sent+NR,Returned,"nonS,Returned"
a,"=MATCH(A2,$C$2:$C$8,0)",e,"=MATCH(C2,$A$2:$A$8,0)"
b,"=MATCH(A3,$C$2:$C$8,0)",g,"=MATCH(C3,$A$2:$A$8,0)"
c,"=MATCH(A4,$C$2:$C$8,0)",a,"=MATCH(C4,$A$2:$A$8,0)"
d,"=MATCH(A5,$C$2:$C$8,0)",b,"=MATCH(C5,$A$2:$A$8,0)"
e,"=MATCH(A6,$C$2:$C$8,0)",c,"=MATCH(C6,$A$2:$A$8,0)"
f,"=MATCH(A7,$C$2:$C$8,0)",x,"=MATCH(C7,$A$2:$A$8,0)"
g,"=MATCH(A8,$C$2:$C$8,0)",y,"=MATCH(C8,$A$2:$A$8,0)"

A: I would create a conditional format that will highlight any values in column A where there is not a corresponding value in column B.  In this fashion, you can quickly visually see what tags have not been turned back in.
To enter a conditional format

*

*Select cell A1

*On the ribbon, select Home tab and then Conditional Formatting

*On the following screen, select new rule and then select Use a formula to determine which cells to format

*Enter the following formula =COUNTIF($A:$A, A1)

*Change the background and text color per your liking

*Change the Applies To box to column A


text:
Q: Simple OAuth2 authentication - Request an access token I have been struggling with this now for a while. So if someone could help me it would be great.
I am trying to get a simple access token from the TwitchTV API. I am referring to this link: https://dev.twitch.tv/docs/authentication/#getting-tokens
GET https://id.twitch.tv/oauth2/authorize
?client_id=<your client ID>
&redirect_uri=<your registered redirect URI>
&response_type=<type>
&scope =<space-separated list of scopes>

So thats where I begin to struggle already. How exactly do I make such requests in an ASP.NET MVC application? I see that I have an Startup.Auth.cs class where I can configure OAuth Authentications. But how does such authentication have to look like?
It then says in the documentation:

If the user authorizes your application, the user is sent to your
  redirect URI, with an ID token and optionally an access token (if that
  was requested):

https://<your registered redirect URI>#id_token=<an id
token>&access_token=<an access token>

Now how do I access this token? Can someone please give me a small Code example of how I should start with this API? I really dont have any experience with such technology. How do I have to configure my Startup.Auth.cs and how does my Action have to look like, that starts the authentication?
Please refer to the link above in your answer. Thank you!

A: You can create a redirect URI as callback URL.
when a user logged in in your app the callback will be triggered containing the Access Token and other information.
here is the sample snippet in PHP (https://yourhost.com/outhcallback.php)
    <?php
       $acccesstoken=$_REQUEST["access_token"];
       $id_token=$_REQUEST["id_token"];
       store_to_session(accesstoken);
    ?>

now you have the token. if this token you require in server-side store to the session and if require in client-side store to local storage.


text:
Q: The commands \wd, \tp and \ht in TikZ/PGF What does these commands, \wd, \tp and \ht stand for? I assumed that they are from TikZ and PGF, because I haven't seen them elsewhere.
I think the \wd stands for "width" and the \ht stands for "height", and they somehow obtain the width and the height of the shape that comes after.
I would like to know if I am right about that. Then I would like to know what \tp stands for, and finally I want to ask, if there is any other such commands out there.
I looked for them in the manual to no avail, then also on Google, but the phrase is just too short, probably.

A: \wd, \ht and \dp (not \tp) are TeX primitives for getting the width, height and depth of a box (respectively).
So, for example,
\newbox\mybox
\setbox\mybox=\hbox{\vrule width10pt height20pt depth 30pt}
\typeout{width=\the\wd\mybox, height=\the\ht\mybox, depth=\the\dp\mybox}

will produce
width=10.0pt, height=20.0pt, depth=30.0pt

Somewhere in the log-file.
More details on boxes can be found in chapter 5 ("Boxes") from TeX by Topic by Victor Eijkhout.


text:
Q: EF Core NodaTime field - could not be mapped I'm using EF Core with <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="5.0.2" />
I've just added a NodaTime.LocalDate field to my entity which uses a package called NodaTime:
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime" Version="5.0.2" />
The field:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Nest;

namespace Vepo.Domain
{
    [ElasticsearchType(RelationName = "eventitem", IdProperty = "Id")]
    public class EventItem : VeganItem<EventItemEstablishment>
    {
        [MaxLength(10)]
        public List<NpgsqlRange<LocalDateTime>> Dates { get; set; }
    }
}

and I now get this error:

InvalidOperationException: The property 'EventItem.Dates' could not be
mapped, because it is of type List<NpgsqlRange<LocalDateTime>> which is not a supported
primitive type or a valid entity type. Either explicitly map this
property, or ignore it using the '[NotMapped]' attribute or by using
'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

So Ef Core cannot map List<NpgsqlRange>.
This is a demo of how to let EF Core map LocalDateTime by using a value converter:
base.OnModelCreating(modelBuilder);
var localDateConverter =
    new ValueConverter<LocalDate, DateTime>(v =>
        v.ToDateTimeUnspecified(),
        v => LocalDate.FromDateTime(v));

modelBuilder.Entity<Event>()
    .Property(e => e.Date)
    .HasConversion(localDateConverter);

But this does not work for me because my field is not LocalDateTime, it is List<NpgsqlRange<LocalDateTime>>
I am struggling to create the value converter correctly. Any help appreciated.
FYI My front end is sending a list of custom objects to the back end: [{DateTime startDate, DateTime endDate}]
IMPORTANT: Shay Rojansky's version is working for me, I needed to change my Startup.cs code from this:
public void ConfigureServices(IServiceCollection services)
{
    services
    .AddDbContext<VepoContext>(opt => {
        opt
        .UseNpgsql(
            Configuration
            .GetConnectionString("DefaultConnection"))
            .EnableSensitiveDataLogging()
            .EnableDetailedErrors()
            .LogTo(Console.WriteLine);
    });

    NpgsqlConnection.GlobalTypeMapper.UseNodaTime();

To this (basically to his - but my initialising code was using ConfigureServices, not OnConfiguring so I thought I will post his solution with the ConfigureServices syntax here for people who's code is already using ConfigureServices:
    services
    .AddDbContext<VepoContext>(opt => {
        opt
        .UseNpgsql(
            Configuration
            .GetConnectionString("DefaultConnection"),
                o => o.UseNodaTime()
            )
            .EnableSensitiveDataLogging()
            .EnableDetailedErrors()
            .LogTo(Console.WriteLine);
    });

A: I got this 'not a supported primitive type' error because I was following the wrong documentation for my situation. I started at https://www.npgsql.org/doc/types/nodatime.html which uses the NuGet package Npgsql.NodaTime and applies the type mapping with NpgsqlConnection.GlobalTypeMapper.UseNodaTime();
I needed to instead follow the documentation for EF Core at https://www.npgsql.org/efcore/mapping/nodatime.html which relies on the NuGet package Npgsql.EntityFrameworkCore.PostgreSQL.NodaTime and applies the type mapping via UseNodaTime() on NpgsqlDbContextOptionsBuilder
builder.UseNpgsql("Host=localhost;Database=test;Username=npgsql_tests;Password=npgsql_tests",
        o => o.UseNodaTime());

A: The above works for me as-is using 5.0.10, without a value converter:
await using var ctx = new BlogContext();
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();

public class BlogContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseNpgsql(@"Host=localhost;Username=test;Password=test", o => o.UseNodaTime())
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    }
}

public class Blog
{
    public int Id { get; set; }
    public List<NpgsqlRange<LocalDateTime>> Dates { get; set; }
}

The following table gets created:
CREATE TABLE "Blogs" (
    "Id" integer GENERATED BY DEFAULT AS IDENTITY,
    "Dates" tsrange[] NULL,
    CONSTRAINT "PK_Blogs" PRIMARY KEY ("Id")
);

You may be interested in the new multirange type in the upcoming PostgreSQL 14 release. Support for it has already been added to version 6.0 of the EF Core provider (a release candidate is already out for both PG14 and EF Core 6.0.0), so you may want to give them a try.


text:
Q: Tensorflow: Picking an optimal model from a training session When training a deep learning network (say with TensorFlow or similar), it is common to train for a fixed set of samples and hope the results get better with longer training.  But this assumes monotonically increasing accuracy, which as shown below, is clearly not true.  As shown below, stopping at "2.0" would have had ten percentage points better accuracy.  Is there any common procedure for picking off better models and saving them.
 In other words a Peak-Detection routine.  Perhaps,  keeping track of the test-accuracy throughout the training session and saving off the model (checkpoint?) whenever the accuracy was higher than a previous value.
Questions:

*

*What is best practice for picking off the best model?

*Does TF have an methods for this?

*Is there merit to continuing to train even longer (maybe a lot longer), on the theory that the optimizer will eventually find a better solution.

*Is a checkpoint the best save method?

Thanks.

EDIT: Thanks to the recommendations from @Wontonimo, the improved accuracy results are shown below.  The following changes were made:

*

*reduce the learning rate in the Adam optimizer from 0.003 to 0.001

*add two additional dropout layers (prob=0.5)

*shuffle-select training frames from the full data set (instead of sequence-selecting)

*increase training iterations by 50%.

With these changes it seems that it would be advantageous to continue training even further.  And possibly add more regularization.

A: This highlights 2 common problems in machine learning

*

*1 : learning rate instability

*2 : overly optimistic
learning rate instability
First let's talk about learning rate instability.  The error rate of your graph shows improvement then suddenly, as if the NN saw some piece of data that voided all of its previous experience, it had its full understanding of the problem blown.  If we think in terms of training an animal or a person, this could happen if we make the next training sessions results too important instead of taking the long view.  People in the industry talk about learning rate decay, which is similar to saying "once you have basic understanding, make small changes to your mental model".
Specifically, consider decreasing your learning rate by 1/2 or a 1/3rd.  Additionally try using a more robust learning algorithm.  If you are using gradient descent, then try using a momentum based gradient descent.  Lastly, decrease your learning rate by 1/2 or 1/3 again if you see these wild swings down in test accuracy.  If you are not using a regularizer like dropout in your last layer, that can also help to keep your training results closely related to your test results so that you do not overfit.
overly optimistic
You mentioned that you would like to stop training when you have good results.  You are ignoring that your model does not actually converge.  Ignoring the poor results is being overly optimistic about the model.
I think your model shows great promise if it is able to get to 0.8.  Small changes like monumentum and dropout will stabilize your results.
Updated : Minibatch
After much review of your old graph and your new graph and taking into consideration comments, it appears that you could decrease the noise considerably by using a larger minibatch.  Consider increasing your batch size by x10.  Your graph very much looks like SGD, or a batch size small enough to have similar results.  It is important to average your loss function across the batch results before sending it to Adam to gain the benefit.  If you do this you may have to run up to x10 the number of epochs but you will see much smoother graphs.

A: I think that in this scenario it is better to approach the problem from a different angle probably selecting another model. To me this accuracy graph looks very noisy are really random.