text:
Q: leaked window again 06-25 15:03:02.596: E/WindowManager(29217):     at com.android.grad.PreviewActivity$1.onClick(PreviewActivity.java:36)
    06-25 15:03:02.596: E/WindowManager(29217):     at android.view.View.performClick(View.java:3527)
    06-25 15:03:02.596: E/WindowManager(29217):     at android.view.View$PerformClick.run(View.java:14234)
    06-25 15:03:02.596: E/WindowManager(29217):     at android.os.Handler.handleCallback(Handler.java:605)
    06-25 15:03:02.596: E/WindowManager(29217):     at android.os.Handler.dispatchMessage(Handler.java:92)
    06-25 15:03:02.596: E/WindowManager(29217):     at android.os.Looper.loop(Looper.java:137)
    06-25 15:03:02.596: E/WindowManager(29217):     at android.app.ActivityThread.main(ActivityThread.java:4441)
    06-25 15:03:02.596: E/WindowManager(29217):     at java.lang.reflect.Method.invokeNative(Native Method)
    06-25 15:03:02.596: E/WindowManager(29217):     at java.lang.reflect.Method.invoke(Method.java:511)
    06-25 15:03:02.596: E/WindowManager(29217):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    06-25 15:03:02.596: E/WindowManager(29217):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    06-25 15:03:02.596: E/WindowManager(29217):     at dalvik.system.NativeStart.main(Native Method)
    06-25 15:03:04.186: I/Process(29217): Sending signal. PID: 29217 SIG: 9
    06-25 15:03:04.566: D/TextLayoutCache(29339): Using debug level: 0 - Debug Enabled: 0
    06-25 15:03:04.606: D/libEGL(29339): loaded /system/lib/egl/libGLES_android.so
    06-25 15:03:04.606: D/libEGL(29339): loaded /system/lib/egl/libEGL_adreno200.so
    06-25 15:03:04.636: D/libEGL(29339): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
    06-25 15:03:04.636: D/dalvikvm(29339): GC_CONCURRENT freed 117K, 3% free 9125K/9351K, paused 4ms+17ms
    06-25 15:03:04.636: D/libEGL(29339): loaded /system/lib/egl/libGLESv2_adreno200.so
    06-25 15:03:04.706: D/OpenGLRenderer(29339): Enabling debug mode 0
    06-25 15:03:07.326: D/OpenGLRenderer(29339): Flushing caches (mode 0)
    06-25 15:03:07.326: W/IInputConnectionWrapper(29339): showStatusIcon on inactive InputConnection
    06-25 15:03:07.366: D/OpenGLRenderer(29339): Flushing caches (mode 1)

I know that this error asked before and i saw the solutions for that but the solutions don't work with me. and this is my code.
The error appear on pd.show().
@Override
protected void onPreExecute() {
    //network.loadData();
    file = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            "MyCameraApp" + File.separator + "project");
    createProgressDialog();
    pd.show();
}

@Override
protected Boolean doInBackground(String... params) {
    try {
        crop = new Crop(params[0]);
        crop.cropID();
        croppedID = crop.getId();
        publishProgress(2);
    } catch (IOException e) {
    }

    segmentNumbers();
    return true;
}

@Override
protected void onProgressUpdate(Integer... values) {
    pd.incrementProgressBy(values[0]);
}

@Override
protected void onPostExecute(Boolean result) {
    pd.dismiss();
    Toast.makeText(activity, "Processing Done", Toast.LENGTH_LONG).show();
}

private void createProgressDialog() {
    pd = new ProgressDialog(activity);
    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    pd.setTitle("Extract ID");
    pd.setMessage("Processing...");
    pd.setIcon(R.drawable.ic_launcher);
    pd.setProgress(0);
    pd.setCancelable(false);
}

onpreExecution method :-
          i am showing my dialog.
doInBackGround method :-
          I execute my segmentNumber() which used to segement picture.
onPostExecution method :-
          I am dismissing my dialog.
Modified code :
package com.OCR.ID;

import java.io.File;
import java.io.IOException;

import org.neuroph.contrib.imgrec.image.Image;
import org.neuroph.contrib.imgrec.image.ImageFactory;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.Camera.R;

    /**
     * @author Mahmud
     *
 */
public class Segement extends AsyncTask<String, Integer, Boolean> {

    int[][] croppedID;
    Crop crop;
    private Activity activity;
    private ProgressDialog pd;
    File file;
    private String ID;
    private Neuroph network;

    public Segement(Activity activity, ProgressDialog pd) throws IOException {
        this.activity = activity;
        this.pd = pd;
        //network = new Neuroph(this.activity);
    }

    @Override
    protected void onPreExecute() {
        //network.loadData();
        file = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "MyCameraApp" + File.separator + "project");
    }

    @Override
    protected Boolean doInBackground(String... params) {
        try {
            crop = new Crop(params[0]);
            crop.cropID();
            croppedID = crop.getId();
            publishProgress(2);
        } catch (IOException e) {
        }

        segmentNumbers();
        return true;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        pd.incrementProgressBy(values[0]);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        pd.dismiss();
        Toast.makeText(activity, "Processing Done & your ID : " + ID,
                Toast.LENGTH_LONG + Toast.LENGTH_LONG).show();
    }

    /**
     * Segment cropped image into number
     */
    public void segmentNumbers() {
        int count = 0, endOfNumber = 0, startOfNumber = 0;
        int[][] number = null;

        while (crop.getxProjection()[endOfNumber] == 0
                && endOfNumber != crop.getxProjection().length - 1)
            endOfNumber++;

        while (endOfNumber != croppedID.length - 1) {
            endOfNumber = startOfNumber;

            while (crop.getxProjection()[endOfNumber] != 0
                    && endOfNumber != crop.getxProjection().length - 1)
                endOfNumber++;

            if (endOfNumber - startOfNumber < 10) {
                startOfNumber = endOfNumber;
                while (crop.getxProjection()[startOfNumber] == 0
                        && endOfNumber != crop.getxProjection().length - 1)
                    startOfNumber++;
                continue;
            }

            if (startOfNumber >= croppedID.length
                    || endOfNumber >= croppedID.length)
                break;

            number = new int[endOfNumber - startOfNumber - 1][croppedID[0].length];

            for (int i = 0; i < number.length; i++)
                for (int j = 0; j < number[i].length; j++)
                    number[i][j] = croppedID[i + startOfNumber][j];

            number = verticalProjectionForNumber(number);

            File numberFile = AndroidImage.save(activity,
                    AndroidImage.write2DIntoImage(number),
                    Integer.toString(count));
//          Image image = ImageFactory.getImage(numberFile.getAbsoluteFile());
//          ID += network.recognize(image);

            //
            // file.getPath() + File.separator + Integer.toString(count) +
            // ".PNG");
            publishProgress(7);

            startOfNumber = endOfNumber;
            while (crop.getxProjection()[startOfNumber] == 0
                    && endOfNumber != crop.getxProjection().length - 1)
                startOfNumber++;

            count++;
        }

        Log.d("ID", ID);
    }

    /**
     * Do vertical projection on each number
     */
    private int[][] verticalProjectionForNumber(int[][] number) {

        int[] projection = new int[number[0].length];

        for (int i = 0; i < (number[0].length * 0.90); i++) {
            for (int j = 0; j < number.length; j++) {
                projection[i] += number[j][i];
            }
        }

        int first = 0;
        while (projection[first] == 0)
            first++;

        int last = projection.length - 1;
        while (projection[last] == 0)
            last--;

        int[][] modifiedNumber = new int[number.length][last - first];
        for (int i = 0; i < modifiedNumber.length; i++)
            for (int j = 0; j < modifiedNumber[i].length; j++)
                modifiedNumber[i][j] = number[i][j + first];

        number = null;
        projection = null;
        System.gc();

        return modifiedNumber;
    }
}

And i called the task from here :-
OnClickListener processOnClickListener = new OnClickListener() {
        public void onClick(View v) {
            try {
                createProgressDialog();
                pd.show();
                new Segement(PreviewActivity.this, pd).execute(path);
            } catch (IOException e) {
            }
        }
    };

A: Hawaii's answer above is correct.
To be more specific, the doInBackground method is not synchronized with the UI thread. Thus, you should never update your views/layouts/anything UI-related in this method. I suggest you show() your dialog before the AsyncTask's execution.

A: You should show() your Dialog before you execute a task.
In AsyncTask you can use only OnProgressUpdate and onPostExecute methods for update your UI.
createProgressDialog();
pd.show();
task.execute();

And change your method to
private void createProgressDialog() {
    pd = new ProgressDialog(YourMainActivity.this);
    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    pd.setTitle("Extract ID");
    pd.setMessage("Processing...");
    pd.setIcon(R.drawable.ic_launcher);
    pd.setProgress(0);
    pd.setCancelable(false);
}


text:
Q: Pdf.js: rendering a pdf file in code-behind Using this part I can easily render any file :
LinkButton lb = sender as LinkButton;
string script = String.Format("Sys.Application.add_load(function() {{
openWindow($get('{0}')); }});", lb.ClientID); ;
lb.ToolTip = "pdf.js/web/viewer.html?file=kit.pdf";
ScriptManager.RegisterStartupScript(this, this.GetType(), "openPdfFile",
script, true);

I am getting base64 from database and can convert it further to byte[] or anything else. But how can I pass it to 'pdf.js/web/viewer.html?file=' string without any JavaScript converts like uint8array, atob etc.(And without saving)

redpajama_set_name: RedPajamaStackExchange


text:
Q: rendering list of objects in react/mobx i have a list of objects in my jsx class. Let's assume it's a fixed list of objects for now
versions = [
{owner: "luca", date: "today", fw: "00"},
{owner: "thomas", date: "tomorrow", fw: "00"},
{owner: "peter", date: "yesterday", fW: "00"},];

i'm trying to render the values of these objects in nested div elements on my webpage. basically it's a panel of rows that i represent as divs. here's the html for it

Version history

                                            **{version.date}**

                                                Created by **{version.owner}**
                                                **{version.fw}**

i'm not sure how to implement this in my component class!!
starting from the first div after this one

my html code to create each row in the panel starts.
I want to iterate over the objects in my list and create/fill each row in my panel with the right data from that list
I've tried a dozen different ways but nothing is showing up on my webpage. I just don't understand how to iterate over the list of objects in 'versions' and create/fill the panel in progress.

A: Iteration is normally done by maping an array of values to an array of components. Something like this:
versions = [ ... ]

return (

Version History

    {
      versions.map(version =>

          {version.date}

      )
    }

)

Note that for Reacts reconciliation to work properly when potentially re-rendering with a new array of values, the outer element in the array should have a unique key attribute so that React quickly can recognize any removed or added values in the array on the next render.

A: Let assume you have array of objects declared inside render using const. You can iterate the array either using .map, .forEach, for loop etc. In your case I would prefer .map for iteration because map returns new array. So inside the map construct jsx elements and return them.
Now, returned jsx elements will be placed in versionItems array. You can just call that with {} like expression in render return.
render(){
     const versions = [
       {owner: "luca", date: "today", fw: "00"},
       {owner: "thomas", date: "tomorrow", fw: "00"},
       {owner: "peter", date: "yesterday", fW: "00"},];

     const versionItems = versions.map((item, index) => {
      return (

              //just get all your property values here using item.owner, item.date etc

     )
 });
    return(

             {versionItems}

    )
}


