text:
Q: Collecting a specific cell value in multiple worksheets and display those values in a master sheet I would like to collect value from cell C3 of all worksheets. And display those values in vertical order of a master worksheet.
Example: There are values Tom, Peter, Mark in cell C3 of 3 worksheet. I would like to collect those values and display in C3 -> Tom, C4 -> Peter, C5 -> Mark in the 4th worksheet.
What function in excel should I use? Please help.

A: This will loop through and grab Range("C3") from each sheet except the target sheet.
Make sure you change Target_sheet_name to your actual target sheet name.
Sub Grab_Names_From_Each_Sheet()
    Target_sheet_name = "Sheet1"
    Column_Num = 2
    For Each Sh In ActiveWorkbook
        If Sh.Name <> Target_sheet_name Then
            Column_Num = Column_Num + 1
            SHEETS(Target_sheet_name).Cells(3, Column_Num) = Sh.Range("C3")
        End If
    Next Sh
End Sub


text:
Q: bash program read array I am trying to run a bash program that takes a few command line input names, and then take an array as a command line input.
I.e.,
#!/bin/bash
name1=$1
name2=$2
my_array_input=("dog" "cat" "lion")

In this example I have name1 and name2 as input, and my_array_input is declared and set inside the script.
In my real script, I'd like to also have name1 and name2 as $1 and $2, but I'd also like to be able to take from the user a (unknown size/ variable size) my_array_input.  The user could input arrays of different lengths, and with his own name of animals as he wish...
Note that all inputs should be command line inputs.
Is there a trick to do this using bash scripting?
Thanks!

A: The arguments to a Bash script (or any program in Unix-like operating systems) are just a list of strings, so there's no way to do exactly what you describe.
However, you can set name1 to the first argument, name2 to the second argument, and my_array_input to all subsequent arguments:
#!/bin/bash
name1="$1"
name2="$2"
my_array_input=("${@:3}")

If the arguments to the above script are foo bar dog cat lion, then name1 will be foo, name2 will be bar, and my_array_input will be the array (dog cat lion).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Const member stack vs heap If I try to compile this code
struct A {
    const int j;
};
A a;

I'll get an expected error:

error: uninitialized const member in 'struct A'

but, if I try to compile this one:
struct A {
    const int j;
};
A * a = new A();

I'll get a successful build.
The question is: why does new allocation allows creating a variable with const member without explicit constructor and stack allocation - doesn't ?

A: This is ill-formed as of C++14. §12.1 [class.ctor] says that

4 A defaulted default constructor for class X is defined as deleted
  if:

*

*[...]

*any non-variant non-static data member of const-qualified type (or array thereof) with no brace-or-equal-initializer does not have a
  user-provided default constructor,

*[...]

  A default constructor is trivial if it is not user-provided and if:

*

*its class has no virtual functions (10.3) and no virtual base classes (10.1), and

*no non-static data member of its class has a brace-or-equal-initializer, and

*all the direct base classes of its class have trivial default constructors, and

*for all the non-static data members of its class that are of class type (or array thereof), each such class has a trivial default
  constructor.

§8.5 [dcl.init] says in turn that

7 To default-initialize an object of type T means:

*

*if T is a (possibly cv-qualified) class type (Clause 9), the default constructor (12.1) for T is called (and the initialization is
  ill-formed if T has no default constructor or overload resolution
  (13.3) results in an ambiguity or in a function that is deleted or
  inaccessible from the context of the initialization);

*[...]

  8 To value-initialize an object of type T means:

*

*if T is a (possibly cv-qualified) class type (Clause 9) with either no default constructor (12.1) or a default constructor that is
  user-provided or deleted, then the object is default-initialized;

*[...]

The empty pair of parentheses results in value-initialization. The default constructor for A is defined as deleted per [class.ctor]/p4. Thus, by [dcl.init]/p8, value-initialization means default-initialization, and by p7 the initialization is ill-formed because the constructor is deleted.
The C++11 version actually allowed value-initialization in this context; it says for value-initialization that, among other things,

if T is a (possibly cv-qualified) non-union class type without a
  user-provided constructor, then the object is zero-initialized and, if
  T's implicitly-declared default constructor is non-trivial, that
  constructor is called.

Since by the definition above the default constructor is trivial (even though it is deleted), it is not actually called. This was considered a defect in the standard and the relevant wording was changed by CWG issue 1301.
Compiler vendors usually do implement defect resolutions, so this could be considered a bug in GCC 4.8 that's been fixed in 4.9.

A: It's not because of the heap allocation, but because of the parenthesis you use when allocating. If you do e.g.
A* a = new A;

it would also fail.
The reason it works when you add the parenthesis is because then your structure is value initialized, and for a POD-type like A value-initialization value-initializes each member, and the default value-initialization for int is zero.
That means it would probably work creating the variable on the stack as well, if you just add the value-initialization parenthesis:
A a = A(); // watch out for the http://en.wikipedia.org/wiki/Most_vexing_parse

Though that brings other potential problems, better use uniform initialization if you can (requies C++11):
A a{};


text:
Q: Insert failed on parent table with new column I've got a main table (payment) and some partitioned tables (payment_AAAA_MM). I obtain these tables with a store function like this one:
CREATE OR REPLACE FUNCTION partitioning_payment()
  RETURNS trigger AS
$BODY$
 DECLARE
 numero integer;
 month float;
 year float;
 monthp float;
 yearp float;
 months text;
 monthps text;

 BEGIN
 month=DATE_PART('month',NEW.REQUEST_TS);
 year=DATE_PART('year',NEW.REQUEST_TS);
 monthp=month;
 yearp=year;
 months=month;
 monthps=monthp;
 IF month = 12 THEN
 yearp=yearp+1;
 monthp=1;
 ELSE
 monthp=monthp+1;
 END IF;
 monthps=monthp;
 IF(length(month::text)=1) THEN
 months=month::text;
 months='0' || months;
 END IF;
 IF(length(monthp::text)=1) THEN
 monthps=monthp::text;
 monthps='0' || monthps;
 END IF;
 EXECUTE 'SELECT count(*) FROM PG_TABLES WHERE SCHEMANAME=''public'' AND TABLENAME=''payment_' || year || '_' || months || '''' INTO numero;
 IF numero=0 THEN
 EXECUTE 'CREATE TABLE payment_' || year || '_' || months || '(CHECK ( REQUEST_TS >= ''' || year || '-' || months || '-01 00:00:00'' and REQUEST_TS <  ''' || yearp || '-' || monthps || '-01 00:00:00'' )) inherits (payment)';
 END IF;

 EXECUTE 'INSERT INTO payment_' || year || '_' || months || ' (id,id_request,REQUEST_TS,response)
 VALUES (
 '''||NEW.ID||''',
 '''||NEW.ID_REQUEST||''',
 '''||NEW.REQUEST_TS||''',
 '''||NEW.RESPONSE||'''
 )';
 RETURN null; END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

CREATE TRIGGER partitioning_payment
  BEFORE INSERT
  ON payment
  FOR EACH ROW
  EXECUTE PROCEDURE partitioning_payment();

Everything is working correctly.
Now, I have to add to parent table a column (is_test integer type). I've added column in parent table, and modify function in this way
CREATE OR REPLACE FUNCTION partitioning_payment()
  RETURNS trigger AS
$BODY$
 DECLARE
 numero integer;
 month float;
 year float;
 monthp float;
 yearp float;
 months text;
 monthps text;

 BEGIN
 month=DATE_PART('month',NEW.REQUEST_TS);
 year=DATE_PART('year',NEW.REQUEST_TS);
 monthp=month;
 yearp=year;
 months=month;
 monthps=monthp;
 IF month = 12 THEN
 yearp=yearp+1;
 monthp=1;
 ELSE
 monthp=monthp+1;
 END IF;
 monthps=monthp;
 IF(length(month::text)=1) THEN
 months=month::text;
 months='0' || months;
 END IF;
 IF(length(monthp::text)=1) THEN
 monthps=monthp::text;
 monthps='0' || monthps;
 END IF;
 EXECUTE 'SELECT count(*) FROM PG_TABLES WHERE SCHEMANAME=''public'' AND TABLENAME=''payment_' || year || '_' || months || '''' INTO numero;
 IF numero=0 THEN
 EXECUTE 'CREATE TABLE payment_' || year || '_' || months || '(CHECK ( REQUEST_TS >= ''' || year || '-' || months || '-01 00:00:00'' and REQUEST_TS <  ''' || yearp || '-' || monthps || '-01 00:00:00'' )) inherits (payment)';
 END IF;

 EXECUTE 'INSERT INTO payment_' || year || '_' || months || ' (id,id_request,REQUEST_TS,response,is_test)
 VALUES (
 '''||NEW.ID||''',
 '''||NEW.ID_REQUEST||''',
 '''||NEW.REQUEST_TS||''',
 '''||NEW.RESPONSE||''',
 '||NEW.IS_TEST||'
 )';
 RETURN null; END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

However, now I've got this situation:

*

*In parent table and partitioned table is_test is present

*If I make an insert on partitioned table, I've got new row

*if I make an insert on parent table, nothing happens

So, how can I add a new column correctly and permit me to do an insert on the parent table?

A: Well...shame on me. I've updated procedure, but you have to drop and recreate trigger on payment table


text:
Q: Find conditions for which 1-form is closed Let $\omega = \alpha \,\mathrm{d}r+r\beta\,\mathrm{d}\theta$ a 1-form on $\mathbb{R}^2$, where $\alpha,\beta$ are pulled back by polar coordinates.
I want to find equations for $\alpha,\beta$ where $\mathrm{d}\omega =0$.
My attempt:
$\mathrm{d}\omega = \mathrm{d}(\alpha \mathrm{d}r) + \mathrm{d}(r\beta \mathrm{d}\theta)\\= \mathrm{d}\alpha \wedge\mathrm{d}r + \mathrm{d}(r\beta) \wedge\mathrm{d}\theta=\left (\displaystyle\frac{\partial \alpha}{\partial r}\mathrm{d}r + \displaystyle\frac{\partial \alpha}{\partial \theta}\mathrm{d}\theta\right ) \wedge\mathrm{d}r + \left (\mathrm{d}r\beta + r\mathrm{d}\beta \right )\wedge \mathrm{d}\theta =\displaystyle \frac{\partial \alpha}{\partial \theta}\mathrm{d}\theta \wedge \mathrm{d}r + \beta\mathrm{d}r\wedge \mathrm{d}\theta+r\displaystyle \frac{\partial \beta }{\partial r}\mathrm{d}r\wedge\mathrm{d}\theta = \left (\beta +r\displaystyle \frac{\partial \beta}{\partial r} - \displaystyle \frac{\partial \alpha}{\partial \theta} \right )(\mathrm{d}r\wedge\mathrm{d}\theta)$
So the smooth coefficient of the 2-form has to vanish. I expected something more concise, since this is from a book.