text:
Q: How you add the greyed out parameter hints (msg, context) for methods in Android Studio for Kotlin? On the image underlined is written grayed out the "msg" word. Had looked around but can't tell how you make it appear like that.
Can't copy paste the code because that word is not being copied.

A: See Jetbrains' help article on inline parameter name hints, it covers both the reasoning behind the feature as well as configuration options.


text:
Q: Drawing 3D points in Matlab and connect them in order via line I have an array that contains 3D float points. Not only I want to depict them in a figure but also I want to connect them with lines.
Example) lets say we have array called X:
X=[0, 0, 0; 0.48, -0.88, 0.09; -1.06, 0.55, 0.9; -0.65, 1.5, -1.44; 1.1, 0.59,
-1.11;0.76, 0.86, -0.52; -1.08, -0.28, 0.55; 1.47, -1.21, 0.14; 1.42, -2.15, 0.71; -0.64,
1.87, 2.4;2.32, -2.44, 2.02; 2.25, -2.56, -3.03; 2.35, 2.65, -1.5; 0.23, -2.25, 2.78; 2.47,
-3.12,  -1.91; 2.27, 1.37, -3.05; 2.3, 1.9, -1.29; -1.77, -0.51, 2.33];

    X1= [0,0,0]
    X2=[0.48, -0.88, 0.09]
    X3=[-1.06, 0.55, 0.9] ...

now I want that X1...Xn to be drawn in figure as points then X1 get connected to X2, X2 get connected to X3, X3 get connected to X4, etc
how could I do that?
Here is what I ve done but I get a wrong figure:
figure;hold on;
    P=[];
    for i=1:size(X,1)
    x=X(i,1);
    y=X(i,2);
    z=X(i,3);
    A=[ x,y,z];
    P=vertcat(P,A);
    plot(P);
    end

And Here is the output:

A: Check out the plot3 documentation.
In particular, plot3(X, Y, Z) will plot the points and join them with a line.
In your case:
plot3(X(:, 1), X(:, 2), X(:, 3))


text:
Q: insert values of check buttons to database i have a problem in my application i want to  insert the values of check buttons but it doesn't work, i had the same difficulty in radio button but you have helped me to solve it, i tried to make the same with check buttons but it didn't go as expected the error comes from the method public void onClick(View view) :
public class MainActivity extends Activity  {
DBAdapter db = new DBAdapter(this);
CheckBox ct1,ct2,ct3,ct4;
   public void  ajouter(View v) {
       db.insertcc(x,y,z,a,b,c);
       Toast.makeText(getApplicationContext(), "Données enregistrées!!! =)", Toast.LENGTH_LONG).show();
    }

  int x;
  int y;
  int z;
  int a;
  int b;
  int c;

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

    db.open();

    ct1 = (CheckBox)findViewById(R.id.rm_41_1_1);
    ct2 = (CheckBox)findViewById(R.id.rm_41_1_2);
    ct3 = (CheckBox)findViewById(R.id.rm_41_1_3);
}
        public void onClick(View view) {
        boolean checked = ((CheckBox) view).isChecked();

        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.rm_41_1_1:
                if (checked)
                      x=10;
                      Toast.makeText(getApplicationContext(), "Données enregistrées!!! =)", Toast.LENGTH_LONG).show();
                    break;
            case R.id.rm_41_1_2:
                if (checked)
                    y=11;
                      Toast.makeText(getApplicationContext(), "Données enregistrées!!! =)", Toast.LENGTH_LONG).show();
                    break;
            case R.id.rm_41_1_3:
                if (checked)
                    z=33;
                break;
        }
            Button bton = (Button)findViewById(R.id.ajout_un);
        bton.setOnClickListener(new View.OnClickListener() {
        @Override
             public void onClick(View v) {
                ajouter(v);
                Toast.makeText(getApplicationContext(), "Données enregistrées!!! =)", Toast.LENGTH_LONG).show();
        }
          });

}

A: after this line
public void onClick(View view) {
        boolean checked = ((CheckBox) view).isChecked();

its mean all clickable views inside layout must be Checkbox to prevent this error add this code
    boolean checked = false;

//Check if View is CheckBox if not will cancel request
    if (view instanceof CheckBox)
    {
       if (((CheckBox) view).isChecked()) {
               checked = true;
       }
    }else
    {
    return;
    }


text:
Q: What is the C# DateTimeOffset equivalent in Go I have the following code which takes a string as input which is converted into UNIX time stamp. I want to do the same in golang but I am not able to recognize the struct or function which will give an equivalent of DateTimeOffset structure in Go.
class Program
{
    static void Main(string[] args)
    {
        var date = GetUtcTimestampFromAttribute();
        Console.WriteLine(date);
        if (date != null)
        {
            Console.WriteLine(ToUnixTimeStamp(date.Value));
        }

        Console.ReadKey();
    }

    public static DateTimeOffset? GetUtcTimestampFromAttribute()
    {
        var ticks = long.Parse("7036640000000");
        Console.WriteLine(ticks);
        return GetUtcTimestampFromTicks(ticks);
    }

    public static DateTimeOffset? GetUtcTimestampFromTicks(long ticks)
    {
        Console.WriteLine(new DateTimeOffset(ticks, TimeSpan.Zero));
        return ticks != 0 ?
            new DateTimeOffset(ticks, TimeSpan.Zero) :
            (DateTimeOffset?)null;
    }

    public static long ToUnixTimeStamp(DateTimeOffset timeStamp)
    {
        var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
        return Convert.ToInt64((timeStamp - epoch).TotalSeconds);
    }
}

For example:
Input: 635804753769100000
Output: 1444878577
Corresponding Time in UTC : 10/15/2015 3:09:36 AM +00:00
Can someone please help me on a workaround to get the above result.
Thanks

A: I believe the time package has everything you need and it is IMO the best time library I've worked with in any language. Example:
package main

import(
    "fmt"
    "time"
)

func main(){

    // this is how you parse a unix timestamp
    t := time.Unix(1444902545, 0)

    // get the UTC time
    fmt.Println("The time converted to UTC:", t.UTC())

    // convert it to any zone: FixedZone can take a utc offset and zone name
    fmt.Println(t.In(time.FixedZone("IST", 7200)))

}

EDIT Converting the time object back to a unix timestamp is simple:
t.Unix()

or
t.UnixNano()

A: For example,
package main

import (
    "fmt"
    "time"
)

func TimeFromTicks(ticks int64) time.Time {
    base := time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix()
    return time.Unix(ticks/10000000+base, ticks%10000000).UTC()
}

func main() {
    fmt.Println(TimeFromTicks(635804753769100000))
}

Output:
2015-10-15 03:09:36.0091 +0000 UTC


text:
Q: In bash what does if [ "$VAR" ] mean I understand how the if function works in bash, but the problem is that I don't get what it means if you aren't comparing it with something. I know there are a bunch of switches like -e or -c or -f, but when would the following code get evaluated as true?
if [ "$VAR" ]; then
  echo "TRUE"
else
  echo "FALSE"
fi

I'm trying to interpret a script someone wrote for me.

A: From help test:
     STRING      True if string is not empty.

A: I think it's the following:
-n STRING
       the length of STRING is nonzero
STRING equivalent to -n STRING

Just the test for non-empty value.


text:
Q: Regex Multiple Expressions Getting Duplicates C# I am using a string list in c#, which contains a list of subjects.
E.g art, science, music.
I then have the user input "I would like to study science and art."
I would like to store the results into a variable, but I get lots of duplicates like "science, sciencemusic" (that's not a typo).
I think it's from the looping of the for each statement. Could there be an easier way to do this or is there something wrong in my code? I can't figure it out.
Here's my code:
string input = "I would like to study science and art.";
string result = "";

foreach (string sub in SubjectsClass.SubjectsList)
{
    Regex rx = new Regex(sub, RegexOptions.IgnoreCase);

    MatchCollection matches = rx.Matches(input);

    foreach (Match match in matches)
    {
        result += match.Value;
    }
}

The subjects class function "SubjectsList" is read from a CSV file with only words in it of random subjects:
CSV File:
Computing
English
Maths
Art
Science
Engineering
private list<string> subjects = new list<string>();

//Read data from csv file to list...

public list<string>SubjectsList
{
   get { return subjects; }
{

Currently the output I get is this:
"input": "art science",
"Subject": "artscienceartscienceartscience"

If I change:
result += match.Value;

to
result += match.Value + " ";

I get lots of spaces.
edit: I should mention that this code runs on a WPF c# button press and then shows the result.

A: Using your code, and with the following test data:
List<string> subjects = new List<string>{"Science", "Art", "Maths"};
string input = "I would like to study science and art.";

I don't get duplicates.
To avoid blank matches, perform a check on the value being empty
foreach (Match match in matches)
{
       if (!string.IsNullOrEmpty(match.Value))
       {
            result += match.Value + " ";
       }
}


text:
Q: Calling PL-SQL Procedure over database link from Java here my objective is to call a procedure over a database link in java. procedure takes one input and has got cursor as an output.
to check if my code is working properly, I created dummy procedure in my database and tried executing. it is working, able to get cursor and play with it.
however when i am calling some procedure over database link, getting error as
java.sql.SQLException: ORA-06550: line 1, column 7:
PLS-00201: identifier 'HR_CLICK_GET_EMP_DETAILS@IBSLUAT1.WORLD' must be declared

I had a call with developer who had created these procedure. according to him procedures exist at this end and access is already given to my user.
Now my questions and queries are

*

*is there something different, i have to do while calling a procedure over database link(code is below)

*what are the things i should be asking to sql developer. by the way database link is right.
           String prc_name = "HR_CLICK_GET_CM_AND_ABOVE@IBSLUAT1.WORLD(?,?)";
             String runSP = "{ call  "+prc_name+" }";

            String runSP1 = "{ call  get_user_by_userId(?,?) }"; this one is working

               try
             {

                 Class.forName("oracle.jdbc.driver.OracleDriver");
             Connection conn = DriverManager.getConnection(

                     "jdbc:oracle:thin:@xx.xx.xxx.xx:port:SERVICE", "username", "password");  // uat

             CallableStatement cs = conn.prepareCall(runSP);

             cs.setString(1, "705151");
             cs.registerOutParameter(2, OracleTypes.CURSOR);
             cs.execute();

             // get refcursor and convert it to ResultSet
             ResultSet resultSet = (ResultSet) cs.getObject(2);
             ResultSetMetaData rsmd = resultSet.getMetaData();
             int columnCount = rsmd.getColumnCount();

             System.out.println("Total Columns in ResultSet : "+columnCount);

             System.out.println("Now Analyzing column one by one:\n\n-----------------------------------------------");

             for (int i = 1; i <= columnCount; i++ ) {
                  String name = rsmd.getColumnName(i);
                 System.out.println("Column No:"+i+">>>>>>>>"+name);
                 }

             }
             catch(SQLException s)
             {
                 s.printStackTrace();
             }
             catch(ClassNotFoundException s)
             {
                 s.printStackTrace();
             }

thanks in advance
Ashish

A: Try to use the Oracle user's name who owns the procedure as a prefix:
username.HR_CLICK_GET_EMP_DETAILS@IBSLUAT1.WORLD

A: Answer is "synonym".
SQL Developer has created a synonym for HR_CLICK_GET_EMP_DETAILS as HR_CLICK_GET_EMP_DETAILS@IBSLUAT1.WORLD
that is what he informed me, I could not quite wrap my head around that but able to hit the procedure.
but now ,  able to get get the metadata of a result set but unable to traverse rows.
I'm getting an error:

java.sql.SQLException: ORA-24338: statement handle not executed
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:743)
at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:207)
at oracle.jdbc.driver.T4CStatement.fetch(T4CStatement.java:1018)
at oracle.jdbc.driver.OracleResultSetImpl.close_or_fetch_from_next(OracleResultSetImpl.java:291)
at  oracle.jdbc.driver.OracleResultSetImpl.next(OracleResultSetImpl.java:213)
at ashishtest.StoredProcedureCursor.main(StoredProcedureCursor.java:80)

I guess, new forum is required for this error.
also I am not marking this as solved as not sure how solution works.


text:
Q: C# Regex with words including asterisks I'm trying to split the following string: "'aaa bbb' 0.05 ccc 3* 20*0.1"
so that the elements are:
0: aaa bbb
1: 0.05
2: ccc
3: 3*
4: 20*0.1

I then want to loop over each of the results.  The following snippet handles the first 3 elements, but not the last two:
Regex
    .Matches(input, @"(?<match>[-+]?[0-9]*\.?[0-9]+)|(?<match>\w+)|'(?<match>[\w\s]*)'")
    .Cast<Match>()
    .Select(m => m.Groups["match"].Value)
    .ToList()
    .ForEach(z => etc...

What should I add to the regex so that 3* and 20*0.01 are returned as single matches?

A: This regular expression matches the expressions the way you wanted:
foreach (var s in Regex.Matches("'aaa bbb' 0.05 ccc 3* 20*0.1", @"('[^']*'|\S+)")) {
    Console.WriteLine(s);
}

produces this output:
'aaa bbb'
0.05
ccc
3*
20*0.1

All you need to do is detecting if a value has single quotes around it, and unquote if necessary.

A: The following will match all 5:
@"(?<match>[-+]?\d*\*(\d+\.?\d*)?)|(?<match>[-+]?\d+\.?\d*)|(?<match>\w+)|'(?<match>[\w\s]*)'")


text:
Q: Why is this code not downloading the data in real time? I have a problem which I don't know how to solve (I'm a beginner in coding). This program is supposed to scrape stock price data from yahoo finance:
import bs4
from bs4 import BeautifulSoup
import requests
import pandas as pd
import datetime as dt

def real_time_price(stock_code):
   url = 'https://finance.yahoo.com/quote/' + stock_code + '/'
   r = requests.get(url)

   web_content = BeautifulSoup(r.text, 'lxml')
   web_content = web_content.find('div', {'class':'My(6px) Pos(r) smartphone_Mt(6px)'})
   web_content = web_content.find('span').text

   if web_content==[]:
       web_content = '999999'

   return web_content

LA = ['AAPL', 'FB', 'F', 'AMZN', 'GOOG']

for step in range(1,101):
    price = []
    col = []#Lista, która dodaje dane do df
    time_stamp = dt.datetime.now()
    time_stamp = time_stamp.strftime('%Y-%m-%d %H:%M:%S')
    for stock_code in LA:
        price.append(real_time_price(stock_code))
    col = [time_stamp]
    col.extend(price)
    df = pd.DataFrame(col)
    df = df.T
    df.to_csv('realtimestockdata.csv', mode = 'a', header = False)
    print(col)

But it seems that it does not update when it's running is there some syntactic error in that that I missed?
All responses are really appriciated, thank you.


text:
Q: No VNC extension on display on VNC desktop I have started vncserver or remote instance with the vncserver command, and now am able to connect to it with VNC client.
Unfortunately, I can't start vncconfig due to error
No VNC extension on display

Everything is happening on VNC. How can it be?

A: 1) Make a copy of vncserver
sudo cp /usr/bin/vncserver /usr/bin/vncserver.bkp

2) Open vncserver and find $defaultXStartup
sudo vi /usr/bin/vncserver

3) Modify lines to:
$defaultXStartup
    = ("#!/bin/sh\n\n".
       "# Uncomment the following two lines for normal desktop:\n".
       "# unset SESSION_MANAGER\n".
       "# exec /etc/X11/xinit/xinitrc\n\n".
       "[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup\n".
       "[ -r \$HOME/.Xresources ] && xrdb \$HOME/.Xresources\n".
       "xsetroot -solid grey\n".
       "vncconfig -iconic &\n".
       "x-terminal-emulator -geometry 80x24+10+10 -ls -title \"\$VNCDESKTOP Desktop\" &\n".
       "x-window-manager &\n");

This will ensure that you have all the right things started inside VNC.
In case you face issues, please follow the below link and ensure you have all the stuff is rightly installed.
See Installation of VNC server on Ubuntu.


text:
Q: Second page of RSS feed I have a my default feed url https://tocanerd.com.br/feed/, but i set it up to show a x number of posts. I'd like to know how to see the other posts in a second page or something like this.

A: You can request different pages of an RSS feed by setting the paged parameter. (Important: not page, but paged with an extra d at the end!)

http://www.example.com/feed/?paged=1

A WordPress theme can disable/break this behavior, though.

*

*WordPress documentation: https://codex.wordpress.org/Pagination

*Related question: Pagination of RSS2 feed

A: Feeds don't support paging. You can only set the number of items to include in the feed, but nothing more. Feed readers don't support paging, but most feed readers cache old posts from each feed (depending on the reader).


text:
Q: Unit Testing Routed Events in WPF I am creating an MVVM WPF application. In my unit tests, it seems I am being forced to register a whole piles of RoutedEventArgs to pass to my VM commands when testing. While I don't see any real problem with this so far, I imagine it would be better to leave the WPF framework out of my unit tests, a la Clean Coding. I tried mocking the event args, but the WPF framework complains about the Event Args not being registered. I am using MVVM Light as well.
Question is this: Is there any way to mock a RoutedEventArgs for use in unit testing? Can you suggest a different way to do it?

A: We follow more of a model-view-presenter format in our WPF applications, but we get what we need on the command CanExecute and Executed functions, then pass it into our testable presentation layer.  You can use a similar technique:
private void WhateverCommand_Executed(object sender, ExecutedRoutedEventArgs e) {
    DoSomething(e.Parameter);
}


text:
Q: Img/Audio Change by document.getElementByID("...").src=x+".png"; wont work I cant figure out why it is not working. Since its nothing too special I searched on the web - and here but all I found was either tutorials without the variable or questions with too specific questions.
Can anyone guide me on this?

<title>Test</title>

<audio id="audioplayer" src="1.mp3" controls autoplay loop>
Your browser does not support the audio element.
</audio>

<input type="button" id="play" value="Play 1" onclick='changeaudio(1)"' />
<input type="button" id="play2" value="Play 2" onclick='changeaudio(2)"' />
<input type="button" id="play3" value="Play 3" onclick='changeaudio(3)"' />

A: Remove the ; after your function definition: function changeaudio(x); should become:function changeaudio(x)
Also, your onclick syntax is wrong: onclick='changeaudio(1)"' should be: onclick="changeaudio(1)".
Your final code should look like this:

        <title>Test</title>

            <audio id="audioplayer" src="1.mp3" controls autoplay loop>
                Your browser does not support the audio element.
            </audio>

            <input type="button" id="play" value="Play 1" onclick="changeaudio(1)" />
            <input type="button" id="play2" value="Play 2" onclick="changeaudio(2)" />
            <input type="button" id="play3" value="Play 3" onclick="changeaudio(3)" />

jsFiddle Demo

A: for a jquery approach :
$(function(){
    $('.play').each(function() {
       var mp3 = $(this).attr("id");
        $(this).click(function(){
           $('#audioplayer').attr("src", mp3+".mp3");
           $('#image').attr("src", mp3+".png");
        });
    });

});

            <audio id="audioplayer" src="1.mp3" controls autoplay loop>
            </audio>

            <input type="button" class="play" id="1" value="Play 1" />
            <input type="button" class="play" id="2" value="Play 2"  />
            <input type="button" class="play" id="3" value="Play 3" />

jsFIDDLE DEMO


text:
Q: what should i need to use in node js stdin or stdout im writing this code to get the input from the user:
label Name:
input(in);

label LastName:
input(in);

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function(chunk){
process.stdout.write('data: ' +chunk);
});

process.stdin.on('end', function(){
process.stdout.write('end');
});

and i am keeping getting this error "Syntax Error: Unexpected token )".
and i do not understand why.
can you help me?
thank you!

A: I'm not sure about the syntax error you are receiveing, but for user input from the command-line, the prompt module from nodejitsu is fantastic.
var prompt = require('prompt');

//
// Start the prompt
//
prompt.start();

//
// Get two properties from the user: username and email
//
prompt.get(['firstname', 'lastname'], function (err, result) {
  //
  // Log the results.
  //
  console.log('Command-line input received:');
  console.log('  firstname: ' + result.firstname);
  console.log('  lastname: ' + result.lastname);
});

The prompt github page has lots of examples of more complex situations involving validation etc.


text:
Q: Как в Laravel 8 сделать поиск по псевдонимам столбцов? Не понимаю, как организовать в Laravel поиск по псевдонимам столбцов. Джойню таблицы, в которых присутствуют колонки с одинаковыми названиями. Каждой присваиваю свой псевдоним. И если в where() использую псевдонимы, то вижу ошибку. Получается, псевдонимы в select() вообще не работают?
БД:
class
id | name

student
id | name | class_id

Код:
$name = 'Иван'
$column = 'student_name' //выдаёт ошибку
//$column = 's.name'     //не выдаёт ошибку
$data = DB::connection('pgsql')->table('student AS s')
    ->leftJoin('class AS c', 'c.id', 's.class_id')
    ->select('s.name AS student_name', 'c.name AS class_title')
    ->where($column, '=', $name)
    ->get()->toArray();

Ошибка:

Undefined column: 7 ERROR: column "student_name" does not exist

Laravel 8, база Постгресс.


text:
Q: How can i test my TSQL syntax? Quick question: How do I get some kind of database to use to test my SQL syntax and create basic data.

I have Sqlite Code which I'll soon put on a server. I have SQL Server 2008 installed with visual studio 2010. I tried connecting to the database and had no luck.
I also tried using an .mdf file instead thinking it's a file and I won't have connectivity issues. Wrong, I still couldn't connect and I used this site to help me (i'm aware its 2005)
In that case I used:
var conn = new SqlConnection(@"Server=.\SQLExpress;AttachDbFilename=C:\dev\src\test\SQL_DB_VS_Test\test.mdf;Database=dbo;Trusted_Connection=Yes;");