text:
Q: How to stop img from overflowing? My problem is that I have an image that I would like to use as the logo for the website. The header and div that it is in are properly sized (i checked by inspecting it on chrome) , but the img is overflowing. How do i scale it down?
(I will use a placeholder image for the code)
Here is the code:

Here is the accompanying css, I'm confused why the max-height isn't working.
* {
  box-sizing: border-box;
}
 body{
   margin: 0;
}
header{
  height:10vh;
  width: 100%;
  float left:
  margin: 0;
  background-color:grey;
  font-family: 'Teko', sans-serif;
  display: inline-block;
}
header .navElement {
  vertical-align: middle;
  float:left;
  width: 17%;
}
.imgcontainer{
  float:left;
  max-height: 100%;
}
.imgcontainer img{
  float:left;
  max-height:100%;
}

I realize some things are unnecessary but its because i've tried so much to fix it that i don't know what works. Thanks for any helpful replies.

A: To prevent overflowing of content, you can simply use the corresponding css-property: overflow: hidden. If you do so, the content which is overflowing, will simply get cut off. In your example, this wouldn't be the right approach.
Instead of using max-height you may use height. By doing so, you'll assign an absolute value for your elements. Since your .imagecontainer only has a max-height property, try replacing it with height, as shown here.
.imgcontainer {
  float: left;
  height: 100%;
}


text:
Q: Again about Bing's house with two rooms
Possible Duplicate:
How to show that the "bing's house with two rooms" is contractible?

I don't know why my question is closed? here, I make my question clearly, when "hollowing out the chambers",why two vertical rectangles (are inserted to form 'support walls' for the two tunnels) are left ? if remove them, it remain contractible?


text:
Q: Is editing configuration cause iis recycle? I saw that in asp.net older version, editing configuration cause recycle.
(so we implemented our own library for dynamic config to avoid recycling).
Now I'm writing new asp.net core app and I have not seen anywhere that there is recycle, if using built-in configuration (like:
.AddJsonFile("appsettings.json", optional: true, **reloadOnChange: true**)

So, can I use it without expecting any down time?

A: AFAIK, editing configuration does not cause IIS recycle. One of the reason maybe is that IIS is acting now merely as a reverse proxy and the application itself runs as a separate process using the Kestrel HTTP server (if you use Kestrel).
If you need to catch moment, when configuration has been changed, you can use Configuration Reload Token  (Microsoft.Extensions.Configuration.ConfigurationReloadToken):
var config = builder.Build();
var token = config.GetReloadToken();
token.RegisterChangeCallback(_ =>
{
    Console.WriteLine("Changed");
}, null);

But note, the token only fires once, so need have code in the callback to a change token, if needed.


text:
Q: PhoneGap: media.startRecord() not working in cordova-1.6.1 I'm trying to record a sample audio with phoneGap, but with no success.
What I do is pretty simple, according to the documentation:
<script>
var media = null;

function record(){
   media = new Media("audio.wav");
   media.startRecord();
}
</script>

The "audio.wav" exists in my "www" folder and is an empty wav file.
Whenever this code block runs, I get this console error:
 - ERROR: Method 'create:withDict:' not defined in Plugin 'Media'

 - FAILED pluginJSON = {"className":"Media","methodName":"create","arguments":["INVALID","952d1fe0-5ec7-5e48-d68a-74cc979878b5","audio.wav"]}

Even with that error, the recording supposedly continues. But when I try to play the recording, I watch the media object at the debugger and I see '_duration : -1'
A different error appears when I try to debug the application on an actuall iPhone device.

A: Actually, the problem was that even thought I correctly created the file on the root directory as you depict, I couldn't access it later on, even though I got it's URI (File not found for some reason, on the same directory the file was created a second ago!!!!).
So I found out (not the easy way..) that I have to access it via "documents://". So when I create a new Media I do something like :
var mediaFile = new Media ("documents://"+audioFileName).
If I had done "var mediaFile = new Media(fileURI_I_Just_Created) It would say that file does not exist!!!! (gotta love phoneGap!)

A: You need to create a blank wav file in the root directory, not the www folder. One of the ways you can get the root directories URI is by using the method toURI().
This is what the URI will look like:
file:///data/some/com.stack.overflow/

Below is an example of how you can create a blank wav file in the root directory:
function onDeviceReady() {
  window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}

function gotFS(fileSystem) {
  fileSystem.root.getFile("blank.wav", {create: true, exclusive: false}, gotFileEntry, fail);
}

Note:

create: Used to indicate that the file or directory should be created, if it does not exist. (boolean)
exclusive: By itself, exclusive has no effect. Used with create, it causes the file or directory creation to fail if the target path

already exists. (boolean)


text:
Q: Custom view has setOnTouchListener called on it but does not override performClick (class extends Activity NOT View) I have created an Android Activity implementing a bit of OpenCV. What it does is to simply create a Custom Camera View, and when the screen is touched, the photo will be saved.
My only problem is that the code mOpenCvCameraView.setOnTouchListener(MainActivity.this); inside the BaseLoaderCallback contains a warning.
mOpenCvCameraView.setOnTouchListener(MainActivity.this); warns about

Custom view com/example/zcameratestv2/Version2CameraView has setOnTouchListener called on it but does not override performClick

Unlike other questions, my class extends an Activity not View, so when i try to override the function private boolean performClick() { ...super.performClick(); } it is not recognized. Here are my classes
package com.example.zcameratestv2;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.OpenCVLoader;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.core.Mat;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.widget.Toast;

public class MainActivity extends Activity implements CvCameraViewListener, OnTouchListener {

private Version2CameraView mOpenCvCameraView;
private static final String TAG = "Version 2::Activity";

private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
    @Override
    public void onManagerConnected(int status) {
        switch (status) {
            case LoaderCallbackInterface.SUCCESS:
            {
                Log.i(TAG, "OpenCV loaded successfully");
                mOpenCvCameraView.enableView();
                mOpenCvCameraView.setOnTouchListener(MainActivity.this);
            } break;
            default:
            {
                super.onManagerConnected(status);
            } break;
        }
    }
};

public MainActivity() {
    Log.i(TAG, "Version 2 Class instantiated");
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    setContentView(R.layout.activity_main);

    mOpenCvCameraView = (Version2CameraView) findViewById(R.id.java_surface_view);

    mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);

    mOpenCvCameraView.setCvCameraViewListener(this);

}

public void onPause()
{
    super.onPause();
    if (mOpenCvCameraView != null)
        mOpenCvCameraView.disableView();
}

@Override
public void onResume()
{
    super.onResume();
    OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this, mLoaderCallback);
}

public void onDestroy() {
    super.onDestroy();
    if (mOpenCvCameraView != null)
        mOpenCvCameraView.disableView();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, 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();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onCameraViewStarted(int width, int height) {
    // TODO Auto-generated method stub

}

@Override
public void onCameraViewStopped() {
    // TODO Auto-generated method stub

}

@Override
public Mat onCameraFrame(Mat inputFrame) {
    // TODO Auto-generated method stub
    return null;
}

@SuppressLint("SimpleDateFormat")
@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        //some code....
        break;
    case MotionEvent.ACTION_UP:
        Log.i(TAG,"onTouch event");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        String currentDateandTime = sdf.format(new Date());
        String fileName = Environment.getExternalStorageDirectory().getPath() +
                               "/sample_picture_" + currentDateandTime + ".jpg";
        mOpenCvCameraView.takePicture(fileName);
        Toast.makeText(this, fileName + " saved", Toast.LENGTH_SHORT).show();
        v.performClick();
        break;
    default:
        break;
    }
    return true;
 }

}

Previously the public boolean onTouch(View v, MotionEvent event) event had a similar warning similar to the OnTouchListener, it displays that I should use a performClick(); method but I cant override it since I extend to an Activity not a View. And I have discovered that applying v.PerformClick(); fixes this.
This other class handles the camera processes
package com.example.zcameratestv2;

import java.io.FileOutputStream;

import org.opencv.android.JavaCameraView;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.util.AttributeSet;
import android.util.Log;

public class Version2CameraView extends JavaCameraView implements PictureCallback {

private static final String TAG = "Version2::CameraView";
private String mPictureFileName;

public Version2CameraView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public void takePicture(final String fileName) {
    Log.i(TAG, "Taking picture");
    this.mPictureFileName = fileName;
    // Postview and jpeg are sent in the same buffers if the queue is not empty when performing a capture.
    // Clear up buffers to avoid mCamera.takePicture to be stuck because of a memory issue
    mCamera.setPreviewCallback(null);

    // PictureCallback is implemented by the current class
    mCamera.takePicture(null, null, this);
}

@Override
public void onPictureTaken(byte[] data, Camera camera) {
    Log.i(TAG, "Saving a bitmap to file");
    // The camera preview was automatically stopped. Start it again.
    mCamera.startPreview();
    mCamera.setPreviewCallback(this);

    // Write the image in a file (in jpeg format)
    try {
        FileOutputStream fos = new FileOutputStream(mPictureFileName);

        fos.write(data);
        fos.close();

    } catch (java.io.IOException e) {
        Log.e("PictureDemo", "Exception in photoCallback", e);
    }

}
}

I have included the required permissions in the Manifest File such as the CAMERA and the WRITE_EXTERNAL_STORAGE
Can someone determine the problem? Need your help. Thanks in advance!

A: onTouch() method gets every touch event from underlying view that hasn't been marked as "processed". If your Version2CameraView doesn't handle touch events, they are processed in Activity and your Version2CameraView is passed as View v parameter.
Unfortunately, your JavaCameraView doesn't override performClick(), but you're trying call it on this view. Solution? Add this method to your Version2CameraView class:
@Override
public boolean performClick() {
    // do what you want
    return true;
}