exception
Unable to open the physical file "C:\dev\src\test\SQL_DB_VS_Test\test.mdf".
Operating system error 5: "5(Access is denied.)".
Cannot attach the file 'C:\dev\src\test\SQL_DB_VS_Test\test.mdf' as database 'dbo'.

With trusted = no I get Login failed for user ''. (What user am I suppose to set?). I created the .mdf with Visual Studio somehow.

A: What if you try this connection string:
var conn = new SqlConnection(@"Server=.\SQLExpress;
        AttachDbFilename=C:\dev\src\test\SQL_DB_VS_Test\test.mdf;
        Database=test;Integrated Security=SSPI;");

I don't think it's a good idea to call your database "dbo" (that's a SQL Server keyword - I wouldn't use it for my own purposes!), and also I believe you need to use Integrated Security=SSPI; to define Windows authentication - Trusted_Connection is not used for SQL Server connection strings, AFAIK.

A: Have you tried using SSMS to access your local instance?  It's helpful for getting connected and getting everything setup.  Also, I think the default install of Sql Express with VS only support trusted connections.

A: After creating the mdf file with visual studios right click the mdf and select properties. In it you'll see a row called Connection String. Copy/paste it into your app and it should connect. The key part is User Instance=True


text:
Q: Zooming in Quicktime Screen Capture Doesn't Show I'm trying to record a screen capture with Quicktime, but whenever I zoom in, it doesn't translate to the video taken. I've seen videos with screen zooming in them, so I know it can be done. I repeat, I can see the zooming while recording, but it doesn't show up in the video later on.
Thanks for any help.

A: Snapz Pro from Ambrosia is able to record the screen with zooming in and out. It costs $69 and can be found at: http://www.ambrosiasw.com/utilities/snapzprox/.
I tested and found this works with the most recent version 2.3.3.
Edit: Fixed punctuation.


text:
Q: The image is not changing when it collapses back (jquery, css) The image will change when it expands, but when it collapses back, it won't change, my code looks like below:
JS:
(function ($) {
    $(document).ready(function () {

        // Categories menu opening
        $('.woocommerce.widget_product_categories .product-categories li.cat-parent').prepend('

');

        $(document).on("click", ".woocommerce.widget_product_categories .product-categories li.cat-parent > .cat-menu-close", function (e) {
            var $catParent = $(this).closest('li.cat-parent');
            var state = $catParent.hasClass('close');

            $catParent.toggleClass('opened', !state);

            $(this).nextAll('ul.children:first').slideToggle(state);

        });

    });
})(jQuery);

CSS:
.woocommerce.widget_product_categories .product-categories li .cat-menu-close {
     position: absolute;
     right: 0;
     line-height: 20px;
     text-align: center;
     cursor: pointer;
     top: 4px;
     width: 20px;
     height: 20px;
}
 .woocommerce.widget_product_categories .product-categories li > .cat-menu- close:hover {
     opacity: 0.5;
}
 .woocommerce.widget_product_categories .product-categories li > .cat-menu- close:after {
     display: inline-block;
     margin-left: 2px;
     background: url("../img/arrow-right.svg") no-repeat center center;
     background-size: 20px 20px;
     width: 10px;
     height: 20px;
     content: "";
}
 .woocommerce.widget_product_categories .product-categories li.opened > .cat- menu-close:after {
     background: url("../img/arrow-down.svg") no-repeat center center;
     background-size: 20px 20px;
}

Could someone help? I need to change the image when it expands and collapses, thank you and much appreciated.

A: the issue is that the category even after the SlideUp stays like this
class="cat-item cat-item-69 cat-parent opened"
instead of returning to it's original state that is
class="cat-item cat-item-69 cat-parent"
I am trying to find out the reason myself but I have too little experience with js so it's kinda hard to figure it out.
now if you remove the "!" from
$catParent.toggleClass('opened', !state);
the image will stop moving in general as it will not change the state.
edited answer bellow
Alright I have solved the riddle
After a bit of trial and error, I have your answer. In your code you have this:
        var $catParent = $(this).closest('li.cat-parent');
        var state = $catParent.hasClass('close');

        $catParent.toggleClass('opened', !state);

this part of the code sets the starting state "close"
        var state = $catParent.hasClass('close');

and when you click you get the state "opened" with the
        $catParent.toggleClass('opened', !state);

This doesn't give you the option to change back to the original state onclick as the "opened" state is set to as important with the exclamation mark.
Now if you edit your code to set two variable states as opened and close. and then leave the toggleClass to change between the states you get the outcome you want. I am not sure if my explanation is correct but here is the code you need.
I have already tested it and I am using it on the webpage I am administrating if you want you can check it out
// Categories menu opening
$('.woocommerce.widget_product_categories .product-categories li.cat-parent').prepend('

');

$(document).on("click", ".woocommerce.widget_product_categories .product-categories li.cat-parent > .cat-menu-close", function(e) {
var $catParent = $(this).closest('li.cat-parent');
var state = 'close'
var state = 'opened'

$catParent.toggleClass(state);

$(this).nextAll('ul.children:first').slideToggle(state);

[Edit]
To anyone checking out this answer I would better recommend another plugin named 'WooCommerce Product Categories Selection' as it seems to be functioning way better.
I am using it on my websites now, the only downside is that it doesn't have icons for expand and collapse but it's really easy to add it, and if you do decide to go that way you may like find this solution helpfull


text:
Q: Is "Paginator" part of the English lexicon? I have searched in oxford dictionary online and I didn't find Paginator word there, I only found Pagination word and I can find Googling there.
So my questions are:

*

*What should we call a something* that manage pagination?

*Is it possible to use it in formal letter?

(*) Let say a script file that manage or generate pagination for a website.

A: English is a very flexible language, particularly with respect to technical language of this type.  If you were discussing a utility for pagination you would generally call it a "pagination utility" or script, but if it is a phrase that is going to come up often, using the word "paginator" would be understood by any audience who understands what pagination is.
I can find it being used in some instances to mean exactly what you suggest, an automated system for paginating.  Most are using it as part of a name in a programming environment (ex: paginatorFunction) but here is an instance of it being used in exactly the sense that you wish to use it.


text:
Q: Zero rupees or zero rupee on the note? 5th Pillar is an NGO fighting against the corruption in India. As a part of non-cooperation movement against corruption, it has come up with a zero rupee note. Here is its image:

Now, my question is: Should we write 'zero rupees' or 'zero rupee'?
'Zero rupee' is written everywhere in the site.

A: Usually, attributive nouns in English are singular; for longer treatment, see How do you use plural or singular form of an adjective?.
You may consider units to be a variety of attributive noun, though there are additional guidelines, for example, for measurements. Different style guides define the guideline in different ways; the Oxford Style Guide says

Note that units of measurement retain their singular form when part of hyphenated compounds before other nouns

a five-pound note
    a two-mile walk
    a six-foot wall
    a 100-metre race

Integer and decimal amounts, on the other hand, are always plural if not exactly one. (Varun KN stated this in another way.) Thus,

*

*1 inch

*0.57 meters

*-3π radians

*62 degrees

*0 rupees

Thus, you have either

*

*a zero-rupee note

*a note worth zero rupees

Also see at EL&U

*

*Is -1 singular or plural?

*Plurality of numbers between -1 and 1

*Why is "zero" plural?

A: Good question!
If you are talking about the word to be printed on the note, it should be 'rupees'

Zero Rupees

Why? Because 'zero' is plural (it has been discussed thousands of times that why 'zero' is plural; Some say that 'only 1 is singular in English', others say it is grammatically synonymous with 'not any'; ...and so on; some simply raise a question -why we say 0.5 apples?...anyway, I won't get into it).
And I consider that you already know how to refer that note [you wrote 'a zero-rupee note'].


text:
Q: How to do a outer join in hibernate This is my sql query
SELECT * FROM candidate A
LEFT JOIN form B ON A.canid = B.canid
UNION
SELECT * FROM candidate A
RIGHT JOIN form B ON A.canid = B.canid

A: Joins in jpa are same as in sql jdbcTemplate. Joins in your above query are fine
SELECT * FROM candidate A
LEFT OUTER JOIN B ON A.canid = B.canid
UNION
SELECT * FROM candidate A
RIGHT OUTER JOIN B ON A.canid = B.canid


text:
Q: Mnemonic for creation and anhiliation operators I am not sure if this is question is withing the scope of this page. I have an exam in quantum mechanics in a few weeks and I always confuse anhilation and creation operator.
$$
a^\dagger |n\rangle = \sqrt{n+1} |n+1\rangle
$$
$$
a|n\rangle = \sqrt{n} |n-1\rangle
$$
Does someone have a mnemonic for these relations?

A: For me this is most easily clinched by the fact that the annihilation operator annihilates the vacuum:
$$\hat a|0\rangle=0.$$
If you're having trouble remembering which of $a$ and $a^\dagger$ is the annihilation/creator operator, this form may be useful; a-times-zero-is-zero sounds about as nice a mnemonic as you're likely to get, at least on the symbols side. (Of course, this requires you to beware of misremembering as $a^\dagger|0\rangle\stackrel{\text{!}}{=}0$. This form is more complicated - it's got more symbols -, so one way to remember it is to go for the simpler of the two.)
Further than that, if you know the general form of the relations,
$$
\begin{align}
a^\dagger |n\rangle &= \sqrt{n(+1?)} |n(\pm?)1\rangle,
\\
a|n\rangle& = \sqrt{n(+1?)} |n(\pm?)1\rangle,
\end{align}
$$
but you're having trouble remembering their exact form,
you can settle the ambiguity by noting that since $a|0\rangle$ must vanish, the coefficient must be $\sqrt{n}$; the coefficient of $a^\dagger$ must therefore be $\sqrt{n+1}$. The fact that $a$ 'kills' something also settles it as the annihilation operator, which means that it must take $|n\rangle$ to $|n-1\rangle$, and that leaves simply $|n+1\rangle$ for the final choice.
Of course, as with any mnemonics, it's a completely personal thing whether any particular mnemonic works for you or not. Also, as time goes on you will either use those relations often enough that you don't need a mnemonic, or you will stop using it and stop needing to remember.

A: I would say that I think $a$ for annihilate. Then since $a^\dagger$ has the dagger, it has to do the opposite thing i.e., create. That is how I would remember the difference between these two.
As far as the actual equation.
$$
a|n\rangle = \sqrt{n} |n-1\rangle
$$.
$$
a^\dagger |n\rangle = \sqrt{n+1} |n+1\rangle
$$
These two me always reminded me of differentiation and integration. The one with the annihilation operator is like differentiation (you bring down an $n$ and replace the original $n$ by $n-1$). The only difference is there is a square root.
Then the creation one looks like integration (you bring down an $n+1$ and then you increase the original $n$ to $n+1$). Here there are two differences: 1) the square root again, and 2) you multiply instead of divide.
If you have trouble remembering the differences from differentiation and integration, you can always check that $a^\dagger a = \hat{n}$. This equation will check out only if you remember about taking square roots and always multiplying.


text:
Q: How to judge if an image is part of another one in Python? This is how I tried:
(1) use PIL.Image to open the original(say 100*100) and target(say 20*20) image and convert them into np.array;
(2) start from every pixel in the original one as a starting position, crop a 20*20 area and compare every pixel RGB with the target.
(3) If the total difference is under certain given level, then stop and output the specific starting pixel position in the original one.
The problem is, step(3) costs over 10s which is much too long, even step(2) costs over 0.04s and I hope to optimize my program. In both steps I used For to iterate array, is there a more efficient way?

A: To compare two signals (or images) at different displacements one can use cross-correlation.
If you have the scipy package you can use 2D cross-correlation to measure how similar the two images are when you slide one image over the other.
This example is copied from the correlate2d function:
from scipy import signal
from scipy import misc
lena = misc.lena() - misc.lena().mean()
template = np.copy(lena[235:295, 310:370]) # right eye
template -= template.mean()
lena = lena + np.random.randn(*lena.shape) * 50 # add noise
corr = signal.correlate2d(lena, template, boundary='symm', mode='same')
y, x = np.unravel_index(np.argmax(corr), corr.shape) # find the match

If you don't want to use a toolbox you could implement the cross-correlation yourself.


text:
Q: Implementing Windows authentication with Reporting Services This is an extension of post Reporting Services Authentication advice sought as I am unable to submit a lengthy post on that thread (apologies admin).
Basically, I am configuring my local installation of reporting services to use Windows Authentication (with the ultimate aim of implementing this authentication on the network).
My current setup:
IIS (5.1):  I have created an application named "ReportServer" that uses ASP.NET v2.0.50727. The security for this application is set to "Integrated Windows authentication".  I have unchecked the "Anonymous access" check box.  Am I correct to assume this will prevent anonymous access to IIS (i.e. to the ReportServer application in IIS?) only.  Therefore, the user will be prompted for log in details, which in turn will be validated against windows/AD?
Report: I have created a shared data source where the database resides on a different server and configured the data source to use "Windows Authentication" (not SQL Server authentication) and I can test connection successfully.  I can also successfully create and test a simple report by running the report in BIDS.
When I deploy the report, I do not get prompted to login (which is fine).  I believe this is due to the fact the application directory in IIS is configured to use "Integrated Windows authentication" which is using the logged in PC user account (correct?).
Whenever I load reporting services via a browser, I am correctly being prompted for my windows domain username and password but only when I run the report from my local PC.  Once authenticated, I can see all reports applicable to me.  If a colleague attempts to connect to the report instance on my PC, he allowed in without having to log in!!  Why is this?!
However, when I run the deployed report via a browser, I receive the error "An error has occurred during report processing. Cannot create a connection to data source . Login failed for user '(null)'. Reason: Not associated with a trusted SQL Server connection."  If I change the data source so it uses SQL Server Authentication and I specify a login that exists in SQL Server, the report can be run successfully in a browser.
The ideal solution I would like to implement is as follows:

*

*A user loads the report server URL in a browser.

*The user is prompted for their Windows/AD credentials (including domain prefix).

*Behind the scenes the user is allowed into the report server.

*The user will only be able to see the report folders and reports he/she is allowed to see. This will be controlled by adding the allowed AD groups/users to the report folders and reports (I know how to do this bit).  I do not wish to have to maintain separate SQL Server user accounts.

I feel as if I am almost there, i.e. connection to the report server is prompting the user for their Windows credentials before allowing them access to the report server.
Please could someone tell me:
a) Why am I being prompted for my windows log in when I access the reports via a browser locally, but a different windows user is not prompted for a log in when they remotely access my report server via a browser window?
b) If a better overall solution should be implemented, please could you advise or point me to relevant resources.
c) Is there anything to be wary of with my current setup that may cause problems in the future.
Many thanks in advance.
JFB

A: There are 2 security aspects to deal with

*

*Authentication for the User Accessing the Report

*Authentication for the Data Source(s) accessing the database(s)

Typically, we've found that we want to kick unauthorized users out at point #1, and then (assuming that user is authorized), provide a static set of connection credentials for the data source - this has benefits such as allows connection pooling and saves our DBA's a ton of headache figuring which users can access which databases, and run which report SPROC's etc, since they only need to configure for the 'Report Data Source user'.
Point #1 is controlled by the Groups / Users added to the Report / Folder.
Point #2 can be done by setting up a domain credential for your Data Source and then assigning this user appropriate read / execute access on the various databases it needs to access.
Possibly the one point you may be missing is that your data source credential runs as needs 'log on locally' permissions in order to work?
FWIW our settings for the data sources are as follows:

*

*Credentials stored securely in the report server

*Check : Use as Windows credentials when connecting to the data source

The account running your

A: The reason you are experiencing this (i.e. user = null) is because you are asking the Report Server to validate Kerberos credentials. There is an extensive post here, but the crux of your issue is that you are asking the Report Server to validate Windows credentials but Active Directory doesn't trust your machine to pass these along. If you get delegation set up correctly, it will satisfy your requirements without a login prompt and you can control visibility by via your point #4.


text:
Q: Ruby Regex match method I was giving this regex /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]{2,}\z/ and I'm to use it in order to verify the validity of an email address.
This is my first Ruby code and I'm not sure how to do it. I was told to use the .match method, which returns MatchData object. But how do I go on verifying that the MatchData object confirms the validity?
I attempted using the following, but it seems that it's accepting any string, even not an email address.
#Register new handler
def register_handler

    email_regex = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]{2,}\z/
    email = "invalid"
    unless email =~ email_regex then
        puts("Insert your e-mail address:")
        email = gets
    end

    puts("email received")

end

What is the correct way to do this? Either using .match or the method I attempted above.

A: The regex matches email addresses:
'invalid' =~ email_regex
=> nil # which boolean value is false

'email@example.com' =~ email_regex
=> 0 # which boolean value is true

however:
"email@example.com\n" =~ email_regex
=> nil

The newline character \n is appended by gets to every input.
That is why, the until loop will run forever regardless of what you will type in the terminal. The matching result will always be nil because of the newline character.
Try using gets.chomp, which will trim the newline character and your code should work.

A: Try this:
Edited the regex and put () to capture group and the beginning and the end
re = /^([\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]{2,})$/m
str = 'a@b.com
p@qasdf.com
adbadf@bwdsfqaf.com
....
a@bdotcom

aasdf.com

www.yahoo.com'

# Print the match result
str.scan(re) do |match|
    puts match.to_s
end

Running sample code


text:
Q: Should class override Dispose(bool) to just call a containing object Dispose()? Should class override Dispose(bool) to just call a containing object Dispose()?
Is it safe to have only Dispose() method that calls a containing object Dispose() like in example below?
public class DisposableContainer : IDisposable
{
    private readonly IDisposable disposableObject = new();

    public void Dispose()
        => disposableObject.Dispose();
}

What bad consequences of this way of implementation could be?
According to Microsoft documentation, if class overrides Dispose(bool disposing), disposableObject.Dispose() should be called only when disposing is true. disposing should be false only when dispose called from a finalizer. But my class doesn not have finalizer.
Other questions about disposing in .NET on Stack Overflow are too general, just like the documentation. It seems like this simple specific case was not disscused yet.
Should I add boilerplate code like in the next example? Do I miss something to implement it properly?
public class DisposableContainer : IDisposable
{
    private readonly IDisposable disposableObject = new();

    public void Dispose()
        => Dispose(true);

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
            disposableObject.Dispose()
    }
}


text:
Q: iPhone(4s): How to update the application with apple-certificated ID with the Apple-certificated ID , we can debug/test the application on the real iPhone and Xcode is always used to install the application to be tested .
My question is : without the xcode, how can I install the test application on real iPhone.
PLease help to enlighten me .
Thanks a lot.

A: You can either send the app and a provisioning profile to a user who can then install the app using iTunes.
Or, and my preferred choice, use a service such as TestFlight to share your app over the air with testers and/or clients.


text:
Q: Export-SPWeb permissions When using Export-SPWeb to export a site does it copy permissions with it? When the export is running can it still be used by others? Once the export is complete will it be usable as before?

A: Yes, you can continue to use the site while executing Export-SPWeb. And, if you want to include the user security settings in the site use the IncludeUserSecurity parameter


text:
Q: ssh tunnel interrupted to unlock key - Looking for a single command I'm trying to create an ssh tunnel to access a remote server(A) that can only be accessed via another server(B). I have a key on my local machine(L) to get to the relay server(B) and another key on the relay server(B) to get to the destination server(A).
[local machine(L) with key to relay server(B)] --> [relay server(B) with key to destination server (A)] --> [destination server (A)]
I have a ~/.ssh/config file that looks like this on my local machine(L):
Host relay.server(B)
    Hostname relay.server
    Port 22
    User me
    IdentityFile ~/.ssh/id_rsa

Host destination.server(A)
    Hostname destination.server
    Port 1122
    User me
    IdentityFile ~/.ssh/id_rsa

And I can cludigly get my tunnel working with the following:
running the command: ssh -N -L 1122:SERVER_PRIVATE_IP:22 relay.server(B) on my local machine(L). This prompts me for a password to unlock the first key and then appears to hang it does not return a prompt, using the -f option or ending with an & prevents me from entering the password. However if I ^C this command after entering the password and then enter ssh destination.server(A) I get a prompt to provide a password to unlock the second key afterwhich I am connected to the destination server(A).
I'm looking for a single command that will let me connect to the destination server(A) from my local machine(L) and will prompt me to provide the passwords needed to unlock each key. Or a suggestion for an alternate way of organising things so that I can connect straight to the destination server(A) from my local machine (L) via the relay server (B).

A: The short answer is you need

*

*ProxyCommand using nc to connect through

*ForwardAgent to pass along keys

*ensure your public key is part of .ssh/authorized_keys on all servers

Host relay
    Hostname        relay.server.fqdn.or.IP
    User            me
    IdentityFile    ~/.ssh/id_rsa
    ForwardAgent    yes

Host destination
    Hostname        destination.server.fqdn.or.IP
    User            me
    IdentityFile    ~/.ssh/id_rsa
    ProxyCommand    ssh -q relay "nc %h %p"
    ForwardAgent    yes

The longer portion.
The ProxyCommand option in ssh config runs a command whenever that enclosing Host is used. It's typically used with nc available from nmap.org, also known as ncat and has lots of options.
In the above Host destination entry of ssh config, ProxyCommand was set to ssh -q relay "nc %h %p" which says, ssh to relay quietly and run nc destination.server.fqdn.or.IP 22.
nc makes the connection between the incoming ssh and the destination.
The ForwardAgent yes tells ssh to add the key to an ssh-agent. ssh agents keep track of the keys and are used to automatically pass the right one to a host as needed. The ForwardAgent yes tells the agent to pass the key along to another agent on the relay and then again to the destination.
Now for all this to work, each server you hop through and ultimately the destination must have the public key associated with your private key (id_rsa) in its .ssh/authorized_keys file. When you created your private key, id_rsa, a public key, id_rsa.pub, should also have been created.
If you don't have your public key, you can always get it from the private key via ssh-keygen -y -f ~/.ssh/id_rsa for easy copy/paste. Note that the public key has 2 or 3 space-separated fields but is one line.
So, ssh relay, edit ~/.ssh/authorized_keys (which may not exist, so mkdir -p ~/.ssh may be necessary) and paste the public key on a new line (or the first if not present).
While on the relay server, check that nc exists in /bin or /usr/bin. If it doesn't, then you'll need to install it using your package manager, either yum or apt-get.
From the relay server, ssh destination and do the same update of ~/.ssh/authorized_keys.
exit out all the way to your local machine, and you should be able to ssh destination