A: I think it is a little bit late but the solution is simple. Classes like Button, TextView are subclasses of View as well as SurfaceView which is the parent of JavaCameraView and Version2CameraView subclasses.
Then what is the difference?
The difference is that TextView implements a 'ViewTreeObserver.OnPreDrawListener' interface. For this reason, Button (which is subclass of TextView) can override the performClick() method.
How can I do with my Version2CameraView class?
Just implement an interface to override the performClick() method.
Which one, ViewTreeObserver.OnPreDrawListener? Nope, you should use SurfaceHolder.Callback like this:
public class Version2CameraView extends JavaCameraView implements PictureCallback, SurfaceHolder.Callback
{
    ...
   /**
     * Process the MotionEvent.
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        synchronized (getHolder()) {
            // Do something
            ...
            return true;
        }
    }

    @Override
    public boolean performClick() {
        // Calls the super implementation, which generates an AccessibilityEvent
        // and calls the onClick() listener on the view, if any
        super.performClick();

        // Handle the action for the custom click here

        return true;
    }
    ...
}

This solution must remove the warning that you have.

A: You need to add a method to handle the touch events since your view has called setOnTouchListener(), add an override of the default method, be sure to call the super method inside to avoid errors like "Method does not override method from its superclass", you can leave it like my sample if you are not going to process the touch events in there:
@Override
public boolean performClick() {
    super.performClick();
    return true;
}


text:
Q: Pulling data from different rows in docx I have written the code below. It works perfectly for what I want it to do which is pull data from a docx table and put it into a xlsx table. Is there a way that I can put all 3 sections that repeat into a simpler looking code?
import pandas as pd
import win32com.client as win32
import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook
word = win32.Dispatch("Word.Application")
word.Visible = 0
word.Documents.Open("C:/Users/documents/flie.docx") #Change document with tables name
doc = word.ActiveDocument

wb = Workbook()
filepath = 'C:/Users/excel.xlsx'
wb.save(filepath)
wb=load_workbook(filepath)
sheet=wb.active

**
a = []
b = []
c = []
d = []
e = []
f = []
**

for i in (list(range(3,9)) + list(range(11,42))):
    table = doc.Tables(i)
 ** a.append(table.Cell(Row = 2, Column = 2).Range.Text)
    b.append(table.Cell(Row = 3, Column = 2).Range.Text)
    c.append(table.Cell(Row = 4, Column = 2).Range.Text)
    d.append(table.Cell(Row = 4, Column = 2).Range.Text)
    e.append(table.Cell(Row = 6, Column = 2).Range.Text)
    f.append(table.Cell(Row = 7, Column = 2).Range.Text) **

**
combine_table = {(table.Cell(Row = 2, Column = 1).Range.Text) : a,
                 (table.Cell(Row = 3, Column = 1).Range.Text) : b,
                 (table.Cell(Row = 4, Column = 1).Range.Text) : c,
                 (table.Cell(Row = 5, Column = 1).Range.Text) : d,
                 (table.Cell(Row = 6, Column = 1).Range.Text) : e,
                 (table.Cell(Row = 7, Column = 1).Range.Text) : f,
                 }     **

labels = [list(range(1,38))]

df = pd.DataFrame(combine_table , index=labels)
df.to_excel("excel.xlsx")

A: You can use a nested data structure, such as a dict of lists, mapping from table row number to the list of items. Then you can use for loops to store and access data for each row.
# Dict mapping row numbers to list of
# items found on that row.
row_data = {}

# Initialize it with empty lists.
for row in range(2, 8):
    row_data[row] = []

for i in (list(range(3,9)) + list(range(11,42))):
    table = doc.Tables(i)
    for row in range(2, 8):
        row_data[row].append(table.Cell(Row = row, Column = 2).Range.Text)

# Finally, combine them back together:
combine_table = {}
for row in range(2, 8):
    combine_table[table.Cell(Row = row, Column = 1).Range.Text] = row_data[row]

But a possibly more efficient way to approach this problem is to just look at the keys in column 1 directly, assuming they're the same for all tables.
You can also use dict's setdefault() method to initialize the item to an empty list the first time it's accessed. (Using a defaultdict would work as well.)
This assumes that column 1 of all tables is the same. It's different from what you're currently doing, which is only looking at column 1 of the last table you fetch. But perhaps this approach is more consistent.
combine_table = {}
for i in (list(range(3,9)) + list(range(11,42))):
    table = doc.Tables(i)
    for row in range(2, 8):
        combine_table.setdefault(
            table.Cell(Row=row, Column=1).Range.Text,
            []
        ).append(
            table.Cell(Row=row, Column=2).Range.Text
        )

At the end of the loop, combine_table will already have all the data that you wanted.


text:
Q: mongosh: Converting circular structure to JSON I'm trying to get map results and save them into a file.
I'm using this:
fs.writeFileSync(
    "id.json",
    JSON.stringify(
        db.patient.find({},{_id: 1}).map(function(p) { return {id: p._id} })
    )
);

I'm getting this error message:
Uncaught:
TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Topology'
    |     property 's' -> object with constructor 'Object'
    |     property 'sessionPool' -> object with constructor 'ServerSessionPool'
    --- property 'topology' closes the circle

I've performed inner query alone:
I'm getting this result:
> db.patient.find({},{_id: 1}).map(function(p) { return {id: p._id} });
[
  { id: 'a94271c9-9658-4100-bc4c-9b0d118f3874' },
  { id: '25361e1b-0460-4a37-aaf3-cfe6b1ef4a06' },
  { id: '1affd292-691d-4094-af28-107b899926a6' },
  { id: '04224f3c-dd06-4d22-9783-0c4e93f5cb41' },
  { id: '3c29dbaf-304e-4060-8b80-689159c35d6e' },
  { id: '1af5eadf-86be-43a5-8b3e-73d8420fab15' },
  { id: '6cc9e843-a4b2-43eb-8177-2303a0975973' },
  { id: '0547b28b-3924-4ebd-8106-8ef03eaae8b9' },
  { id: '0539c3c9-be44-4bbb-88eb-66ec201383a7' },
  { id: 'a95ed645-a337-47be-a768-e29d1432daab' },
  { id: 'c6a2ce32-1d4b-4a5d-b778-e886cb4a205c' },
  { id: '063ba0f7-f687-49fd-ae01-23dcfcc7357a' },
  { id: '96a5f896-0ab4-46b8-9c5f-67ffcb82d728' },
  { id: '56ab0a98-ef5f-474d-a856-50444128109b' },
  { id: '311b9c3f-9f4a-4c84-b7c6-51d583a8abf6' },
  { id: '30361451-a853-46f0-b360-c5adb88cd369' },
  { id: 'b66af759-d3c2-45b0-be1d-efc1b06b3fed' },
  { id: '7699f6e5-edce-485d-b678-0424c7655de2' },
  { id: 'bbb02ef1-c572-4f30-89c9-30c8c71bd98d' },
  { id: '1db4dc43-fba8-4644-9ac8-1482bc5cae3c' }
]


text:
Q: How to get form answer in javascript's alert like window Without using any Javascript's alert() function, how to force browser to show answer from PHP server in a window like this:

A: You are not able to show such a window without JavaScript.
There are other opportunities when you don't want to use the alert() function.
For example the Bootstrap Framework has included quite a good JS Plugin.
http://getbootstrap.com/javascript/#modals


text:
Q: Apply regular expression for expressjs I need to handle requests like this:
/key/6435.254.53538

I wrote regexp that work in RegexPal
(([0-9]+\.?)+)

I create handler in Express.js
/key/:key(([0-9]+\.?)+)

but it returns only last part of the key
req.params.key == '53538'

how can I retrieve full key?

A: The problem seems to be that you accidently capture the digits, and only the last capture is returned. Try either:
/key/:key((?:[0-9]+\.?)+)

or
/key/:key(((?:[0-9]+\.?)+))

Alternatively:
/key/:key([\d.]+)

The only difference is that it allows leading and consecutive periods. If you know that will never be the case, or not a problem, then this regex is a lot easier to read.


text:
Q: Detecting the end of the stream on popen.stdout.readline I have a python program which launches subprocesses using Popen and consumes their output nearly real-time as it is produced.  The code of the relevant loop is:
def run(self, output_consumer):
    self.prepare_to_run()
    popen_args = self.get_popen_args()
    logging.debug("Calling popen with arguments %s" % popen_args)
    self.popen = subprocess.Popen(**popen_args)
    while True:
        outdata = self.popen.stdout.readline()
        if not outdata and self.popen.returncode is not None:
            # Terminate when we've read all the output and the returncode is set
            break
        output_consumer.process_output(outdata)
        self.popen.poll()  # updates returncode so we can exit the loop
    output_consumer.finish(self.popen.returncode)
    self.post_run()

def get_popen_args(self):
    return {
        'args': self.command,
        'shell': False, # Just being explicit for security's sake
        'bufsize': 0,   # More likely to see what's being printed as it happens
                        # Not guarantted since the process itself might buffer its output
                        # run `python -u` to unbuffer output of a python processes
        'cwd': self.get_cwd(),
        'env': self.get_environment(),
        'stdout': subprocess.PIPE,
        'stderr': subprocess.STDOUT,
        'close_fds': True,  # Doesn't seem to matter
    }

This works great on my production machines, but on my dev machine, the call to .readline() hangs when certain subprocesses complete.  That is, it will successfully process all of the output, including the final output line saying "process complete", but then will again poll readline and never return.  This method exits properly on the dev machine for most of the sub-processes I call, but consistently fails to exit for one complex bash script that itself calls many sub-processes.
It's worth noting that popen.returncode gets set to a non-None (usually 0) value many lines before the end of the output.  So I can't just break out of the loop when that is set or else I lose everything that gets spat out at the end of the process and is still buffered waiting for reading.  The problem is that when I'm flushing the buffer at that point, I can't tell when I'm at the end because the last call to readline() hangs.  Calling read() also hangs.  Calling read(1) gets me every last character out, but also hangs after the final line.  popen.stdout.closed is always False.  How can I tell when I'm at the end?
All systems are running python 2.7.3 on Ubuntu 12.04LTS.  FWIW, stderr is being merged with stdout using stderr=subprocess.STDOUT.
Why the difference?  Is it failing to close stdout for some reason?  Could the sub-sub-processes do something to keep it open somehow?  Could it be because I'm launching the process from a terminal on my dev box, but in production it's launched as a daemon through supervisord?  Would that change the way the pipes are processed and if so how do I normalize them?

A: The main code loop looks right.  It could be that the pipe isn't closing because another process is keeping it open.  For example, if script launches a background process that writes to stdout then the pipe will no close.  Are you sure no other child process still running?
An idea is to change modes when you see the .returncode has set.  Once you know the main process is done, read all its output from buffer, but don't get stuck waiting.  You can use select to read from the pipe with a timeout.  Set a several seconds timeout and you can clear the buffer without getting stuck waiting child process.

A: Without knowing the contents of the "one complex bash script" which causes the problem, there's too many possibilities to determine the exact cause.
However, focusing on the fact that you claim it works if you run your Python script under supervisord, then it might be getting stuck if a sub-process is trying to read from stdin, or just behaves differently if stdin is a tty, which (I presume) supervisord will redirect from /dev/null.
This minimal example seems to cope better with cases where my example test.sh runs subprocesses which try to read from stdin...
import os
import subprocess

f = subprocess.Popen(args='./test.sh',
                     shell=False,
                     bufsize=0,
                     stdin=open(os.devnull, 'rb'),
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT,
                     close_fds=True)

while 1:
    s = f.stdout.readline()
    if not s and f.returncode is not None:
        break
    print s.strip()
    f.poll()
print "done %d" % f.returncode

Otherwise, you can always fall back to using a non-blocking read, and bail out when you get your final output line saying "process complete", although it's a bit of a hack.

A: If you use readline() or read(), it should not hang. No need to check returncode or poll(). If it is hanging when you know the process is finished, it is most probably a subprocess keeping your pipe open, as others said before.
There are two things you could do to debug this:
* Try to reproduce with a minimal script instead of the current complex one, or
* Run that complex script with strace -f -e clone,execve,exit_group and see what is that script starting, and if any process is surviving the main script (check when the main script calls exit_group, if strace is still waiting after that, you have a child still alive).

A: I find that calls to read (or readline) sometimes hang, despite previously calling poll. So I resorted to calling select to find out if there is readable data. However, select without a timeout can hang, too, if the process was closed. So I call select in a semi-busy loop with a tiny timeout for each iteration (see below).
I'm not sure if you can adapt this to readline, as readline might hang if the final \n is missing, or if the process doesn't close its stdout before you close its stdin and/or terminate it. You could wrap this in a generator, and everytime you encounter a \n in stdout_collected, yield the current line.
Also note that in my actual code, I'm using pseudoterminals (pty) to wrap the popen handles (to more closely fake user input) but it should work without.
# handle to read from
handle = self.popen.stdout

# how many seconds to wait without data
timeout = 1

begin = datetime.now()
stdout_collected = ""

while self.popen.poll() is None:
    try:
        fds = select.select([handle], [], [], 0.01)[0]
    except select.error, exc:
        print exc
        break

    if len(fds) == 0:
        # select timed out, no new data
        delta = (datetime.now() - begin).total_seconds()
        if delta > timeout:
            return stdout_collected

        # try longer
        continue
    else:
        # have data, timeout counter resets again
        begin = datetime.now()

    for fd in fds:
        if fd == handle:
            data = os.read(handle, 1024)
            # can handle the bytes as they come in here
            # self._handle_stdout(data)
            stdout_collected += data

# process exited
# if using a pseudoterminal, close the handles here
self.popen.wait()

A: Why are you setting the sdterr to STDOUT?
The real benefit of making a communicate() call on a subproces is that you are able to retrieve a tuple containining the stdout response as well as the stderr meesage.
Those might be useful if the logic depends on their succsss or failure.
Also, it would save you from the pain of having to iterate through lines. Communicate() gives you everything and there would be no unresolved questions about whether or not the full message was received

A: I wrote a demo with bash subprocess that can be easy explored.
A closed pipe can be recognized by '' in the output from readline(), while the output from an empty line is '\n'.
from subprocess import Popen, PIPE, STDOUT
p = Popen(['bash'], stdout=PIPE, stderr=STDOUT)
out = []
while True:
    outdata = p.stdout.readline()
    if not outdata:
        break
    #output_consumer.process_output(outdata)
    print "* " + repr(outdata)
    out.append(outdata)
print "* closed", repr(out)
print "* returncode", p.wait()

Example of input/output: Closing the pipe distinctly before terminating the process. That is why wait() should be used instead of poll()
[prompt] $ python myscript.py
echo abc
* 'abc\n'
exec 1>&- # close stdout
exec 2>&- # close stderr
* closed ['abc\n']
exit
* returncode 0
[prompt] $

Your code did output a huge number of empty strings for this case.

Example: Fast terminated process without '\n' on the last line:
echo -n abc
exit
* 'abc'
* closed ['abc']
* returncode 0


text:
Q: No converter for [class java.lang.String] with preset Content-Type 'text/plain' I'm trying to return a formatted string from a endpoint with spring, with the following code
private static class Json
            implements Serializable {
        private final String value;

        public Json(String value) {
            this.value = value;
        }

        public String getValue() {
            return this.value;
        }

        @Override
        public String toString() {
            return "Json{" +
                    "value='" + value + '\'' +
                    '}';
        }
    }
    @RequestMapping(value = "/description", method = RequestMethod.GET)
    public HttpEntity<String> retrieveDescription() {

        String text = this.retrieveDescription();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.TEXT_PLAIN);

        return new HttpEntity<String>(text, headers);
    }

But when I execute the request I get the following error

No converter for [class java.lang.String] with preset Content-Type 'text/plain'

I've tried returning the Json class but still the same problem
Any idea how to solve it?


text:
Q: How to forbid special characters in first and last character of email username I have a form I'm trying to do validation on.  Requirements state that underscore and hyphen are allowed in the email username, but NO special characters (including hyphen and underscore) are allowed as the leading and/or trailing character of the email username.
Would this be done using regex in the form validation?  Or would it be done in a separate jquery function?  I'm trying to fire an error in the case that a special character is used as the first or last character of the email username.
Here's my validation code for the email field:
email: function(value, element) {
        // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
        return this.optional(element) || /^((([a-z]|\d|[\-\_]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[\-\_]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(value);
    },

And here's the code for the registration form validation:
if (form == 'registration') {
    var validation_rules = {
        rules: {
            password_confirm: {
                equalTo: "#password"
            },
            email: {

            },
            email_confirm: {
                equalTo: "#email"
            },
            dd_reg_month: "required"
        },
        groups: {
            birthday: "dd_reg_month dd_reg_year"
        },
        errorPlacement: function(error, element) {
            if (element.attr("name") == "dd_reg_month" || element.attr("name") == "dd_reg_year") $("#reg_birthday").append(error);
            else error.insertAfter(element);
        },
        validClass: "success",
        success: "success",
        focusInvalid: false,
        invalidHandler: function(form, validator) {
            var errors = validator.numberOfInvalids();
            var ipAddress =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
                if (errors) {
                    var message = errors == 1 ? 'Please correct the error below' : 'Please correct the ' + errors + ' errors below.';
                    $("div.error_info").html(message);
                    $("div.error_info").show();

                } else {
                    $("div.error_info").hide();
                    $('form input.success').css('border-color', 'green');
                }
        },
        ignore: ".ignore"

    };
}

Any help, even a clue as to how to deal with leading and trailing characters, would be totally awesome.

A: thanks for the contribution guys!  I found some regex that did the trick - this site is really helpful: http://regexlib.com/DisplayPatterns.aspx
The pattern I used was this, posted by Rob Eberhardt:
^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$

Figured I'd share in case anyone comes across the same problem. Check out the regex library if you need to do other things with email validation, it's got a lot of great patterns. I'm new to regex and hadn't heard of it yet until today. :-)
Thanks again!

A: If the special requirements should trigger the same error as a regular invalid email you can put it in the validation function.
It could probably be included in the email validation regex but I'm not going to dive into that huge thing to change it. My code below will tack on an extra regex, after the email is validated, to test for your special case.
email: function(value, element) {
    // contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
    var valid = this.optional(element) || /^((([a-z]|\d|[\-\_]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[\-\_]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(value);
    return valid && /^[a-z].*[a-z]@.+/i.test(value);
},

A: I don't know jquery, but if the regexes are .NET maybe just inserting a couple of lookahead and lookbehind assertions might solve the problem.
This is expanded. Just look where they are added and insert them into your regex.
If it works great, if not, was worth the try.
/
  ^
    (

(?![_-])

      (
         (
            [a-z]
          | \d
          | [\-\_]
          | [\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]
         )+
         (
           \.
           (
              [a-z]
            | \d
            | [\-\_]
            | [\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]
           )+
         )*

(?<![_-])

      )

    |

      (
        (\x22)                                           "

(?![\x01-\x20\x7f]*[_-])

        (
           (
              (
                 (\x20|\x09)*
                 (\x0d\x0a)
              )?
              (\x20|\x09)+
           )?
           (
              (
                 [\x01-\x08\x0b\x0c\x0e-\x1f\x7f]
               | \x21
               | [\x23-\x5b]
               | [\x5d-\x7e]
               | [\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]
              )
            |
              (
                 \\
                 (
                    [\x01-\x09\x0b\x0c\x0d-\x7f]
                  | [\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]
                 )
              )
           )
        )*
        (
           (
              (\x20|\x09)*
              (\x0d\x0a)
           )?
           (\x20|\x09)+
        )?

(?<![_-][\x01-\x20\x7f]*)

        (\x22)                                           "
      )
    )

    @

    ((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i


text:
Q: SQL WHERE statement is not working with RIGHT JOIN I have the below SQL query, but the problem is that the WHERE statement is not working properly with RIGHT JOIN:
   SELECT COUNT(*) no_of_application_by_status, applicationStatusName
    FROM `Application` `a`
    right JOIN `ApplicationStatus` `ass` ON `ass`.`applicationStatusId`=`a`.`applicationStatusId`
    WHERE `applicationTypeId` = '40007'
    GROUP BY `ass`.`applicationStatusId`

I want to get the applicationStatusName where no_of_application_by_status = 0

A: You have to put the where condition to the on clause:
SELECT COUNT(*) no_of_application_by_status, applicationStatusName
    FROM `Application` `a`
    right JOIN `ApplicationStatus` `ass` ON `ass`.`applicationStatusId`=`a`.`applicationStatusId`
   and `applicationTypeId` = '40007'
    GROUP BY `ass`.`applicationStatusId`

If you do not do it, the joind result will be filtered by the where condition.

A: Use Having you want to fetch group count = 0 OR if you want to count only the records where no_of_application_by_status = 0 then use AND condition in WHERE
For Group Count = 0
SELECT COUNT(*) no_of_application_by_status,
    applicationStatusName
FROM Application a
RIGHT JOIN ApplicationStatus ass ON ass.applicationStatusId=a.applicationStatusId
WHERE applicationTypeId = '40007'
HAVING COUNT(*) = 0
GROUP BY ass.applicationStatusId

OR count of no_of_application_by_status = 0
SELECT COUNT(*) no_of_application_by_status,
    applicationStatusName
FROM Application a
RIGHT JOIN ApplicationStatus ass ON ass.applicationStatusId=a.applicationStatusId
WHERE applicationTypeId = '40007' AND no_of_application_by_status = 0
GROUP BY ass.applicationStatusId


text:
Q: Spring Cloud OAuth2Authentication returns NullPointerException I'm slowly moving into understanding Spring Cloud Security. I've created an authorization service and it works when authorizing and returning a token, but doesn't return any current user details when using that token, when getting these from OAuth2Authentication. This two lines return an NPE:
userInfo.put("user", user.getUserAuthentication().getPrincipal());
            userInfo.put("authorities", AuthorityUtils.authorityListToSet(user.getUserAuthentication().getAuthorities()));

OAuth2Authentication user isn't instantiated and is null, while I understood that it should be by default instantiated by Spring Security. Maybe I am missing some configuration beans? Thanks in advance!
Application.class
@SpringBootApplication
@RestController
@EnableResourceServer
@EnableAuthorizationServer
public class AuthorizationServiceApplication {

    @RequestMapping(value = {"/user"}, produces = "application/json")
    public Map <String, Object> user (OAuth2Authentication user) {
        Map <String, Object> userInfo = new HashMap <>();
        userInfo.put("user", user.getUserAuthentication().getPrincipal());
        userInfo.put("authorities", AuthorityUtils.authorityListToSet(user.getUserAuthentication().getAuthorities()));
        return userInfo;
    }

    public static void main (String[] args) {
        SpringApplication.run(AuthorizationServiceApplication.class, args);
    }
}

OAuth2Config.class
@Configuration
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Value("${token.secret}")
    private String secret;
    private AuthenticationManager authenticationManager;
    private UserDetailsService userDetailsService;

    public OAuth2Config (AuthenticationManager authenticationManager, UserDetailsService userDetailsService) {
        this.authenticationManager = authenticationManager;
        this.userDetailsService = userDetailsService;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("eagleeye")
                .secret(secret)
                .authorizedGrantTypes("refresh_token", "password", "client_credentials")
                .scopes("webclient", "mobileclient");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService);
    }
}

WebSecurityConfigurer.class
@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean () throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    @Bean
    public UserDetailsService userDetailsServiceBean() throws Exception {
        return super.userDetailsServiceBean();
    }

    // TODO: implemented DB stuff
    @Override
    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder
                .inMemoryAuthentication()
                .withUser("deniss").password("deniss1").roles("USER")
                .and()
                .withUser("oksana").password("oksana").roles("USER, ADMIN");
    }

    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setSessionAttributeName("_csrf");
        return repository;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().csrfTokenRepository(csrfTokenRepository());
    }
}

A: In the end I got it working like this:
Application.class
@SpringBootApplication
@RestController
@EnableResourceServer
public class AuthorizationServiceApplication {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("/user")
    public Principal user(Principal user) {
        log.info("User information display for User: " + user.getName());
        return user;
    }

    @Bean
    UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("deniss").password("deniss").roles("USER").build());
        return manager;
    }

    public static void main (String[] args) {
        SpringApplication.run(AuthorizationServiceApplication.class, args);
    }
}

OAuth2Config.java
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    //TODO: refactor to recieve this info from config server
    @Value("${token.secret}")
    private String secret;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("eagleeye")
                .secret(secret)
                .authorizedGrantTypes("refresh_token", "password", "client_credentials")
                .scopes("webclient", "mobileclient");
    }
}

SecurityConfigurer.class
@Configuration
@EnableGlobalAuthentication
public class SecurityConfigurer extends GlobalAuthenticationConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    // TODO: implemented DB stuff
    @Override
    public void init(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(this.userDetailsService);
    }
}

A: I met the same problem, it seems a bug of new version. I changed Spring Boot 1.5.9.RELEASE,Spring Cloud Edgware.RELEASE backed to Spring Boot 1.4.4.RELEASE,Spring Cloud Camden.SR5, the problem disappeared.

A: Set security.oauth2.resource.filter-order=3 configuration property to restore the ordering used in previous versions. See enter link description here for more details.


text:
Q: Quaternions still have gimbal lock Instead of Euler angles I moved to Quaternions to represent and process the rotation of a cube in 3D. Although it would solve gimbal lock, I'm still experiencing this issue.
My code is:
// p is the point to be rotated
// angles is a Vector3D representing the rotation angles

var xaxis = new Vector3D(1, 0, 0);
var yaxis = new Vector3D(0, 1, 0);
var zaxis = new Vector3D(0, 0, 1);

p = rotate(p, xaxis, angles.x);
p = rotate(p, yaxis, angles.y);
p = rotate(p, zaxis, angles.z);

The rotate functions comes from http://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#Pseudo-code_for_rotating_using_a_quaternion_in_3D_space (translated into JavaScript).
I guess the problem is due to the fact that I still use an order of axes (x y z) which is the main problem of gimbal lock.
How would one implement quaternion rotation in such a way that gimbal lock is solved?
Thanks in advance.

A: Quaternions are not susceptible to gimbal lock, so that's not your problem.  If your
x, y, and z angles are intended to represent something like Euler angles, the issue
is more likely that you're defining xaxis, yaxis, and zaxis relative to the original
coordinate system.  But that won't give the expected results, because after the first
rotation around xaxis, the Y and Z axes don't point in the original directions
any more, yet the next two rotations are still referenced to the original coordinate
system.

A: As you mention the gimbal lock issue arises anytime you do three consecutive rotations (such as Euler Angles) to get from an inertial coordinate frame to a body frame. This includes combining three successive quaternion rotations (through a operation called composition).
The reason why quaternions can overcome gimbal lock is that they can represent the transformation from the inertial coordinate frame to the body fixed frame in a single rotation. This is however imho the big disadvantage of quaternions - it is not physically intuitive to come up with a desired quaternion.


text:
Q: duplicating cookies to another domain I have user preference (colour, locale settings) on example.com that I would like to migrate to example2.com
I'm wondering if I can use AJAX or a hidden iFrame to pass the cookie information from example.com to example2.com which will then set another cookie with the same information on example2.com.
I know I could do this easily through the URL string and a redirect, but I would like to achieve this in the background if possible -- no redirects -- and needs to work on major browsers (IE6+, FF1.5+, Safari, Opera)
Point is this cookie information isn't secure so there's no risk there.

A: It depends on the browser setup for starters, if the browser is configured to reject 3rd party cookies you're out of luck.
Assuming that you control example.com, and the cookie is not an HTTP only cookie you could add a script. The script would write out an img tag pointing to a script on example2.com, with document.cookies as the parameter. Within the script write out a 1x1 transparent gif and attach the cookie from example to the response, having parsed the parameter string to pull out the cookie name/value pairs.

A: Setup a path on example.com that generates a javascript file containing the cookies passed in. Lets say it is example.com/get_cookie.js
Then you can do an ajax call from example2.com to example.com/get_cookie.js to get those cookies, and save them under example2.com.
Since it is cross-domain, you can't use XHR (XmlHttpRequest), instead you'll have append get_cookie.js as a javascript node, and that javascript file will have to call a callback to pass you the data.
So get_cookie.js would look somthing like:
return_data( 'here is my example.com cookie info' );

A: You would need to make a server-to-server XMLHTTP request, and have the second server recreate the cookies. You can't "pass" them.

A: Have you considered using Flash Cookies to store those preferences? The work with all the major browsers include chrome.
http://www.ghacks.net/2007/05/04/flash-cookies-explained/


text:
Q: Can't pass password validation Android I just want to check if the given passwords are not equal to each other. So I had made this:
    String password = etPassword.getText().toString().trim();
    String confirmPassword = etConfirmPassword.getText().toString().trim();

    if (password != confirmPassword) {
        Toast.makeText(getApplicationContext(),
                "Passwords do not match", Toast.LENGTH_LONG)
                .show();
    }

But somehow it doesn't work. I have logged it when I gave an input value "e" for both passwords.

A: use this equals() method instead of != like this:
if (!password.equals(confirmPassword)) {

With Strings you almost always want to use the equals method. In fact with Objects in general you do.

A: You cannot use != , try to compare with .equals()
if (password.equals(confirmPassword) == false) {
        Toast.makeText(getApplicationContext(),
                "Passwords do not match", Toast.LENGTH_LONG)
                .show();
    }


text:
Q: Error in compiling curl with openssl1.1.1i Below is the error I am getting when compiling curl with openssl1.1.1i static libs.
In file included from /home/administrator/Development/myapp/thirdparty/curl/lib/curl_setup.h:76:0,
                 from /home/administrator/Development/myapp/thirdparty/curl/lib/altsvc.c:26:
/home/administrator/Development/myapp/build/thirdparty/curl/lib/curl_config.h:1033:19: error: two or more data types in declaration specifiers
 #define in_addr_t unsigned long
                   ^

/home/administrator/Development/myapp/thirdparty/curl/lib/curl_config.h:1033:28: error: two or more data types in declaration specifiers
 #define in_addr_t unsigned long
                            ^

myapp/thirdparty/curl/lib/CMakeFiles/libcurl.dir/build.make:62: recipe for target 'myapp/curl/lib/CMakeFiles/libcurl.dir/altsvc.c.o' failed
make[2]: *** [myapp/thirdparty/curl/lib/CMakeFiles/libcurl.dir/altsvc.c.o] Error 1


text:
Q: Search git log using a comment I check my git logs using git log --stat which shows me all the commits and the files that were changed in those commits.
Now there is a commit that was  made a long time ago, I remember a part of the commit message such that  when I do git log --stat | grep 'message text' the log shows only the commit messages in which 'message text' exists.
I, however need to see at least the commit id along with the grep results. How do I achieve this?

A: Try using this to get complete information.
git log --all --grep='Your text here'

Git Version used:
git version 2.9.0.windows.1

Example:
$ git log --all --grep='Favourite Module modifie'

Result:
commit 8226dce6f4f5ffd8143b8aefdee3b9b971040aa0
Author: Surender Singh <sure**@gmail.com> Date: Thu Aug 25 11:29:32 2016 +0530
view Favourite Module modified

A: Try using --oneline :
git log --oneline | grep -F 'message text'

Otherwise, pipe your result through less, and searching using less:
git log | less
/message text

A: Use opts for grep to show more context lines. Choose appropriate size of num to see your id.
grep -A num -B num

A: This will find your comment.
git log --grep "search text" --author your_name

Atlassian Documentation for git log Scroll down to "By Message" for more detials.
As an aside you can use --author twice. I needed to look for a set of check-ins made by two developers. This is my favorite way to look for that needle in git's haystack. --pretty=online does two things, 1) each commit is on one line, and 2) the full commit reference number is displayed. Just using --oneline give the same except the commit reference number is abbreviated.
git log --grep "#Bug" --author jones --author smith --pretty=oneline

\dev8.4> git log --grep "#Bug" --author jones --author smith --pretty=oneline
80334597b56add0ad4a3ddd02e7a6514bf01ad1e #Bug -- Further Mods To Code - CC Save
16cc3b4e949e965de9b72eb4583fa8df659528a0 #Bug -- Use new get charge function to load CC.
b207498261b4622ef88cb696365bf9af2f3fc6e1 #Bug -- Reference now editable after CC scan.
56385b7a77e2ec9af3b827f6a9ba93c22f267e51 #Bug -- Reload Entire Page after CC charge.
19e9cb05dabd8cc7c9a80e64187821d562af043c #Bug -- force Guid after save event.
c363ed97fdc2b56d1fcd84ca48eb300dbb120a3d #Bug -- Guid was getting lost in some cases.


text:
Q: How can I define map extent based on points displayed? I have the following map I've made, by overlaying points on a mapbox map using d3.js.
I'm trying to get the map to zoom so that the map extent just includes the d3 markers (points).
I think the pseudocode would look something like this:
//find the northernmost, easternmost, southernmost, westernmost points in the data

//get some sort of bounding box?

//make map extent the bounding box?

Existing code:

Update
I found this code for reference, linked here at https://data-map-d3.readthedocs.io/en/latest/steps/step_03.html:
    function calculateScaleCenter(features) {
  // Get the bounding box of the paths (in pixels!) and calculate a
  // scale factor based on the size of the bounding box and the map
  // size.
  var bbox_path = path.bounds(features),
      scale = 0.95 / Math.max(
        (bbox_path[1][0] - bbox_path[0][0]) / width,
        (bbox_path[1][1] - bbox_path[0][1]) / height
      );

  // Get the bounding box of the features (in map units!) and use it
  // to calculate the center of the features.
  var bbox_feature = d3.geo.bounds(features),
      center = [
        (bbox_feature[1][0] + bbox_feature[0][0]) / 2,
        (bbox_feature[1][1] + bbox_feature[0][1]) / 2];

  return {
    'scale': scale,
    'center': center
  };
}

However, when I run the function:
  var scaleCenter = calculateScaleCenter(data);
  console.log("scalecenter is", scaleCenter)

I get the error:
path is not defined

Furthermore, it seems like I would need to dynamically adjust the center and zoom parameters of the mapbox map. Would I just set these values dynamically with the values produced by the calculateScaleCenter function?

A: The readthedocs example code is erroneously missing a bit of code
Your javascript code is reporting that you have not defined the variable path before using it. You have copied it correctly from readthedocs, but the code you are copying contains an omission.
Fortunately, on the readthedocs version of the code snippet, there is a mention of a Stack Overflow answer http://stackoverflow.com/a/17067379/841644
that gives more information.
Does adding this information, or something similar corresponding to your situation, help fix your problem?
var projection = d3.geo.mercator()
    .scale(1);

var path = d3.geo.path()
    .projection(projection);


text:
Q: Error in using created custom widget in designer I am having a problem on using created custom widget. I have successfully created a custom widget that produces .dll file. I placed this .dll file under bin/designer. It was also recognized in the designer. I used it and placed it on my ui. But when I tried to build it, error occurred.

debug\moc_scribblearea.cpp(44) : warning C4273: 'staticMetaObject' : inconsistent dll linkage
      d:\project\qt\workspace\sample-build-desktop\debug../../oep/scribblearea.h(53) : see previous definition of 'public: static QMetaObject const ScribbleArea::staticMetaObject'
debug\moc_scribblearea.cpp(44) : error C2491: 'ScribbleArea::staticMetaObject' : definition of dllimport static data member not allowed
debug\moc_scribblearea.cpp(54) : warning C4273: 'ScribbleArea::metaObject' : inconsistent dll linkage
  d:\project\qt\workspace\sample-build-desktop\debug../../sample/scribblearea.h(53) : see previous definition of 'metaObject'
debug\moc_scribblearea.cpp(59) : warning C4273: 'ScribbleArea::qt_metacast' : inconsistent dll linkage
  d:\project\qt\workspace\sample-build-desktop\debug../../sample/scribblearea.h(53) : see previous definition of 'qt_metacast'
debug\moc_scribblearea.cpp(67) : warning C4273: 'ScribbleArea::qt_metacall' : inconsistent dll linkage
  d:\project\qt\workspace\sample-build-desktop\debug../../oep/scribblearea.h(53) : see previous definition of 'qt_metacall'

How can I use my created custom widget correctly? Are there any document/reference that describes how to use custom widget, from copying .dll to bin/designer folder upto building a project?

A: I have never created a custom widget stored in a .dll, therefore I can't help your on your primary question, but I have a workaround to offer:
If your custom widget is relatively simple (it does not have complex properties that explicitly require the Form-Editor) you can create a placeholder of another kind (e.g. a superclass of your widget) in your container-form, to be able to set the basic properties like position, geometry, size & size-policy and then replace this placeholder with your custom widget using some simple code in the container-form constructor.
Let's say that you have the following:
a. A custom widget GuiInpImageView inheriting from QGraphicsView:
GuiInpImageView::GuiInpImageView(QWidget *parent):QGraphicsView(parent)
b. A mainwindowbase.ui (class MainWindow) at which you actually want to put an instance of GuiInpImageView
This is the workaround solution step-by-step:

*

*Put the .cpp source & header file for GuiInpImageView directly in your project (not in a DLL)

*Define the following private member in MainWindow class header:
GuiInpImageView *inpImageView;

*Open the mainwindowvase.ui in Form-Editor and put a QGraphicsView widget at the position you actually wanted to put your custom GuiInpImageView widget.
Let's say you have created a vertical layout named inpImageViewVertLayout containing a QGraphicsView named inpImageViewPH (PH = PlaceHolder).
You can also set -if you wish- the geometry, Min & Max Size and the size policy of inpImageViewPH using the properties exposed in form-editor of QtCreator.

*Put the following code into your MainWindow constructor:

   // Main Window Constructor
   MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
   {
setupUi(this); // Setup UI

// Replace inpImageViewPH with custom Widget
// (inpImageViewPH is just a place holder to visualize UI in design mode)
inpImageView = new GuiInpImageView(centralwidget);
inpImageView->setGeometry(inpImageViewPH->geometry());
inpImageView->setMinimumSize(inpImageViewPH->minimumSize());
inpImageView->setMaximumSize(inpImageViewPH->maximumSize());
inpImageView->setSizePolicy(inpImageViewPH->sizePolicy());
inpImageViewVertLayout->addWidget(inpImageView);
// Remove and hide placeholder, keep only the Custom View
inpImageViewVertLayout->removeWidget(inpImageViewPH);
inpImageViewPH->hide();

...

This is the easiest way I have found to insert a custom widget in a form using code (without creating a .DLL) but to have also a graphical-preview and some control about the position & size of the widget in the form-container.
Hope this helps...


text:
Q: Computing $\lim_{x→\infty}\ln(3x ^2 − 4x + 2) − \ln(5x ^2 + 19x − 1)$ I've been having troubles with limits, any help would be greatly appreciated.

A: Hint: Use the $\ln$ property: $\ln(a)-\ln(b)=\ln\left(\frac{a}{b}\right)$.
$$\lim_{x\to\infty}\ln\left(\frac{3x^2-4x+2}{5x^2+19x-1}\right)=\lim_{x\to\infty}\ln\left(\frac{3-\frac{4}{x}+\frac{2}{x^2}}{5+\frac{19}{x}-\frac{1}{x^2}}\right)$$
$\ln$ is continuous, so we can swap $\lim$ and $\ln$:
$$\ln\lim_{x\to \infty}\left(\frac{3-\frac{4}{x}+\frac{2}{x^2}}{5+\frac{19}{x}-\frac{1}{x^2}}\right)$$

A: Since logarithmic functions are continuous we have
\begin{align}
\lim_{x\to\infty}\ln(3x^2-4x+2)-\ln(5x^2+19x-1)&=\lim_{x\to\infty}\ln\left(\frac{3x^2-4x+2}{5x^2+19x-1}\right)\\
&=\ln\left(\lim_{x\to\infty}\frac{3x^2-4x+2}{5x^2+19x-1}\right)
\end{align}


text:
Q: Using Fractions in Python I'm using classes here to input a fraction (when given the numerator and denominator), as well as add and multiply two fractions together. For some reason, the imported fractions module only works correctly for part of the program; the gcd method works, but the Fraction method (where when given two numbers, puts into fraction format) does not work, instead throwing a NameError (specifically, "global name 'Fractions' is not defined").
What am I doing wrong? I am relatively new to Python, and any suggestions on how to make this code tighter with more exceptions would be greatly appreciated.
Here is my code:
import fractions

class FractionClass:
    # Initialize starting numerator and denominator.
    n = 0
    d = 0
    def __init__(self, numerator, denominator):
        self.n = numerator
        self.d = denominator

    # Function that adds fractions, whichs throws NameError if gcd() doesn't work!
    def add_fractions(self, other):
        try:
            sum_numerator = self.n + other.n
            sum_denominator = fractions.gcd(self.d, other.d)
            return(sum_numerator, sum_denominator)
        except NameError:
            print("Methods aren't defined.")

    # Function that multiplies fractions, whichs throws NameError if gcd() doesn't work!
    def multiply_fractions(self, other):
        try:
            product_numerator = self.n * other.n
            product_denominator = self.d * other.d
            return(product_numerator, product_denominator)
         except NameError:
            print("Methods aren't defined.")

    # Enter input function.
def user_input():
    try:
        print("Enter a numerator and denominator:")
        n, d = [int(x) for x in input().split()]
        print("Enter a numerator and denominator:")
        n2, d2 = [int(x) for x in input().split()]
        # Check used to debug for denominators that aren't the minimum of 1 (0 can't be divided!)
        check = 1 / d
        check = 1 / d2
        # print(check)

        # Exception for d = 0.
    except ZeroDivisionError:
        print("\n You didn't enter the minimum denominator.")
        print("Set denominator to minimum default.")
        d = 1
        # Exception for not entering a space in between numbers.
    except UnboundLocalError:
        print("You didn't enter your numbers in properly! Try again.")
        # Exception for not entering all required.
    except NameError:
        print("\n You didn't enter two numbers.")
        # Exception for user input both or one of them, not being integers.
    except TypeError:
        print("\n You didn't enter all valid numbers.")
        # General exception case.
    except:
        print("Something went wrong!")

    fract = FractionClass(n,d)
    another_fraction = FractionClass(n2, d2)
    total_sum = fract.add_fractions(another_fraction)
    # Unpacks total sum tuple.
    # Puts in fraction format.
    sum_numerator, sum_denominator = total_sum
    add_output = fractions.Fraction(sum_numerator, sum_denominator)
    total_product = fract.multiply_fractions(another_fraction)
    # Unpacks product sum tuple.
    # Puts in fraction format.
    product_numerator, product_denominator = total_product
    multiply_output = fractions.Fraction(product_numerator, product_denominator)
    print(add_output, multiply_output)

A: You don't need your own class to multiply two fractions:
>>> from fractions import Fraction as F
>>> F("1/2")
Fraction(1, 2)
>>> F("3/4")
Fraction(3, 4)
>>> F("1/2") * F("3/4")
Fraction(3, 8)
>>> F("1/2") + F("3/4")
Fraction(5, 4)
>>> F(5, 8) + F(4, 7)
Fraction(67, 56)

As for the error you mentioned, it's unlikely as you don't have a name "Fractions" anywhere in your code and you didn't post a traceback. You're most likely running some old version of your code.

A: There is one more space at the line 26:
         except NameError:

It should be
        except NameError:

You should also check and fix the indentation. Otherwise, there is no body -- nothing is called.


text:
Q: ansible-playbook unable to use regex I am using ansible version 2.7. I was practicing a task where I have to add users whose username and uid stored in var file named /home/automation/plays/vars/user_list.yml  and password for the same is stored in secrets.yml having correct content. I am also able to add user from it with with_item but with next requirement of task I need to add users whose uid stats with 1* on specified hostgroup which is called with "group_names"  i was trying match regex for the same but getting error
My requirement is add a user whose udi begins with ^1  to hostgroup "webserver"
I have used with explict uids such 1201 / 1201 which is working but not working with regex
- hosts: all
  become: yes
  gather_facts: no
  vars_files:
     - /home/automation/plays/vars/user_list.yml
     - secrets.yml
  tasks:
     - debug:
         msg: "{{users | type_debug}},{{user_password}}"
       with_items: "{{ users }}"
     - name: Adding Users to webserver groupwith List
       user:
        name: "{{item.username}}"
        uid:   "{{item.uid}}"
        state: absent
        remove: yes
        password: "{{ user_password }}"
        shell: /bin/bash
        groups: wheel
        generate_ssh_key: yes
        ssh_key_bits: 2048
        ssh_key_file: .ssh/id_rsa
       when:  item.uid  is regex("1.*")
       with_items: "{{users}}"

fatal: [ansnode_1]: FAILED! => {"msg": "The conditional check 'item.uid  is regex(\"1.*\")' failed. The error was: Unexpected templating type error occurred on ({% if item.uid  is regex(\"1.*\") %} True {% else %} False {% endif %}): expected string or buffer\n\nThe error appears to have been in '/home/automation/plays/users.yml': line 12, column 8, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n       with_items: \"{{ users }}\"\n     - name: Adding Users to webserver groupwith List\n       ^ here\n"}
fatal: [ansnode_4]: FAILED! => {"msg": "The conditional check 'item.uid  is regex(\"1.*\")' failed. The error was: Unexpected templating type error occurred on ({% if item.uid  is regex(\"1.*\") %} True {% else %} False {% endif %}): expected string or buffer\n\nThe error appears to have been in '/home/automation/plays/users.yml': line 12, column 8, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n       with_items: \"{{ users }}\"\n     - name: Adding Users to webserver groupwith List\n       ^ here\n"}
fatal: [ansnode_2]: FAILED! => {"msg": "The conditional check 'item.uid  is regex(\"1.*\")' failed. The error was: Unexpected templating type error occurred on ({% if item.uid  is regex(\"1.*\") %} True {% else %} False {% endif %}): expected string or buffer\n\nThe error appears to have been in '/home/automation/plays/users.yml': line 12, column 8, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n       with_items: \"{{ users }}\"\n     - name: Adding Users to webserver groupwith List\n       ^ here\n"}
fatal: [ansnode_3]: FAILED! => {"msg": "The conditional check 'item.uid  is regex(\"1.*\")' failed. The error was: Unexpected templating type error occurred on ({% if item.uid  is regex(\"1.*\") %} True {% else %} False {% endif %}): expected string or buffer\n\nThe error appears to have been in '/home/automation/plays/users.yml': line 12, column 8, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n       with_items: \"{{ users }}\"\n     - name: Adding Users to webserver groupwith List\n       ^ here\n"}

A: Let's assume the users have already been created and
"the requirement is to add users whose uid begins with '1' to group 'webserver'".
The task below does the job
    - name: Adding users to webserver group
      user:
        name: "{{ item.username }}"
        groups: webserver
      loop: "{{ users }}"
      when:  item.uid|string|first == '1'

Regex

*

*The condition below is an equivalent

      when: item.uid|string is match('^1.*$')

*To match the user "where userid ends with 5" use

      when: item.uid|string is match('^.*5$')

A: In the official documentation for Ansible 2.7, there is no reference to the regex filter. It appears only in the documentation for Ansible 2.8, so I assume it is a new addition of that version.
According to that same documentation, regex("1.*") will not match the UIDs starting with "1", but all the UIDs containing "1". You will want to use match("1.*") instead, that should work with your version of Ansible.

A: With this task.
tasks:
- name: Create users
  user:
    name: "{{ item.username }}"
    group: wheel
    password: "{{ user_password | password_hash('sha512') }}"
    shell: /bin/bash
    update_password: on_create
  with_items: "{{ users }}"
  when:
    - ansible_fqdn in groups['webservers']
    - "item.uid|string|first == '1'"


text:
Q: Setting an ID as an Integer with C# I am currently using the following script to set this value as a String:
string ID = Request.QueryString["ID"].ToString();
However, I'd now like to store it as an Integer.
How do I do this?
Many thanks for any pointers.

A: Assuming you don't want to throw a server error on a bad string
int id=0;
if (int.TryParse(Request.QueryString["ID"],out id)) {
  .. logic for valid id
} else {
  .. logic for invalid id
}

A: int ID = int.Parse(Request.QueryString["ID"].ToString());

A: Use either of these:
If you know that you have an ID:
string ID = Request.QueryString["ID"];
int integerId = int.Parse(ID);

or, if the query string may be missing or invalid (never trust query strings....)
string ID = Request.QueryString["ID"];
int integerId;
if (int.TryParse(ID, out integerId))
{
   // you have a valid integer ID here.
   // process it
}
else
{
    // handle missing or invalid ID
}

A: You could do something like:
int i = Convert.ToInt32(ID);

or
int i;
Int32.TryParse(ID, out i);

BTW Request.QueryString["ID"] is already a string so the following is fine:
string ID = Request.QueryString["ID"];

A: Try
int ID = int.Parse(Request.QueryString["ID"]);

See How can I convert String to Int?

A: You can do like this:
string ID = Request.QueryString["ID"].ToString();

int id=int.Parse(ID);

or
int id=Convert.ToInt16(ID);

A: Always use tryparse for querystring values if you want to convert it to integer even if you never set it to string , because user can change that anytime before sending request (visible in URL).
int id = 0 ;//default value
bool success = int.TryParse(Request.QueryString["ID"],out id))
if (success) {
//write code for default value action
return;
}
//write code for other values.


text:
Q: mysql Select question I can't get on the right track with this, any help would be appreciated
I have one table
+---+----------+---------+-----------+
|id | match_id | team_id | player_id |
+---+----------+---------+-----------+
| 1 |        9 |      10 |         5 |
| 2 |        9 |      10 |         7 |
| 3 |        9 |      10 |         9 |
| 4 |        9 |      11 |        12 |
| 5 |        9 |      11 |        15 |
| 6 |        9 |      11 |        18 |
+---+----------+---------+-----------+

I want to select these with a where on the match_id and both team id's so the output will be
+---------+-------+------+---------+---------+
| MATCHID | TEAMA | TEAMB| PLAYERA | PLAYERB |
+---------+-------+------+---------+---------+
|       9 |    10 |   11 |       5 |      12 |
|       9 |    10 |   11 |       7 |      15 |
|       9 |    10 |   11 |       9 |      18 |
+---------+-------+------+---------+---------+

It's probably very simple, but i'm stuck..
thanks in advance
p.s. seemed to forgot a column on my first post, sorry

A: I think you should redesign your table though, maybe the format that you want as output should be your table design.
With your design, it's possible to have three or more teams playing against each other...

So. I gave this another try (coming from Oracle myself, I really miss ROWNUM here).
The following query should give you the result you want to have, but I'm not sure if you should really do that in pure SQL. Maybe you could just combine the teams in your client?
SELECT m1.match_id, m1.team_id, m2.team_id, m1.player_id, m2.player_id
FROM (
  SELECT match_id, team_id, player_id,
   -- get ranking
   ( SELECT 1 + count(*)
     FROM   matches m1b
     WHERE  m1b.match_id = m1a.match_id
     AND    m1b.team_id = m1a.team_id
     AND    m1b.player_id < m1a.player_id) rank
  FROM matches m1a
  WHERE m1a.team_id = (SELECT MIN(team_id) -- first team
                       FROM    matches
                       WHERE match_id = m1a.match_id)
)  m1,
(
  SELECT match_id, team_id, player_id,
   -- get ranking
   ( SELECT 1 + count(*)
     FROM   matches m2b
     WHERE  m2b.match_id = m2a.match_id
     AND    m2b.team_id = m2a.team_id
     AND    m2b.player_id < m2a.player_id) rank
  FROM matches m2a
  WHERE m2a.team_id = (SELECT MAX(team_id) -- second team
                        FROM matches
                        WHERE match_id = m2a.match_id)
)  m2
WHERE m1.match_id = m2.match_id
AND   m1.rank = m2.rank

What I do here is:

*

*Select all ROWs from the teams with lower team_id per match and give them a ranking (1 to 3 per match)

*Select all ROWs from the teams with higher team_id per match and give them a ranking (1 to 3 per match)

*Combine those two queries in one result, where the match_id and the ranking match

A: match is a reserve word in mysql. table name used here is matchs
select match_id, sum(if(id=1, team_id,0))team_A, sum(if(id=2,team_id,0)) team_b
from matchs
group by match_id;
+----------+--------+--------+
| match_id | team_A | team_b |
+----------+--------+--------+
|        5 |      9 |     10 |
+----------+--------+--------+
1 row in set (0.00 sec)

A: I'm not sure if the previous answers will give you what you're looking for, at least I took your question to mean something else - perhaps you could clarify the purpose of the table and the query. If the table associates teams with matches and you want a query to show you all the teams associated with one match, then your query should be
select team_id as teams from table where match_id = id_here

which would give you back (for id_here being 5)
teams
-----
9
10

A: Take a look at the url below, It is exactly what you want but is in t-sql. It can merge any number of rows.

*

*Converting fields into columns


text:
Q: Pandas `try df.loc[x]` vs `x in df.index` I have a dataframe with one column. I would like to write a function that returns the column value for a given key value; or a different (constant) value if the key is not in the index. I can think of (at least) two reasonable ways to implement this -- aside from speed is there a reason one would be better than the other?
And w/r/t speed, with len(df) = 10k and len(ids_to_check) = 20k, the try/except is about 2x slower. This is surprising to me since the other method has to traverse the index twice. Any intuitive explanation for this behavior?

*

*Using a try/except block
def attempt_1(id_val,df):
    try:
        return df.loc[id_val]
    except KeyError:
        return constant_val

%timeit [attempt_1(i,df) for i in ids_to_check]

1 loops, best of 3: 480 ms per loop

*Using in to test if id_val is in the index
def attempt_2(id_val,df):
    if id_val in df.index:
        return df.loc[id_val]
    else:
        return constant_val

%timeit [attempt_2(i,df) for i in ids_to_check]

1 loops, best of 3: 235 ms per loop

A: Create a test frame
In [22]: df = DataFrame(dict(A = np.random.randn(10000)))

Select some ids
In [21]: ids_to_check = np.random.choice(np.arange(0,20000),size=10000,replace=False)

Your methods
In [18]: %timeit [attempt_2(i,df) for i in ids_to_check]
1 loops, best of 3: 409 ms per loop

In [16]: %timeit [attempt_1(i,df) for i in ids_to_check]
1 loops, best of 3: 620 ms per loop

An efficient method, using vectorized lookups. isin returns a boolean array if the location values are in the index; indexing off of this is pretty fast.
Then I reindex to recover the original index and fill with the value for the missing entries
In [19]: %timeit df.A.loc[df.index.isin(ids_to_check)].reindex(df.index).fillna(-100)
100 loops, best of 3: 6.74 ms per loop

This returns a Series; easily could have returned the DataFrame
In [20]: df.A.loc[df.index.isin(np.random.choice(np.arange(0,20000),size=10000,replace=False))].reindex(df.index).fillna(-100)
Out[20]:
0    -100.000000
1      -0.485421
2      -0.397338
3    -100.000000
4       0.573031
5    -100.000000
6       0.359699
7       0.298462
8    -100.000000
9      -1.274819
10   -100.000000
11      0.112869
12   -100.000000
13     -2.251186
14     -0.846211
...
9985   -100.000000
9986     -0.988055
9987     -0.080460
9988   -100.000000
9989      1.007490
9990     -1.454466
9991      0.875455
9992   -100.000000
9993   -100.000000
9994      0.194506
9995   -100.000000
9996   -100.000000
9997   -100.000000
9998     -0.477828
9999     -0.777487
Name: A, Length: 10000, dtype: float64

So the answer is always use vectorized methods, never loop.


text:
Q: Having an 'SyntaxError: Unexpected token 'export' Issue with my Electron-Ionic Application //Having this issue and I don't know how to solve it:
Uncaught C:\Users\Zac\ionic_projects\robot-backup-4\node_modules\@ionic\core\components\index.js:4
export { setAssetPath, setPlatformOptions } from '@stencil/core/internal/client';
^^^^^^

SyntaxError: Unexpected token 'export'
    at new Script (vm.js:101:7)
    at createScript (vm.js:262:10)
    at Object.runInThisContext (vm.js:310:10)
    at wrapSafe (internal/modules/cjs/loader.js:979:15)
    at Module._compile (internal/modules/cjs/loader.js:1039:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1113:10)
    at Module.load (internal/modules/cjs/loader.js:940:32)
    at Module._load (internal/modules/cjs/loader.js:781:14)
    at Function.f._load (electron/js2c/asar_bundle.js:5:12913)
    at Function.o._load (electron/js2c/renderer_init.js:29:379)

This is currently effecting all my ionic electron projects that I make. My projects were working fine before I started having this issue.
I tried to get some information but couldn't find much on the internet. Tried looking at the stencils.config.ts file but couldn't find it. I also tried upgrading to a different version of stencils.
my epxressjs server isn't running when I run:
"npx cap open @capacitor-community/electron"

A: I figured it out, it turns out it was a module require import that wasn't supposed to be in my backend server. I'm still fairly new to javascript and react so I wasn't sure where to find it because the runtime error wasn't very clear.


text:
Q: please explain this function used to find index of highest number in a array We have not defined greatest. So how can we check against it in the if statement.
function findIndexOfGreatest(array) {
  var greatest;
  var indexOfGreatest;
  for (var i = 0; i < array.length; i++) {
    if (!greatest || array[i] > greatest) {
      greatest = array[i];
      indexOfGreatest = i;
    }
  }
  return indexOfGreatest;
}

A: With !greatest you check if greatest has a not falsy value. It´s not the best way to check for undefined nor null, because 0 will give you also a true (!(0 == true)) - and some other values too.
A cleaner way would be to set greatest initial to the smallest number - 1 you expect, or check against undefined:
 if (typeof greatest === 'undefined' || array[i] > greatest)

It also would be better to set indexOfGreatest to -1 for no index found, like other
indexOf functions does.
As reference see String.indexOf:

This method returns -1 if the value to search for never occurs.

A: function findIndexOfGreatest(array) {

  //storage for the current highest value in the array
  var greatest;
  //storage for the index of the highest value in the array
  var indexOfGreatest;

  //iterate over the array
  for (var i = 0; i < array.length; i++) {
    //if no greates value yet, or current element is greater then current greatest
    if (!greatest || array[i] > greatest) {
      //store index and value of current element
      greatest = array[i];
      indexOfGreatest = i;
    }
  }
  return indexOfGreatest;
}

Like also @take noted: !greatest will screw up this algorithm if the array contains values like [-1, 0, -3, -5, -7] because in the second iteration greatest will be set to 0 and !0 will evaluate to true in the third iteration, thus setting the greatest = -3 and indexOfGreatest = 2 which is obviously wrong.
Shorter and safer version:
function findIndexOfGreatest(array) {
   //if array is empty return -1 as indicating invalid index
   if (!array.length) return -1;

   //index of the greates element is assumed to be first element
   let index = 0;
   //iterate from the second element in the array to the end
   for (let i = 1; i < array.length; i++)
       //check if the current element is greater then the element at the stored index. If yes, update index to point to the current element
       if (array[i] > array[index]) index = i;
   return index;
}

A: @Hamid, first have a look at the following JS statements executed on Node REPL.
> var greatest;
undefined
>
> !greatest
true
>
> // Let's assign some value to greatest
undefined
>
> greatest = 4
4
> !greatest
false
>
> // Understanding the work of || operator
undefined
>
> 1 || 2
1
>
> 11 || 2
11
>
> 0 || 2
2
>
> true || 88
true
>
> false || 88
88
>
> var a
undefined
>
> a || 10
10
>
> !a || 10
true
>

You can check this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators to know more about the working of || operator.

So in the statement !greatest || array[i] > greatest, !greatest will be evaluated as !undefined which is true and its only for first iteration.
For latter iterations, !greatest will be evaluated as false and the code inside if block only gets evaluated if array[i] > greatest is true.

expr1 || expr2, returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true.

You can also try the below code.

I have used reduce() method defined on array to get the maximum element.
After this it is very easy to find the index of item using indexOf() method defined on array.

function findIndexOfGreatest(array) {
   var greatest;
   var indexOfGreatest

   greatest = array.reduce((num1, num2) => {
  if(num1 > num2) {
   return num1
  } else {
   return num2
  }
   })

   indexOfGreatest = array.indexOf(greatest);
   return indexOfGreatest
}

// TEST
var array = [0, -1, 3, 6, 7, 4, 2, 8, 22, 11, -4, 7, 5, 3, 9]
var indexOfGreatest = findIndexOfGreatest(array)

console.log(indexOfGreatest) // 8 (index of 22 in array)


text:
Q: Help center page on closed questions still incorrectly indicates that feedback on closure is private, when as of recently, it's no longer so The /help/closed-questions page on every site says:

If your question is closed, you will receive private feedback on the reason why it was closed.

However, following this change to the close notices, this feedback is now shown to everyone, so as to allow for other users without the close voting privilege to edit the question to make it suitable. The part of the notice claiming it as "private feedback" has also been removed.
The word "private" in the help center page's sentence needs to be removed. It should just say "you will receive feedback" since it's not private anymore.


text:
Q: Sequential compactness implies compactness I'm currently trying to prove that if $X$ is a metric space and $X$ is sequentially compact, then $X$ itself is compact. My current strategy is to proceed by contraposition. We assume $X$ is not compact. Then it has an open cover $\mathcal{O}$ for which no finite subcover contains all of $X$. Next, I think it would be easier to proceed by contradiction: we assume that a sequence $\{x_n\}$ has a subsequence $\{x_{n_k}\}$ that converges to a point $L$. We know that since $\mathcal{O}$ covers $X$, there is some open set $O\in \mathcal{O}$ such that $L\in O$. Then there is some $N\in\mathbb{N}$ such that for all $k\geq N$, $x_{n_k}\in O$. I'm not sure how to proceed from here. I'm expecting to be able to derive that the open cover $\mathcal{O}$ has a finite subcover, contradicting our assumption that $X$ is not compact.
Any advice will be helpful. Thanks!

A: A few notes to make: Firstly if you are proceeding by contradiction you need to assume that every sequence $\{x_n\}$ has a convergent subsequence, not just one (the negation of not sequentially compact is compact).
Secondly, you haven't used the fact that $X$ is a metric space, which is crucial here, so to proceed you'd definitely need to use some property only possessed by metrisable spaces.
It is not a trivial fact that sequentially compact metric spaces are compact, and I think you will struggle to proceed without some lemmas. I recommend looking at Lebesgue's Number Lemma or the fact that $X$ has the Lindelof property, as well as the fact that sequentially compact spaces are totally bounded and that sequentially compact metric spaces satisfy the finite intersection property for closed sets.


text:
Q: ADFv2 SSIS-IR and DB2 Driver IBM DB2 ODBC DRIVER - DB2COPY1. SSIS package Unexpected Termination in prevalidate Using ADFv2 SSIS-IR and DB2 Driver IBM DB2 ODBC DRIVER - DB2COPY1. Have defined the TCPIP Nodes and database using db2cmd DB2 CATALOG commands. Defined 32-bit and 64-bit SystemDSNs. The st.err and st.out from the SSIS-IR provisioning show all commands were successful and echos all the CATALOG and ODBC DSNs as expected.
Everything look good but SSIS packages fail with "Unexpected Termination" in Prevalidate when specifying the configured SystemDSNs. There is not a single message in SSISDB to review.  The package is simple - one data flow task with an ODBC data source specifying the SystemDSN and a simple Rowcount task just to test the connection.
I have created a second SSIS package that dumps the event logs for the node and I see this message
    2018-05-11 16:32:05.0000000|The description for Event ID '1073819648' in
Source 'SQLISPackage140' cannot be found.
The local computer may not have the necessary registry information or message DLL files to display the message,
or you may not have permission to access them.
The following information is part of the event:'ReadApplicationEventLogtoBlob|SQLISPackage140|Information

Anyone have any clues on this I am a bit stumped right now
Thanks in advance

A: I have created another ssis package that simply uses c# script task to try to connect to the DSN.  And am receiving a more useful message.
Script Task Error: ERROR[08001][IBM][CLI Driver] SQL1336N The remote host "namehere" was not found. SQLSTATE=08001
I am looking into the connectivity to the namehere database as configured and working to identify why I connect find the server. Thank you everyone who took a look.