A: Newer OpenSSH versions allow ProxyJump in .ssh/config:
Host relay
    Hostname        relay.server.fqdn.or.IP
    User            me
    IdentityFile    ~/.ssh/id_rsa
    ForwardAgent    yes

Host destination
    Hostname        destination.server.fqdn.or.IP
    ProxyJump       relay
    User            me
    IdentityFile    ~/.ssh/id_rsa


text:
Q: intersystems cache - Is there a way to get change notivication on globals? I need realtime notifications on globals.
Because of the large amount of data it is very slow to read every time again and again the global data to detect what is change, delete or added.
For reading the globals i use the GlobalsFramework.dll and InterSystems.CacheExtreme.dll.
So i need tracking Data Changes without Audit Log.

A: No way, no real-time notifications. The only way to get this information is from Journal files.


text:
Q: Jenkins : Dynamically make the parameter available in UI while building job Assume I have a job at jenkins . and am trying to build it with parameters.
Assume I have 2 parameters say para1 and para2.
para1 is of choice type parameter with 'yes' and 'No' value
I want para2 to be available in the UI only when 'yes' is selected in para1. otherwise i dont want this parameter itself displayed in the UI
We have following plugins

*

*https://wiki.jenkins.io/display/JENKINS/Active+Choices+Plugin

*https://wiki.jenkins.io/display/JENKINS/Reactive+Reference+Dynamic+Parameter+Controls
but these will allow to dynamically return values for a parameter based on any reference i.e any prev paramter value,
but not to disable a parameter itself from a job while it builds, like the user should not see the parameter name itself in UI while building the job , in my case para2 should not be seen when 'No' selected in para1 ...
any suggestion or workaround to acheive my scenario ?
Many Thanks

A: What you are trying to achieve is not possible. A Jenkins job is defined by XML, displaying a new parameter based on a value of another one means that the XML definition of the job should be changed and the job reloaded again.
What you can do is to have both parameters displayed in the job and then just use a simple if statement in your Jenkins pipeline to ignore para2 in case para1 value is no.
if (para1 == 'yes'){
    print "Do something that takes into account ${para2}"
} else {
    print "${para2} value is ignored"
}


text:
Q: How to implement Line Feed in PowerBuilder? I have writen a script below that performs a line feed behavior (see attached image as reference output). But when I transmitted the text file via FTP, it results to a feedback error of  "Delimiters of the file is incorrect. It is still carriage return & line feed. It should just be a line feed. "
Hoping for a response from anybody....
PBScript:
Long ll_row
ll_row = dw_Outbound.InsertRow(0)
dw_Outbound.SetITem(ll_row,'message',as_message)
as_message = ""

File Write Function Script :
    //Retrieve Transaction Set Header
    ids_TSH = CREATE DataStore
    ids_TSH.DataObject = 'd_inventory_advice_transetheader'
    ids_TSH.SetTransObject( SQLCA )
    ids_TSH.Retrieve()
    IF ids_TSH.ROwCount() = 1 THEN
        ls_Msg += Trim(ids_TSH.Object.headerid[1])
        ls_Msg += "*" + Trim(ids_TSH.Object.setidcode[1])
        ls_Msg += "*" + Trim(ids_TSH.Object.setctrlnum[1])
        ls_Msg += "|"
        //Set LineFeed
        //ls_Msg += "~n"
        of_ReturnOutboundMessage(ls_Msg)
        of_getInventoryAdviceTranRowCount(ls_Msg)
    END IF

    //Retrieve Beginning Segment
    ids_BIA = CREATE DataStore
    ids_BIA.DataObject = 'd_inventory_advice_begsegment'
    ids_BIA.SetTransObject(SQLCA)
    ids_BIA.Retrieve()
    IF ids_BIA.RowCount() = 1 THEN
        ls_Msg += Trim(ids_BIA.Object.biaid[1])
        ls_Msg += "*" + Trim(ids_BIA.Object.trnsetpcode[1])
        ls_Msg += "*" + Trim(ids_BIA.Object.reptypecode[1])
        ls_Msg += "*" + Trim(ids_BIA.Object.refid[1])
        ls_Msg += "*" + is_BIADATE
        ls_Msg += "|"
        of_ReturnOutboundMessage(ls_Msg)
        of_getInventoryAdviceTranRowCount(ls_Msg)
    END IF

    //Assigned DateTime Reference
    ls_Msg += "DTM"
    ls_Msg += "*" + "007"
    ls_Msg += "*" + is_BIADATE
    ls_Msg += "*" + is_Time
    ls_Msg += "*" + "UT"
    ls_Msg += "|"
    of_ReturnOutboundMessage(ls_Msg)
    of_getInventoryAdviceTranRowCount(ls_Msg)

    //Assigned Reference Identification
    ls_Msg += "REF"
    ls_Msg += "*" + "EO"
    ls_Msg += "*" + "SAPMBT01" //ISA06 SENDERID : SPI818TEST
    ls_Msg += "|"
    of_ReturnOutboundMessage(ls_Msg)
    of_getInventoryAdviceTranRowCount(ls_Msg)

    lds_Data = CREATE DataStore
    lds_Data.DataObject = 'd_inventory_advice_subinv_phldef'
    lds_Data.SetTransObject(SQLCA)
    lds_Data.Retrieve()

    lds_Name = CREATE DAtaStore
    lds_Name.DataObject = 'd_inventory_advice_nameheader'
    lds_Name.SetTransObject(SQLCA)
    lds_Name.Retrieve()

    IF lds_Name.RowCount() = 1 THEN
        ls_Msg += Trim(lds_Name.Object.nameid[1])
        ls_Msg += "*" + Trim(lds_Name.Object.entityidcode[1])
        ls_Msg += "*" + Trim(lds_Name.Object.entityname[1])
        ls_Msg += "*" + Trim(lds_Name.Object.idcodequal[1])
        ls_Msg += "*" + Trim(lds_Data.Object.subinv[1])
        ls_Msg += "|"
        of_ReturnOutboundMessage(ls_Msg)
        of_getInventoryAdviceTranRowCount(ls_Msg)

        ls_Msg += Trim(lds_Name.Object.addressid[1])
        ls_Msg += "*" + Trim(lds_Name.Object.addressinfo[1])
        ls_Msg += "|"
        of_ReturnOutboundMessage(ls_Msg)
        of_getInventoryAdviceTranRowCount(ls_Msg)

        ls_Msg += Trim(lds_Name.Object.glid[1])
        ls_Msg += "*" + Trim(lds_Name.Object.cityname[1])
        ls_Msg += "*" + 'ML' //STATE OR PROVINCE CODE
        ls_Msg += "*" + Trim(lds_Name.Object.postalcode[1])
        ls_Msg += "*" + Trim(lds_Name.Object.countrycode[1])
        ls_Msg += "|"
        of_ReturnOutboundMessage(ls_Msg)
        of_getInventoryAdviceTranRowCount(ls_Msg)
    END IF

    //Administration Communication Contact
    /*lds_Contact = CREATE DataStore
    lds_Contact.DataObject = 'd_inventory_advice_contact'
    lds_Contact.SetTransObject(SQLCA)
    lds_Contact.Retrieve()
    IF lds_Contact.RowCOunt() = 1 THEN
        ls_Msg += Trim(lds_Contact.Object.accid[1])
        ls_Msg += "*" + Trim(lds_Contact.Object.fnccode[1])
        ls_Msg += "*" + Trim(lds_Contact.Object.name[1])
        ls_Msg += "*" + Trim(lds_Contact.Object.numqual[1])
        ls_Msg += "*" + Trim(lds_Contact.Object.telnum[1])
        ls_Msg += "|"
        of_ReturnOutboundMessage(ls_Msg)
        of_getInventoryAdviceTranRowCount(ls_Msg)
    END IF*/

    //Initialize DataStore To Handle Line Item RowCount
    ids_ITem = CREATE DAtaStore
    ids_ITem.DataObject = 'd_edi_outbound_message_external'
    ids_ITem.SetTransObject( SQLCA )

    IF lds_Data.RowCOunt() > 0 THEN
        FOR ll_Data = 1 To lds_Data.RowCOunt()
            ls_item = lds_Data.getitemString(ll_Data, 'itemcode')
            ls_qtyonhand = String(lds_Data.getItemNumber(ll_Data,'sohqty'))
            ls_qtyavailable = String(lds_Data.getItemNumber(ll_Data,'availableqty'))
            ls_subinv = lds_Data.getItemString(ll_Data,'subinv')

            ls_Msg = "LIN**MG*" + ls_item + "|"
            of_ReturnOutboundMessage(ls_Msg)
            of_getItemCodeRowCount(ls_Msg)
            of_getInventoryAdviceTranRowCount(ls_Msg)

            ls_Msg = "QTY*17*" + ls_qtyonhand + "|"
            of_ReturnOutboundMessage(ls_Msg)
            of_getInventoryAdviceTranRowCount(ls_Msg)

            ls_Msg = "QTY*33*" + ls_qtyavailable + "|"
            of_ReturnOutboundMessage(ls_Msg)
            of_getInventoryAdviceTranRowCount(ls_Msg)

            ls_Msg = "UIT*EA|"
            of_ReturnOutboundMessage(ls_Msg)
            of_getInventoryAdviceTranRowCount(ls_Msg)
        NEXT
    END IF

    ll_Filter = ids_ITem.RowCount()
    //Transaction Total
    ls_Msg += "CTT*" + String(ll_Filter) + "|"
    of_ReturnOutboundMessage(ls_Msg)
    of_getInventoryAdviceTranRowCount(ls_Msg)

    //Retrieve Set Trailer
    ids_TST = CREATE DataStore
    ids_TST.DataObject = 'd_inventory_advice_transettrailer'
    ids_TST.SetTRansObject(SQLCA)
    ids_TST.Retrieve()

    IF ids_TST.RowCount() = 1 THEN
        of_getInventoryAdviceTranRowCount(ls_Msg)
        //Get the  DataStore RowCount For Trasaction Set Trailer
        is_SetTrailer = String(ids_InvTranTrailer.RowCount())

        ls_Msg += Trim(ids_TST.Object.trailerid[1])+ "*" + is_SetTrailer + "*"
        ls_Msg += Trim(ids_TSH.Object.setctrlnum[1]) + "|"
    END IF
    of_ReturnOutboundMessage(ls_Msg)

    //Note: Function below should not be remove.
    //of_getInventoryAdviceGroupTrailer()
    //of_getInventoryAdviceControlTrailer()

    GETDATETIME:
    ls_ServerDate = gnv_app.of_getServerDateTime()

    IF is_ServerDateNull = ls_ServerDate THEN GOTO GETDATETIME
    is_ServerDateNull = ls_ServerDate

    FilePath = String(dw_path.Object.outboundfilepath[1])
    FileName = 'EDI_846_' + ls_ServerDate + '.TXT'
    FileDir = FilePath + '/' + FileName

    dw_Outbound.SaveAs(FileDir, TEXT!, FALSE)

    dw_Outbound.Reset()

A: The problem you've run into is the difference between the concept of newline between different operating systems. PowerBuilder is (at point of this writing, you haven't described which function is transporting data from the DataWindow into a text file) creating a file with Windows-style newlines (CR+LF, or in PowerScript, "~r~n"), whereas your FTP or FTP recipient (not clear where this message is coming from) wants Unix-style newlines (LF, or in PowerScript, "~n"). If you want control over how the newlines are generated, you're going to have to write the file yourself (in script, using FileOpen(), FileWrite(), etc... and not relying on PB to generate newlines, so no FileOpen (..., LineMode!, ...))
Good luck,
Terry.

A: I appreciate all the inputs and thank you for helping out. By the way i just want to share how i was able to resolved the issue.
Inside the IF lds_Data.RowCOunt() > 0 ELSE THEN construct, i have made a wrong concatenation which is  ' ls_Msg = ' which is supposed to be ' ls_Msg += '. Script has been revised and the files were successfully processed.


text:
Q: Can't open rptproj file in VS 15 Preview 4 I have downloaded BIDS and SSDT for 2015, but these don't seem to allow me to open a .rptproj file in my sln. It tells me that the application is not installed. How can I open this? It opens perfectly fine on vs 2012.

A: Currently the SQL BI project types (SSAS, SSRS, SSIS) are not supported on Visual Studio "15" Preview releases. The BI projects rely on some things not available yet (for example SSIS requires VSTA) and so support is not yet available in that product. The list of available versions to install is on the SSDT download page and will be updated when future versions are supported.
For now, Visual Studio 2015 is the recommended version to use - it is backwards compatible for all project types through SQL Server 2012-2016, with relational DB projects, SSAS and SSRS supported back through SQL Server 2008.


text:
Q: Automatic Chrome opening on session start - windows 10 I just want Google Chrome to automatically launch itself when I log into my win 10 session. Is that possible ? I saw a LOT of people wanting to disable this behavior on some systems, but none who tried to actually enable it, so couldn't find a solution yet.

A: Windows 10 has a startup folder in the Start Menu in which you can drop shortcuts to applications you want to start automatically.
In previous versions of Windows it was pretty easy to find but Windows 10 has made it a little more difficult.

*

*Press the Windows key and R together to open the run dialog

*Type in shell:startup and press OK, an explorer window will open up

*Copy and paste a shortcut to Chrome from your desktop to this window.

*Restart your PC and Chrome will automatically launch.

There is also a special mode called kiosk mode that will limit Windows to a single program. This is usually used for public access terminals.

A: I want to launch a program when I log in
Add a shortcut to the program you want to start (chrome in your case) to:
C:\Users\Your user name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

How to add or remove startup apps in Windows 10

Startup items for the current user are stored usually at two locations: the Registry and the special "Startup" folder. The Startup folder is an easier way to manage apps. To add or remove an app from the Startup folder, you need to do the following:

*

*Press Win+R shortcut keys together and type the following into the Run box:
shell:Startup
The text above is a special shell command which will open the Startup
  folder for you directly.

The Startup folder is located here:
C:\Users\Your user name\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

Just copy and paste a shortcut in this folder so that the app loads
  when Windows boots. To remove the application from the Startup folder,
  delete the appropriate shortcut.

Source How to add or remove startup apps in Windows 10

A: As described here go to

C:\Users\Your user name\AppData\Roaming\Microsoft\Windows\Start
  Menu\Programs\Startup

(or on Run shell:Startup )and add a shortcut of chrome at this folder


text:
Q: Retrofit 2.X - Response vs Call - What is the recommended to use? Please can you explain to me the difference of "Call" and "Response" in retrofit 2.X, What is the recommended way to use? and the difference of each. For instance I want to consume a 4 API calls with coroutines at the same time some might wait for response of other API and some will not. Thank you.

A: They are types for different purposes, but they come hand in hand.
Call<T> is a container that "sends a request to a webserver and returns a response".
Response is a container that delivers a result back to you, either from calling enqueue(Callback<T> callback) (asynchronously) and implementing Callback<T> or by calling execute() (synchronously). A Response can be either successful or a failure.
In other words, first you do a Call and then you get back a Response.
Documentation

*

*Call

*Response

A: Call --> When you wanna use request callback for error or response, you can use that. it's useful for tracking request status if it is successful or failed.
call.enqueue(object : Callback<T> {
     override fun onResponse(call: Call<T>, response: Response<T>) {
         // in response
     }

     override fun onFailure(call: Call<T>, t: Throwable) {
         // in error
     }
})

Response --> When you wanna use kotlin Coroutines or RxJava in your project, it's strongly recommended to use Response. It's very very fantastic experience to use that for working with asynchronous tasks...
suspend fun getUsersFromServer(): List<User> {
    var users = ArrayList<User>()
    val response = retrofitService.getUsers()
    response.body()?.let {
        users = it
    }
    return users
}


text:
Q: Median select algorithm - does it find the absolute median, or a "median of medians" close to the absolute median? Section 9.3 in CLRS 3rd edition "Selection in worst-case linear time" talks about the "Select"  algorithm (sometimes called the BFPRT algorithm due to Blum, Floyd, Pratt, Rivest, and Tarjan) for finding the median of a list in O(n) time at worst case. I got a little confused as I tried to run a sample on the whiteboard. I understand that a certain number of elements can be eliminated at each call to "Select" (I have read 30% are eliminated versus 70% that need to be  checked again), what I was confused about was which part of the array can be eliminated, i.e. if the array is visualized as a matrix with height 5 and width n/5, then which quadrant(s) do the eliminated elements rest in? I originally thought it was two diagonally adjacent quadrants but now I am thinking it is only one quadrant depending on what the median of medians is (see steps 5, 6, and 7 here).
So I went to wikipedia to see if there was a quick explanation with less analysis than CLRS (for the sake of understanding the algorithm before I jumped back to CLRS for the analysis). I came to this, particularly 'Finally, the "median of medians' is chosen to be the pivot." from the sound of the description in wikipedia, "Select" does not find the true median rather a element that is median-enough for the purpose of choosing a pivot for quicksort.
So what does "Select" do in terms of the true median, and how does it do it? The phrase that comes to mind through all of this is "partial hierarchy", which as I understand, is the reason "Select" works, but by what logic can you eliminate elements from the list from being the median based on this partial hierarchy?

A: It finds the absolute median.
As you said, "Select" does not find the true median rather a element that is median-enough for the purpose of choosing a pivot for quicksort.  In particular it is median enough that it is guaranteed to drop at least 30% of the dataset on every iteration.  Unfortunately it is also an expensive operation.
The key idea is that the median of medians is less than or equal to 3 out of every 5 elements whose median is less than or equal to it.  So it is less than or equal to 3 out of every 5 elements for half the groups of 5, so at least 30% of the set is less than or equal to it.  So it is in the largest 70% of the data set.
Similarly it is in the smallest 70% of the data set.
This guarantees that you avoid the potential pitfall of quickselect, which is picking pivot points that have extreme values.
If you wish to combine efficiency and a good worst case you can combine this with quickselect.  For instance 4 rounds of quickselect followed by one round of this followed by 4 rounds of quickselect, etc.  The expensive rounds of BFPRT guarantee O(n) while the quickselect on average is going to be fast.  By putting off your first round of BFPRT until you've done several rounds of quickselect you can make the extra running time only a few percent more than quickselect on average.  (The worst case cost goes up by quite a bit, but we don't expect to encounter that.)


text:
Q: Error while doing text-classification in Keras I am doing text classification in Keras. First, I am creating an embedding matrix with Word2Vec and passing it to Keras Embedding layer. Then I am running Conv1D on top of it. This is the dataset I am using. Here is my code below:
from gensim.models import Word2Vec
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
import numpy as np
from keras.models import Sequential
from keras.layers import Embedding,Flatten,Dense,Conv1D,MaxPooling1D,GlobalMaxPooling1D
from sklearn.preprocessing import LabelEncoder
from keras.utils import np_utils
import pandas as pd
from nltk.tokenize import word_tokenize

# def dataframe_to_list_of_words(df_name, col):
#   df = pd.read_csv(df_name)
#   lst = df[col].drop_duplicates().values.tolist()
#   tokenized_sents = [word_tokenize(i) for i in lst]
#   tokenized_sents_mod = [word for sublist in tokenized_sents for word in sublist]
#   return tokenized_sents_mod

# def convert_data_to_index(string_data, wv):
#     index_data = []
#     for word in string_data:
#         if word in wv:
#             index_data.append(wv.vocab[word].index)
#     return index_data

df=pd.read_csv('emotion_merged_dataset.csv')
texts=df['text']
labels=df['sentiment']

df_tokenized=df.apply(lambda row: word_tokenize(row['text']), axis=1)

model = Word2Vec(df_tokenized, min_count=1,size=300)
##############
embedding_matrix = np.zeros((len(model.wv.vocab), 300))
for i in range(len(model.wv.vocab)):
#     print(model.wv.index2word[i])
    embedding_vector = model.wv[model.wv.index2word[i]]
    if embedding_vector is not None:
        embedding_matrix[i] = embedding_vector
################
labels=df['sentiment']
encoder = LabelEncoder()
encoder.fit(labels)
encoded_Y = encoder.transform(labels)
labels_encoded= np_utils.to_categorical(encoded_Y)
#########################

maxlen=30
tokenizer = Tokenizer(3000)
tokenizer.fit_on_texts(texts)
sequences = tokenizer.texts_to_sequences(texts)
word_index = tokenizer.word_index
print('Found %s unique tokens.' % len(word_index))
data = pad_sequences(sequences, maxlen=37)
############################
embeddings = Embedding(input_dim=embedding_matrix.shape[0], output_dim=embedding_matrix.shape[1],
                      weights=[embedding_matrix],trainable=False)
model=Sequential()
model.add(embeddings)
model.add(Conv1D(32,7,activation='relu'))
model.add(MaxPooling1D(5))
model.add(Conv1D(32,7,activation='relu'))
model.add(GlobalMaxPooling1D())
model.add(Dense(labels_encoded.shape[1], activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

model.fit(data, labels, validation_split=0.2, epochs=10, batch_size=100)

I am getting the following error when I am running my code:
Error when checking target: expected dense_1 to have shape (None, 8) but got array with shape (19283, 1)

Can someone please help me?

A: You have encoded the labels as categorical, but didn't actually used the result of this. Change:
model.fit(data, labels, validation_split=0.2, epochs=10, batch_size=100)

to ...
model.fit(data, labels_encoded, validation_split=0.2, epochs=10, batch_size=100)


text:
Q: Cycles in gaussian graphical models I understand examples where two nodes can be dependent but conditionally independent given their common cause. For instance the common cause is high temperature, and the children nodes are high icecream sales and more number of sharks. The children are correlated through the high temperature, but independent given the high temperature. Mathematically, this is equivalent to -
\begin{align*}
b&=a+\epsilon_1\\
c&=a+\epsilon_2
\end{align*}
$b$ is correlated with $c$, but $b\perp c|a$
I cannot imagine a scenario where cycles would occur. What is a physical or mathematical example that leads to a graph with cycles?

A: Cycles in a probabilistic graphical model (PGM) violate the condition that the product of the individual node's local distributions P(v_i | parent_of(v_i) ) equal the joint of the node variables in the network P( v_1..v_n). Similarly if, one thinks causally, by analogy it looks like a case of circular reasoning.
One closely related model, a continuous time Bayes network, does allow cycles, but they "unwind" to create a temporal dependence.
In short, if you conceive of cycles in a PGM, its probably a temporal effect where each time around the cycle represents a different time-stage.


text:
Q: How can you start a process from asp.net without interfering with the website? We have an asp.net application that is able to create .air files.
To do this we use the following code:
System.Diagnostics.Process process = new System.Diagnostics.Process();

//process.StartInfo.FileName = strBatchFile;
if (File.Exists(@"C:\Program Files\Java\jre6\bin\java.exe"))
{
    process.StartInfo.FileName = @"C:\Program Files\Java\jre6\bin\java.exe";
}
else
{
    process.StartInfo.FileName = @"C:\Program Files (x86)\Java\jre6\bin\java.exe";
}
process.StartInfo.Arguments = GetArguments();
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.PriorityClass = ProcessPriorityClass.Idle;

process.Start();

string strOutput = process.StandardOutput.ReadToEnd();
string strError = process.StandardError.ReadToEnd();

HttpContext.Current.Response.Write(strOutput + "<p>" + strError + "</p>");

process.WaitForExit();

Well the problem now is that sometimes the cpu of the server is reaching 100% causing the application to run very slow and even lose sessions (we think this is the problem).
Is there any other solution on how to generate air files or run an external process without interfering with the asp.net application?
Cheers,
M.

A: The problem is here: process.WaitForExit();, you are simply halting the execution of the application. You might want to use a thread to start the process and some sort of IPC (Inter Process Communication, like remoting, named pipes) to know when the generation is finished.


text:
Q: How to make SSRS reports available to users? I've been thinking of the best way to present reports to the end user. We've accumulated several dozen reports. Some are subscription-based and are exported into Excel or emailed out regularly but a large number are run on-demand.
There's the option of sending the users the direct link to the reports. We don't do this because it's not easy to find (they have to dig through emails or bookmark the link)
http://server/ReportServer/Pages/ReportViewer.aspx?myreportrs:Command=Render
We've been embedding reports in sharepoint (or simply adding a link to the report). We're not using Sharepoint Integrated Mode. This has become a little unorganized where we have a large number of links to reports. I'm not sure what other solution exists..
SQL 2008, Sharepoint 2007

A: Depends on how much maintenance effort and instruction you want to provide. Some likely options include:

*

*Use a SharePoint content page and hardcode a page with links to different reports.

*Create a Sharepoint URL list linking to the different reports.

*Create an SSRS report that is acts as a central index. This could either be a static page (a report without any data
source, just many static text boxes.) or a dynamic list of reports.
Depending on requirements you could query the SSRS databases and
use that as a central list.

My clients have generally found that a one of these, the Report Manager interface (/reports/), and emailing of specific report urls to be adequate.
Another option I once used: we created a formula (happened to be in Excel) that would create a url with the appropriate custom parameters to return just the data the user was interested in. Passed the parameters to SSRS as part of the URL. (Search on SSRS URL access.)


text:
Q: Loading Image in Silverlight I want to create a WritableBitmap and display a bitmap from stream onto a Image object. How to do that in Silverlight. I am doing the following which is not working.
  Image img = new Image();

  System.IO.Stream stream =  File.OpenRead("1.bmp"); //Getting access permission error

  WriteableBitmap bmp1 = new WriteableBitmap(100, 100);
  bmp1.SetSource(stream);
  //do operations with bmp1

  img.Source = bmp1;

A: In Silverlight, file I/O is pretty constrained.
Check this post
In Browser Silverlight Application - Client Side File/Directory access


text:
Q: Get a Sorted List by user I need to get a list sorted by decreasing values of expenses, but by Taxpayer. Imagining the Taxpayer with number 1 has 3 expenses and the Taxpayer with number 2 has 2 expenses, I need to get the expenses from the first Taxpayer and sort them, then sort the expenses of Taxpayer number 2. What I had so far was:
 public TreeSet<Expense> getListFactIndivValor(){
   TreeSet<Expense> t = new TreeSet<Expense>(new ComparatorValue(-1)); //-1 because I had to use this comparator to do ascending order on another method
   Company c = (Company) this.users.get(userId); //Entity that issues expenses. has the method getExpenses. Gets the Company logged in.
   for(User u: this.users.values()){ //this.users has all the users on the system
       if(!u.getUserType()){ // If user is Taxpayer
           for(Expense e: c.getExpenses().values()){ //gets all the expenses of the Company.
             if(u.getTIN().equals(e.getTINUser())){ //if the user TIN is the same that the one on expense
                  t.add(e.clone());
             }
           }
       }
   }
   return t;

}
What I think is happening is he goes through each Taxpayer like I intend, but then it's just ordering it by value, not taking into consideration that I need to have it by each Taxpayer.

A: A Set (TreeSet) is not designed to have a specific order. Rather use an ArrayList as the result of your method.
You have to do two steps:

*

*Sort the expenses to the user it belong to (using a TreeMap which is sortable)

*Iterate on the (sorted) users and extract the her expenses.
public List<Expense> getListFactIndivValor()
{
    Comparator<TINUser> comparator = TINUser::compareTo;
    TreeMap<TINUser, List<Expense>> map = new TreeMap<>( comparator);
    Company c = new Company();
    for ( Expense e : c.getExpenses() )
    {
        List<Expense> expenses = map.get( e.getTINUser());
        if ( expenses == null )
        {
            expenses = new ArrayList<>();
            map.put( e.getTINUser(), expenses);
        }
        expenses.add( e);
    }

    List<Expense> result = new ArrayList<>();
    for ( TINUser u : map.descendingKeySet() )
    {
        List<Expense> expenses = map.get( u);

        for ( Expense expense : expenses )
        {
            result.add( expense);
        }
    }

    return result;
}

Implement a compareTo() method in your TINUser class which defines the sort criteria.


text:
Q: Update multiple rows using math to add to existing value I am trying to update multiple rows. Some rows may have a value already. So if the value in that row was 2 and I wanted to update it with an additional 4 to make total of 6. How can I do that without querying each row for it's current value? Or must I do that?
I currently have something like thing like this.
item_match = Item.where("id IN (?)", item_match_ids).to_a
item_match.update_all(quantity: quantity)

A: If adding the same value to all records, you can use the following:
item_match.update_all("quantity = quantity + #{ quantity }")

This is much faster than updating the records individually. To be safe, you should make the quantity column non-null and set a default value. Be sure to sanitize the quantity value for SQL if it's user-supplied.

A: I think you must remove the to_a, leaving this way:
Item.where(id: [id1, id2, ...]).update_all(quantity: quantity)

But, if you want to add a quantity to each record you need use find each:
Item.where(id: [id1, id2, ...]).find_each do |item|
  item.update(quantity: item.quantity + quantity)
end

You will find more of find_each here


text:
Q: Vector Space Operator such that $T^9 = T^8$ but $T \neq T^2$. Find a Vector Space Operator such that $T^9 = T^8$ but $T \neq T^2$,
I rewrote this as
$$\left\{\begin{array}{rcl} T(T^8-I) & = & 0 \\
T(T-I) & \neq & 0 \end{array}\right.
\implies (T^8 = I) \wedge (T \neq I).$$
For the life of me I can't find an example of this.
Thanks :)

A: Nilpotent matrices of order 8 (matrices $A$ for which $A^8=O$ but $A^n\ne O$ for $n<8$) will satisfy the requirements. One such example is the 8×8 shift matrix with ones on the superdiagonal or subdiagonal and zeroes everywhere else.

A: We have that $T$ satisfies $T^9=T^8$, if and only if the minimal polynomial of $T$ divides $x^9-x^8=x^8(x-1)$. Since we don't want that $T^2=T$, we must pick a $T$ with minimal polynomial equals to $x^k(x-1)$, with $k>1$. By the Jordan form, we have that the operator given by
$$
\left[\begin{array}{ccc}
0 & 1 & 0 \\
0 & 0 & 0 \\
0 & 0 & 1
\end{array}\right]
$$
has minimal polynomial equal to $x^2(x-1)$, so it satifies what we want.

A: $$
\left(
\begin{array}{cc}
0&1 \\
0&0
\end{array}
\right)
$$


text:
Q: how to return value from CASE expression into a ALIAS I want to return a value into an alias from a case argument. I've tried various connotations around the following
CASE dbo.sch_group.group_code WHEN 'ERDS' THEN '1' AS alias_name

but I get incorrect syntax warnings near the alias

A: You're missing an END (CASE on MSDN). This is a "simple CASE expression"
CASE dbo.sch_group.group_code
    WHEN 'ERDS' THEN '1'
END AS alias_name

If you have more conditions then it would be this
CASE dbo.sch_group.group_code
    WHEN 'ERDS' THEN '1'
    WHEN 'abcd' THEN '2'
    ELSE <something>
END AS alias_name

I also assume this is in a SELECT or such
SELECT
    col1, col2,
    CASE dbo.sch_group.group_code
        WHEN 'ERDS' THEN '1'
        WHEN 'abcd' THEN '2'
        ELSE <something>
    END AS alias_name
FROM
    dbo.sch_group
WHERE
    ...

A: This is from ORACLE so I'm not sure if it'll work in SQL Server but:
(CASE WHEN dbo.sch_group.group_code = 'ERDS' THEN '1' END) AS alias_name


text:
Q: Comparing the efficiency of estimators I've taken the following explanation from Wikipedia page on efficiency.

If $T_1$ and $T_2$ are estimators for the parameter $\theta$, then $T_1$ is said to ''dominate'' $T_2$ if:

*

*Its mean squared error (MSE) is smaller for at least some value of $\theta$

*The MSE does not exceed that of $T_2$ for any value of $\theta$.
Formally, $T_1$ dominates $T_2$ if
$
\mathrm{E}
\left[
 (T_1 - \theta)^2
\right]
\leq
\mathrm{E}
\left[
 (T_2-\theta)^2
\right]
$
holds for all $\theta$, with strict inequality holding somewhere.

My question is, how can this hold for all $\theta$? Isn't there only one value of $\theta$? If $\theta$ is a parameter isn't it's value fixed at a single unknown quantity? Or does the formula imply that the estimators are compared across different populations which all of which have an important defining parameter which is called $\theta$?