text:
Q: how to separate the grade of the student kindly help me, i'm on the making of online student information and it have many students and i don't know how to separate the grades of the student according to their StudID (student ID).
My code goes like this...
function Content()
{
      $code = <<< htmlcode

            <form name="frmGrade" method="POST" action="" style="padding-top:30px;">

                    Subject
                    First Grading
                    Second Grading
                    Third Grading
                    Fourth Grading
                    Average
                    Remarks

        htmlcode;

    //-------------------------------------
    // retrieve data from database
    //-------------------------------------
    $sql = "SELECT Subject,FirstGrading,SecondGrading,ThirdGrading,FourthGrading,Average,Remarks FROM grades WHERE StudID = '002' ;";
    $result = mysql_query($sql);
    $num_rows = mysql_num_rows($result);

    //-------------------------------------
    // fetch each record from database
    //-------------------------------------
    if($num_rows > 0)
    {

        for($ctr = 1; $ctr <= $num_rows; $ctr++)
        {
            $row = mysql_fetch_array($result);
            $sub = $row['Subject'];
            $fg = $row['FirstGrading'];
            $secg = $row['SecondGrading'];
            $thg = $row['ThirdGrading'];
            $fourthg = $row['FourthGrading'];
            $ave = $row['Average'];
            $remarks = $row['Remarks'];

            $code .= <<< htmlcode

                     $sub
                     $fg
                     $secg
                     $thg
                     $fourthg
                     $ave
                     $remarks
                    $actions

            htmlcode;
        }

        //-------------------------------------
        // end table
        //-------------------------------------
        $code .= "
 </form>

";

    }

    //-------------------------------------
    // Display table
    //-------------------------------------

    return $code;
}
?>

what i want is that when Student one with StudID=001 he/she will see are the grade of him/her and when student two with StudID=002 will see ONLY his grade.

A: Fetch row from $result in while loop not for loop
function Content($sid)
{
  $code = <<< htmlcode

        <form name="frmGrade" method="POST" action="" style="padding-top:30px;">

                Subject
                First Grading
                Second Grading
                Third Grading
                Fourth Grading
                Average
                Remarks

    htmlcode;

//-------------------------------------
// retrieve data from database
//-------------------------------------
$sql = "SELECT Subject,FirstGrading,SecondGrading,ThirdGrading,FourthGrading,Average,Remarks FROM grades WHERE StudID = '$sid' ;";
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);

//-------------------------------------
// fetch each record from database
//-------------------------------------
if($num_rows > 0)
{

    while($row = mysql_fetch_array($result))
    {

        $sub = $row['Subject'];
        $fg = $row['FirstGrading'];
        $secg = $row['SecondGrading'];
        $thg = $row['ThirdGrading'];
        $fourthg = $row['FourthGrading'];
        $ave = $row['Average'];
        $remarks = $row['Remarks'];

        $code .= <<< htmlcode

                 $sub
                 $fg
                 $secg
                 $thg
                 $fourthg
                 $ave
                 $remarks
                $actions

        htmlcode;
    }

    //-------------------------------------
    // end table
    //-------------------------------------
    $code .= "
 </form>

";

}

//-------------------------------------
// Display table
//-------------------------------------

return $code;
}
?>

<?php
    //to get content for student 001
    echo Content('001');

    //to get content for student 002
    echo Content('002');
?>


text:
Q: How to scroll with jqGrid cell editing on editrow call? I've set up my jqGrid to use cell editing, and I've bound some keys for navigation.
Up and down arrows will call edit row on the previous or next row, and it works great. Only problem is if I get to the end of the visible records, it does not scroll to keep up.
I've tried setting scrollrows: true in the grid options, but that only seems to work for selecting a whole row, and not a cell.
Anyone have to deal with this before? I'm not very experienced with scrolling and javascript/jquery, so I don't have an out of the box solution for this.
Thanks for any suggestions!
EDIT: Here is a fiddle to help debug. To see the problem, click on the "Thingy" column, the use the down arrow to navigate.

A: The editNewCell function may be modified to use setSelection to ensure the newly edited row is visible:
function editNewCell(iRow, iCol) {
    e.preventDefault();
    e.stopPropagation();
    e.stopImmediatePropagation();
    grid.editCell(iRow, iCol, true);

    var selRow = grid.getGridParam('selrow');
    grid.jqGrid('setSelection', selRow );
};

Here is a jsfiddle with the change, if you would like to try it out.

A: I'm not sure I got it right. What do you mean by "if I get to the end of the visible records, it does not scroll to keep up."? Do you mean that once you reach the top/bottom row you cannot go any further OR do you mean that in a row if you keep scrolling horizontally and once you cross the end of visible records your edit mode goes away.
I have similar excel like gridedit implementation where i have the up and down arrow navigation in edit mode for cell edit. The link in the first paragraph will take you to the jsfiddle sample. In the javascript section look for HandleInputNavigation function. I have tied the keydown event in the colModel under the column's editoptions to the HandleInputNavigation function. Thats where I handle the up/down navigation.
UPDATED 5/24: Here is how your code should look like:
    if (iRow && iCol) {
    var isShift = window.event.shiftKey ? true : false;
    var top = 1; //UPDATED
    var bottom = grid.getGridParam('reccount');
    var left = 0;
    var right = grid.getGridParam("colNames").length - 1;

    switch (key) {

    case 38:
            // up
        if (iRow === top) saveCell(iRow, iCol); //UPDATED
        else editNewCell(iRow - 1, iCol);
        break;

    case 40:
            // down
        if (iRow === bottom) saveCell(iRow, iCol); //UPDATED
        else editNewCell(iRow + 1, iCol);
        break;
    ...
    ...

UPDATED FIDDLE

redpajama_set_name: RedPajamaStackExchange


text:
Q: Return data from method in object I have been trying to figure this one out and I'm not getting how to return the data to another method and call it so that I don't have to statically add the data into my request. I keep getting undefined data on my B2C method when I run it for the data returned from this.O_Auth. Any clues?
let obj = {
    O_Auth(key, secret) {
        const key = Key;
        const secret = Secret;
        const auth = "Basic " + new Buffer(key + ":" + secret).toString("base64");

        request(
            {
                uri: "https://randomurl",
                method: 'GET',
                headers: {
                    "Authorization": auth
                }
            },
            (err, res, body) => {
                if (err) {
                    return err;
                } else {
                    // console.log(body);

                    let response = JSON.parse(body);
                    let res = JSON.stringify(response.access_token)
                    return res;

                }
            }
        );
    },
    B2C(params) {
        console.log("Random " + this.O_Auth('first', 'second'));
        let options = {
            method: 'POST',
            uri: 'https://randomurl',
            headers: {
                "Authorization": "Bearer " + this.O_Auth('first', 'second'),
                "Content-Type": "application/json"
            },
            body: {
                //values
            },
            json: true
        };

        rp(options)
            .then(function (body) {
                console.log(body);
            })
            .catch(function (err) {
                console.log(err);
            });
    }
}

A: Ended up figuring out the asynchronous nature of JavaScript meant I was requesting data that was being evaluated later so I used a promise to get the data and output it first before using it in a subsequent promise that outputs the body. Changed the first request to request promise (rp) that returns the options that will be needed for that promise in the second method.
    let obj = {
    O_Auth(Key, Secret) {
        const key = Key;
        const secret = Secret;
        const auth = "Basic " + new Buffer(key + ":" + secret).toString("base64");

     let options = {
                uri: "https://randomurl",
                headers: {
                    "Authorization": auth
                },
                json: true
            };

        return rp(options)
    },
    B2C(param1, param2, param3...) {
        this.O_Auth('first', 'second'))then(response =>{
        let token = response.access_token;
        let options = {
            method: 'POST',
            uri: 'https://randomurl',
            headers: {
                "Authorization": "Bearer " + token,
                "Content-Type": "application/json"
            },
            body: {
                //values
            },
            json: true
        };

        rp(options)
            .then(function (body) {
                console.log(body);
            })
            .catch(function (err) {
                console.log(err);
            });
    }).catch(error => console.log(error));
    }
}


text:
Q: How to read serial number from text file I have a text file which contain of lots of information, but i only want to show the serial number of the text file. I am able to read and show the whole line of the serial number in label, but i only required the serial number in the format of ["BcXXXXX"]. Anyone would able to guide through?
        string path = @"D:\Sample.txt";
        StringBuilder buffer = new StringBuilder();
        using (StreamReader sr = new StreamReader(path))
        {
            while (sr.Peek() >= 0)
            {
                String str = sr.ReadLine();
                if (Regex.IsMatch(str, "Bc"))
                    buffer.Append(str);
                string s = buffer.Append(str);
                int start = s.IndexOf("["Bc") + 1;
                int end = s.IndexOf(""]" , start);
                string result = s.Substring(start, end - start);
                label2.Text = result.ToString();
            }

A: string serialNumber = System.IO.File.ReadLines(@"D:\Sample.txt")
.Select(line =>
{
    var match = System.Text.RegularExpressions.Regex.Match(line, @"^\[""(.*)""\]$");
    return match.Success ? match.Groups[1].Value : null;
}).FirstOrDefault(sn => sn != null);


text:
Q: Selecting between valid and non-valid non-type parameter pack I'm trying to replicate the answer to this question: Selecting between valid and non-valid types but I can't figure out how to achieve this with a non-type template parameter pack.
For context, I'm trying to implement a templated multidimensional array
template<typename T, std::size_t CurrentDim, std::size_t... Dims>
class Array {

In the class, I'm trying to create a array of type T if Dims is empty and an an array of type Array<T, Dims...> if Dims is not empty. For example:
using SubType = std::conditional<sizeof...(Dims) == 0, T, Array<T, Dims...>>;
SubType array[CurrentDim];

The problem is that if Dims is empty, the conditional fails with
error: too few template arguments for class template 'Array'

...since the second part of the conditional, which is invalid, is evaluated even though the check is false. Does anyone know how to achieve this? I know I could specialize my Array class but I believe that would require me to duplicate all my code?
Here's another related question: std::conditional compile-time branch evaluation

A: One approach would be partial specialization:
template<typename T, std::size_t CurrentDim, std::size_t... Dims>
class Array {
  Array<T, Dims...> array[CurrentDim];
};

template<typename T, std::size_t Dim>
class Array<T, Dim> {
  T array[Dim];
};


text:
Q: Why isn't the sequence $\frac 1n$ bounded? Since "Every convergent sequence is bounded" and bounded means bounded above and below.
Then why is the sequence $\frac 1n$  convergent? since it is not bounded above (converges to $0$ for lim -> infinity) it is bounded below by $0$ but not above so the sequence is not bounded yet it is convergent.

A: There seems to be misunderstanding about definition of sequence:

Sequence $(a_n)$ in set $S$ is a function $a\colon \Bbb N\to S$.

For example, sequence $a_n = \frac 1 n$ is a function $n\mapsto\frac 1 n\colon \Bbb N\to\Bbb R$ and some of its terms are: $$1,\frac 12,\frac 13,\frac 14,\frac 15,\frac 16\ldots$$
You can observe that $a_n> 0$, for all $n\in\Bbb N$:
$$\frac 1 n> 0 \iff n > 0\quad\small\text{(which is true for all $n\in\Bbb N$)}$$ and thus, $(a_n)$ is bounded from bellow.
Also, observe that $(a_n)$ is strictly decreasing sequence, i.e. $a_n> a_{n+1}$, for all $n\in\Bbb N$:
$$\frac 1n>\frac 1{n+1} \iff n+1>n\iff 1>0.$$
In particular, $a_n\leq a_1 = 1$, for all $n\in\Bbb N$ and thus, $(a_n)$ is bounded from above.

A: The sequence is bounded from above by $9$. For every $n\in \mathbb N$, the inequality $$\frac1n\leq 9$$ is true.

A: It is bounded above, by, say, 2: every term is less than 2. A bound does not have to be tight.


text:
Q: A graph-coloring problem where only some of the edges should be bichromatic In a standard graph-coloring problem, it is required that all edges will be bichromatic (i.e., all edges should be connected to two vertices with different colors). What is a term, and some basic references, for a graph-coloring problem in which only a fraction of the edges should satisfy this condition? For example, at least $\frac23$ or at least $\frac12$?
I looked for "fractional coloring" but, apparently, it is a completely different problem.

A: A colouring without the condition that edges be bicromatic is called by different names such as relaxed coloring, improper coloring and defective coloring. (warning: the term defective coloring is more commonly used to mean a relaxed coloring with a restriction on maximum degree allowed in colour classes; relaxed coloring with this restriction is explored enough in the literature in both theoretical interest and applications)
What you want is a relaxed coloring with a fraction of edges coloured properly. I remember seeing something similar to this on a paper on .... defective colouring(?), but quite don't remember the source.
I thought this could help someone interested to further explore.


text:
Q: Cannot load library jni ffmpeg in intellij idea After a lot of trial and error I managed to make all the program work except when coming to load a library. The library is located in the JNI folder. Can someone help me with this error?
02-11 21:38:32.940  26771-26771/com.example.untitled E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.untitled, PID: 26771
    java.lang.UnsatisfiedLinkError: Couldn't load nativetester-jni from loader dalvik.system.PathClassLoader[DexPathList[[zip file "/data/app/com.example.untitled-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.example.untitled-2, /vendor/lib, /system/lib]]]: findLibrary returned null
            at java.lang.Runtime.loadLibrary(Runtime.java:358)
            at java.lang.System.loadLibrary(System.java:526)
            at com.example.untitled.NativeTester.<clinit>(NativeTester.java:23)
            at com.example.untitled.FFmpegPlayer.<clinit>(FFmpegPlayer.java:184)
            at com.example.untitled.VideoActivity.onCreate(VideoActivity.java:134)
            at android.app.Activity.performCreate(Activity.java:5231)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
            at android.app.ActivityThread.access$800(ActivityThread.java:145)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5081)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
            at dalvik.system.NativeStart.main(Native Method)

A: The library should not be in the JNI folder, only your source. The actual library should be in the libs/armeabi, and should be named in your case libnativetester-jni.so

A: [For More Clear Clarification have a look at Image :1
Try this:
add following in your build.gradle (module:app)
ndk {
moduleName "nativetester-jni"
}

A: The below link is a perfectly working demo.
http://androidwarzone.blogspot.in/2011/12/ffmpeg4android.html
Please follow step which is mentioned in above link.
Because i already implemented video compression and making video by merging images using above link.
Hope it will help you out.


text:
Q: Compare line by line two files with multiple columns using bash using comperatives I have two files:
file1:
a b 30 d
a b 50 d

and file2:
a b 20 d
a b 60 d

the preferred output file file_output:
a b 20 d
a b 50 d

I want to compare each file line by line and I want to print in the output file,  the line in which the number in the 3rd column is smaller using awk.
I tried something like:
awk '  NR==FNR { arr[$3];next} arr[$3] < $3 ' file1 file2 > file_output

but it prints only the smaller for file1 and not for file2

A: awk 'FNR==NR {f3[FNR]=$3;a[FNR]=$0;next} FNR in a {print ($3<f3[FNR])?$0:a[FNR]}' file1 file2


text:
Q: Rails 3 company account with many users, restrict access to data I'm wondering about the best way to structure authentication/authorization in my app. I want to have

*

*many company accounts, possibly using subdomains

*account has many users

*and users can only access records that were created by themselves or another user with the same account.
The research I've done provides lots of mix n' match ideas for combining devise / cancan / authlogic in weird and wonderful ways, but I've yet to find anything which shows me the best way to restrict user access to data within the same model.
So for instance:

Account 1: Eurasia
User 1: Bob
User 2: Jim

Account 2: Eastasia
User 1: Dave
User 2: Alan

Isbn 1: account_id is 1
Isbn 2: account_id is 2

How do I make sure Bob can't access or crud Isbn 2?
///update
Of course, now I've posted this, my google fu has kicked in and I've found the readme from RyanB for CanCan 2.0, which seems perfect:
> Resources

What if you need to change authorization based on a model's
  attributes? You can do so by passing a hash of conditions as the last
  argument to can. For example, if you want to only allow one to access
  projects which he owns you can set the :user_id option.

A: I'd suggest using CanCan for authorization.
Your Ability model would look something like
can :manage, :isbn do |isbn|
  isbn.account == current_user.account
end

Then you can use conditionals like can? :manage, @post in your Controller/Views.

A: You should have a look at https://github.com/stffn/declarative_authorization I think that one do exactly as you're asking for (you can limit access to certain records)
so, in your example you could set up the authorization with something like this:
has_permission_on :isbn do
    to :manage
    if_attribute :account_id => is_in {user.account_ids}
end

A: Have you looked at XACML? It's a policy-based, declarative framework for authorization. It's also a standard from OASIS.
With XACML you can take any attributes you need (user, resource, action, or context attributes) and express the use case that you have.
Your initial requirement was

users can only access records that were created by themselves or another user with the same account.

In XACML that would become the following policy:

A user can access a record if and only if the record.owner==user.id OR
  user.accountId==record.accountId

That's all! XACML's architecture defines the policy enforcement point (PEP) which is the component that protects your app/data and sends the authorization request to the policy decision point (PDP).
The PEP says: "Can Alice access record #123?"
The PDP checks Alice's account Id and the record's account id as well as owner.
The PDP eventually returns a "Permit" or a "Deny".
HTH


text:
Q: Flask app can't load CSS file from static folder So my file directory looks like this:
/templates
--base.html
/static
--/css
----base.css

In the  of my base.html file I have this line:
<link rel="stylesheet" href="{{ url_for('static', filename='css/base.css') }}">

However, when I run the app the base.css file isn't applied to the base.html page. In my browser I get the following error in the console:
GET http://0.0.0.0:8081/static/css/base.css net::ERR_ABORTED 404 (NOT FOUND)

I've already tried clearing my browser cache, hard refreshing the page, and restarting the app, but it still doesn't work.

A: I've figured out the solution. I just needed to add the following to my __init__.py file:
package_dir = os.path.dirname(
    os.path.abspath(__file__)
)
static = os.path.join(
    package_dir, "static"
)
app.static_folder=static


text:
Q: c# How to apply empty cell by using StringBuilder I am filling excel cells with StringBuilder with codes below.
System.Text.StringBuilder sr = new System.Text.StringBuilder();
sr.Append("Value1" + "$");
sr.Append("$"); //I jump to next cell here with null value.
sr.Append("Value2" +"$");

string[] array = sr.ToString().Replace("\r\n", string.Empty).Split('$');

for (int i = 0; i < dizi.Length; i++)
{
Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)xws.Cells[StartRow,StartCol + i];
myRange.Value2 = array[i];
}

I use "$" and split it for leaving empty cell and jump to next cell. But it creates whitespace.
How can i jump to next cell without adding whitespace?

A: This is a very simple answer -- just run this check after you get myRange:
  if( !String.IsNullOrEmpty( array[i] ) )
  {
       myRange.Value2 = array[i];
  }

You just want to prevent setting the text if it's empty, right?  Simple.


text:
Q: Uploading file onto apache server using httppost I am currently trying to upload file / images on to my apache server from AVD. I'm not getting any errors when i execute my code, but image is not uploaded to the server. I've changed permission of the folder on the apache server which is
http://10.0.2.2/images to writable and editable by other users. I am having trouble with this, please help. Follow is my code
This code gets the image and decode into bitmap.
   bmp = BitmapFactory.decodeFile(filePath);

Following is code that i run to upload files to the server
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Bitmap tmpbmp = bmp;
tmpbmp.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(url);
ByteArrayBody bab = new ByteArrayBody(data, "test.jpg");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("uploaded", bab);
reqEntity.addPart("photoCaption", new StringBody("aaaa"));
postRequest.setEntity(reqEntity);
HttpResponse httpResponse = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new  InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();

            while ((sResponse = reader.readLine()) != null) {
                s = s.append(sResponse);
            }

            Log.i("wi", "Response: " + s);

        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            Log.i("wi", "Encoding failed: " + e);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            Log.i("wi", "client protocol exception!: " + e);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            Log.i("wi", "IO Exception!: " + e);
        }

And i am getting response from Log.i("wi", "Response: " + s); =
    Response: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Index of /images</title>
Index of /images

 Parent Directory

It hasn't uploaded the file.

A: I am using Apache's commons-net-ftp library to upload my song file to the server...i am giving you the code....Try using this..
 import java.io.File;

    import java.io.FileInputStream;

    import java.io.IOException;

    import org.apache.commons.net.ftp.FTP;

    import org.apache.commons.net.ftp.FTPClient;

    import android.util.Log;

    public class MyOwn {

        public void goforIt(){

            FTPClient con = null;

            try
            {
                con = new FTPClient();
                con.connect("www.mysamle.net");                 // Its dummy Address

                if (con.login("uju495", "Stevejobs!!"))
                {
                    con.enterLocalPassiveMode();                   // Very Important

                    con.setFileType(FTP.BINARY_FILE_TYPE);        //  Very Important
                    String data = "/sdcard/Vivekm4a.m4a";

                    FileInputStream in = new FileInputStream(new File(data));
                    boolean result = con.storeFile("/Ads/Vivekm4a.m4a", in);
                    in.close();
                    if (result) Log.v("upload result", "succeeded");
                    con.logout();
                    con.disconnect();
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }

    }

A: It seems that server is returning directory listing. You need to code a server side script to receive the file. Have you done this?
There is an example here:
http://getablogger.blogspot.fi/2008/01/android-how-to-post-file-to-php-server.html


text:
Q: Dark Souls 3: Special ability / parry (L2 on ps4) sometimes triggers unintentionally. Why? On a Dark Souls 3 for ps4 (latest patch but it's always happened), if you're locked onto an enemy, sometimes hitting circle (to roll) causes your character to parry rather than roll if a shield is equipped.
This happens for all of the weapons I've used but it's not exclusively a parry thing- whatever your L2 trigger does (default control layout- it's the Parry button), sometimes will trigger randomly in fights. Sometimes not even in fights.
Why is this happening and how can I stop it? Has anyone else experienced this?
It's infuriating.
Edit:
I've further refined this to a specific, easily reproducible example.
If you equip the Deep Battle Axe, pressing up and circle at the same time will cause the action of L2 happen.

https://www.reddit.com/r/darksouls3/comments/4k063z/not_hitting_l2_but_powering_upparrying_somehow/
Edit 2:
Ok this just happens when you press L3.
Still. How do you turn it off?

A: Controller was messed up for some reason.


text:
Q: Return a list from the function using OUT parameter I would like to create a CMake function as:
function(test src_list dst_list)
# do something
endfunction()

usage:
test(${my_list} chg_list)

It means, my_list is a list with several fields, and chg_list will receive a list modified inside test function.
How can I create a function in CMake to do that?

A: Check that inside your function you are set()ing not dst_list but ${dst_list}. You need this to return data to the parent scope.

A: In CMake, functions have their own scope, and by default, all modification of variables are local, unless you pass CACHE or PARENT_SCOPE as parameter to set. Inside a function, if you want to modify a variable in the scope of the caller, you should use:
set(${dst_list} <something> PARENT_SCOPE)

See documentation:

A function opens a new scope: see set(var PARENT_SCOPE) for details.

A: Here's how I solved a similar problem which was marked a duplicate of this question. This function takes a string BinaryName and adds it to the list OutVariable which is available in the parent scope. If the list is not defined it is created. I use this strategy for creating new test targets and adding the name of these targets to a list of targets in the main scope.
Thanks to @Tsyvarev for the comments that lead me to figure this out.
function(AddToListFromFunction BinaryName OutVariable)
    if ("${${OutVariable}}" STREQUAL "")
        message(STATUS "1")
        set(${OutVariable} ${BinaryName} PARENT_SCOPE)
        message(STATUS "OutVariable: ${OutVariable} ${${OutVariable}}")
    else ()
        message(STATUS "2")
        set(${OutVariable} "${${OutVariable}}" "${BinaryName}" PARENT_SCOPE)
    endif ()
endfunction()
AddToListFromFunction(MyBinary1 MyTests)
AddToListFromFunction(MyBinary2 MyTests)
message(STATUS "MyTests Variable:  ${MyTests}")


text:
Q: iPhone, C/objC: getting hostname (not by resolving from IP) by hooking into system wide functions? I'm currently writing an MobileSubstrate plugin (code injection for iPhone). It gets the hostname by hooking into connect() and this piece of code:
#ifndef   NI_MAXHOST
#define   NI_MAXHOST 1025
#endif

int error;

 char hostname[NI_MAXHOST] = "";

 error = getnameinfo(serv_addr, addrlen, hostname, NI_MAXHOST, NULL, 0, 0);

 if (error !=0) {
  ALogTCP(@"coudldn't resolve hostname or internal connect");

  return orig__connect(sockfd, serv_addr, addrlen);
  }

 if (error == 0) {
  ALogTCP(@"hostname: %s", hostname);
  NSString *hostFirst = [NSString stringWithCString:hostname];
}

Now I've noticed that some hostnames won't get resolved properly (wrong host: like connect.xyz.com instead of irc.xyz.com)  (depending on the DNS Server).
I'm not very used to all the networking functions and an extensive search didn't turn up any solution.:
I'm thinking about hooking into a function which is responsible for all hostname->IP "conversions", getting the hostname and use it later in the above code. Is there such a function? and how is it called?
Thank you very much in advance.

A: this is how I finally did it, took me only about 7 hours to figure it out :D

*

*hooking into CFHostCreateWithName(CFAllocatorRef *allocator, CFStringRef *hostname)

*after that I use gethostbyname to get the IP.
now I can compare that information with the one I retrieve by hooking into connect()


text:
Q: HTACCESS setting HTTPS as default, so redirect to / will skip the first HTTP redirect I have a simple htaccess redirect rule:
RewriteRule ^directory$     /   [R=301,L]

Which currently does the following redirect structure:
https://mywebsite.com/directory ->  http://mywebsite.com->  https://mywebsite.com
(notice the HTTPS vs HTTP).
The 2nd redirect is due to rule set to handle HTTP->HTTPS redirection:
RewriteCond %{HTTP_HOST} !mywebsite.com$ [NC]
RewriteRule ^(.*)$ https://mywebsite.com/$1 [L,R=301]

RewriteCond %{REQUEST_URI} !\.(jpg|png|gif|bmp)$ [nc]
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^(.*)$ https://%{SERVER_NAME}/$1 [R=301,L]

But I would like to avoid that double step. How do I set HTTPS as the default for htaccess?

A:
How do I set HTTPS as the default for htaccess?

Just use https:// URL in redirect:
RewriteRule ^directory/?$ https://%{HTTP_HOST}/ [R=301,L,NE,NC]


text:
Q: accessing user's email with a discord bot I created a discord bot that needs to retrieve the user's email to perform some task. However, after I have changed the OAuth scope to email, my returned user property still doesn't have a email property.
this is my sample authorization URL:
https://discord.com/oauth2/authorize?client_id=123456789&scope=email%20bot&permissions=268435506
and this is my test function:
bot.on("message", (msg) => {
console.log(msg.member.user);});

My returned user does not even have a email property.
user {
  id: '652349438404198401',
  system: null,
  locale: null,
  flags: UserFlags { bitfield: 0 },
  username: 'Geek_.0',
  bot: false,
  discriminator: '8104',
  avatar: 'acba52ce51c54dacbcb2cba257c724af',
  lastMessageID: '812447507249889300',
  lastMessageChannelID: '809526161964531766'
}


text: Q: How to stop Google Chrome from removing ../ from the requested URL? I'm testing if my application is prone to path traversal attacks, but when browsing  to localhost/browser/../123/456.txt Chrome automatically converts the URL to localhost/browser/123/456.txt. How can I prevent Google Chrome from removing the ../ part?


text:
Q: Favorite Linux Variety and why? Right now I have Fedora dual booted with Windows 7. The reasoning behind that is just because windows was the first OS I ever used and has some essential software, and Fedora is the first linux distribution I tried, but I would like to hear the argument for other distros, as I may be looking to switch.
Thanks ahead of time.

A: Ubuntu.  This is currently the most popular distribution of linux and as such comes with many advantages.  There is much more available help for this distribution for those new to linux than I've seen in with other distribution's support.  Also, it is more user friendly (read: more gui) than most distros (though I use the command line for everything, which works just as well).  When I encounter a problem it is usually a simple google search away from an answer.  I don't just use it because it is easy (I used gentoo before this) or the most popular (I'd use windows if I wanted something popular), but because of the many other advantages from using such a highly used distro of quick support and good stability.

A: Linux from Scratch is a good way to really get to know Linux.

A: Debian 5.0
One of the most stable thing on Earth.

A: I spent a few months looking at the various distributions available, I literally went through the top 10 at Distrowatch and a few more besides. In the end it came down to two, Fedora and OpenSUSE.
for me, the ultimate choice is openSUSE. It's the distribution that gave me the least trouble, provided the best support, through their excellent forums and it's the one I feel most comfortable using.

A: ArchLinux is my OS of choice at the moment, 'cause it comes with just the essential, then is up to the user.


text:
Q: Sat4J Running out of heap space I am trying to solve a partial weighted maximum satisfiability problem using the SAT solver, SAT4J.
My .wcnf file is large, it contains about a million constraints.
When I run the solver,
I get the following as part of the output (OutOfMemoryError : Java heap space) :
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at org.sat4j.minisat.constraints.cnf.WLClause.<init>(WLClause.java:67)
at org.sat4j.minisat.constraints.cnf.LearntWLClause.<init>(LearntWLClause.java:38)
at org.sat4j.pb.constraints.UnitBinaryWLClauseConstructor.constructLearntClause(UnitBinaryWLClauseConstructor.java:66)
at org.sat4j.pb.constraints.AbstractPBClauseCardConstrDataStructure.constructLearntClause(AbstractPBClauseCardConstrDataStructure.java:197)
at org.sat4j.pb.constraints.AbstractPBClauseCardConstrDataStructure.createUnregisteredClause(AbstractPBClauseCardConstrDataStructure.java:75)
at org.sat4j.minisat.core.Solver.analyze(Solver.java:614)
at org.sat4j.minisat.core.Solver.search(Solver.java:1245)
at org.sat4j.minisat.core.Solver.isSatisfiable(Solver.java:2018)
at org.sat4j.tools.SolverDecorator.isSatisfiable(SolverDecorator.java:114)
at org.sat4j.tools.SolverDecorator.isSatisfiable(SolverDecorator.java:114)
at org.sat4j.pb.PseudoOptDecorator.admitABetterSolution(PseudoOptDecorator.java:177)
at org.sat4j.pb.PseudoOptDecorator.admitABetterSolution(PseudoOptDecorator.java:170)
at org.sat4j.ILauncherMode$2.solve(ILauncherMode.java:311)
at org.sat4j.AbstractLauncher.solve(AbstractLauncher.java:278)
at org.sat4j.AbstractLauncher.run(AbstractLauncher.java:245)
at org.sat4j.maxsat.GenericOptLauncher.main(GenericOptLauncher.java:229)

That is, an out of heap space error. How do I increase the size of the heap space and what is a suitable value to increase it to?
This is how I invoke the sat4j solver on my constraint file constraints.wcnf:
/usr/bin/java -jar sat4j-maxsat.jar constraints.wcnf
Thanks

A: Just use
java -Xms2g -Xmx2g -jar sat4j-maxsat.jar constraints.wcnf

for instance to use 2Gb of heap memory.


text:
Q: How do you intercept WSDL requests in CXF? Backstory:
I have a WSDL that was created by the customer (non-negotiable) that mixes several web standards into a single service. This one soap service has four soap ports that refer to bindings in referenced (wsdl:import) WSDL files that import XSDs resulting in a dependency tree that is significantly complex.
Since this is done by imports, the top level WSDL isn't that big. WSDL2Java and wsimport choke on it, but I have a library of the schemas compiled into JAXB objects to work with. So I created a CXF service that has all of the required operations and I was able to test it with SoapUI (it imported the top level WSDL fine since it didn't have to make java classes).
Since all the soap ports point to the same address, and that service handles all the operations from the various ports, the client doesn't know that the server thinks all the operations belong to the same port.
Problem:
This breaks down when it comes to CXF generating the WSDL. It puts all the operations on one port with the same namespace. In the customer provided WSDL, the service, ports and bindings are not all in the same namespace. I have tried to supply the service with the WSDL using the @WebService(wsdlLocation="") annotation, but it tries to parse it and match it to the code (as it would in a sane world).
Question:
I would like to intercept/override the http://example.com/service?wsdl operation and return the customer provided wsdl. Is there a way to do this in CXF?

A: I ended up splitting the ports out into separate services, but I still needed a custom WSDL that had info for all the ports. The way to do this with CXF is to create an interceptor.
I followed the example of the CXF interceptor that regularly handles WSDL generation: http://grepcode.com/file/repo1.maven.org/maven2/org.apache.cxf/cxf-rt-frontend-simple/2.4.0/org/apache/cxf/frontend/WSDLGetInterceptor.java. I read in my custom WSDL and replace the placeholder hostname with the hostname that comes from the request URL.
You need to then add the custom interceptor when you make your service (I use spring for my configuration). More info on that at http://cxf.apache.org/docs/interceptors.html.


text:
Q: kivy says I have multiple screens with the same name Kivy keeps telling me that I have multiple screens with the same name for all my screens and I don't have and i think that's why some code I am trying to run doesn't seem to work. need assistance.
here's my Window manager
<ScreenManager>:
    id: window manager
    Homepage:
        id: home
        name: "home"
    SignUpWindow:
        id: create
        name: "create"
    SignUp:
        id: signup
        name: "signup"
    LoginWindow:
        id: login
        name: "login"
    ProjectListScreen:
        id: project_list_screen
        name: "project_list_screen"
    ApplyPage:
        id: applyingpage
        name: "applyingpage"
    MainWindow:
        id: main
        name: "main"
    NewProjectScreen:
        id: placements
        name: "placements"
    ProfileWindow:
        id: page
        name: "page"

A: Kivy automatch the classes that inherit the App class with it's class's name. For example if your class that inherit the App class is class TestApp(App) :  it will be matched with test.kv or Test.kv
if you also used builder to load kv file (for example with open("test.kv") as kvfile:)  as a result, you would load kvfile twice. so you're system tell you that you have multiple screen name.
solution 1. change your kv file name.


text:
Q: How to identify unknown date time format which is five digits followed by twelve digits, and deal with in NodeJs Checked several other Stack Overflow Questions, searched for a while through all unknown date format questions, none I found look like this. I need to deal with this type of date time format in Javascript, which Google Sheets and LibreOffice Calc both are able to recognize and parse as 5/24/2023 10:00 for this example.
45070.416666666664 <- what date time format is this?

A: In GSheets (as others), change format to date.
In app script, use
function myFunction() {
  const sh = SpreadsheetApp.getActiveSheet()
  const value = sh.getRange('C1').getValue()
  console.log (Utilities.formatDate(value, Session.getScriptTimeZone(), "MM/dd/yyyy HH:mm"))
}


text:
Q: GDB: Insert a breakpoint on external file using address i'm just learning how to use GDB.
I'm trying to set a breakpoint for an external binary that is called by my program. I do not have the source of the other binary, so I can't compile it with the -g option.
Both my file and the other (a Framework) are written in Objective-C.
I managed to find the address of the line where I want to set my break, but of course GDB so not allow to use that, since I'm working with my file.
How can I tell GDB to set a breakpoint on that binary file, on that address?

A: To break at a specific address you can use:
break *0x12345

The "*" tells gdb to interpret the remainder of the "linespec" (see the manual) as an expression.
Often, even without debug info, you can still set breakpoints by name.  This will work as long as there are "linker" symbols of whatever flavor in the library, and as long as you know the linkage name.


text:
Q: Can't get toLocaleString() to work I'd like to know how to use toLocaleString() in these two small scripts. I've tried different takes, but nothing seem to work. Could anyone please explain what I'm doing wrong?
$(window).load(function(){
  $('input[type="radio"]').change(function () {
    var total_span = 0;
    $('input[type="radio"]').each(function () {
      total_span += this.checked && +this.value;
    });

   $({counter: + $('#total').text()}).animate({counter: total_span},{
     duration: 1000,
     easing: 'swing',
     step: function () {
       $('#total').text(Math.floor(this.counter));
       $('#total-2').text(Math.floor(this.counter));
     },
     complete : function(){
       $('#total').text(total_span.toLocaleString("sv-SE"));
       $('#total-2').text(total_span.toLocaleString("sv-SE"));
     }
   });
  });
});

and
$(document).ready(function () {
  $(':radio').change(function (e) {
    //clear the div
    $('#final').html('');
    //update the div
    $(':radio:checked').each(function (ind, ele) {
        $('#final').append('

' + $(ele).attr("name") + ':
' + $(ele).attr("id") + '
' + $(ele).val().toLocaleString("sv-SE") + ':-

');
    });
  });
});

I'd be very grateful if someone could please let me know how to solve this?
Many thanks in advance!

A: Perhaps you mean this? toLocaleString seems to work as expected

$(function() {
  $('input[type="radio"]').change(function() {
    var total_span = 0;
    $('#final').empty(); // same as .html("")
    $('input[type="radio"]:checked').each(function() { // Only take the checked radios
      var val = +this.value; // the + makes the value numeric if it is a number
      val = isNaN(val) ? 0 : val; // check it IS a number
      total_span += val; // and add it
      $('#final').append('

' + this.name + ':
' + this.id + '
' + val.toLocaleString("sv-SE") + ':-

');
    });
    $({
      counter: +$('#total').text()
    }).animate({
      counter: total_span
    }, {
      duration: 1000,
      easing: 'swing',
      step: function() {
        $('#total').text(Math.floor(this.counter));
        $('#total-2').text(Math.floor(this.counter));
      },
      complete: function() {
        $('#total').text(total_span.toLocaleString("sv-SE"));
        $('#total-2').text(total_span.toLocaleString("sv-SE"));
      }
    });
  });
});

100.01 <input type="radio" name="rad1" id="rad1" value="100.01" />

200.02 <input type="radio" name="rad2" id="rad2" value="200.02" />

300.03 <input type="radio" name="rad3" id="rad3" value="100.03" />

Total
Total-2


text:
Q: Grouping map by similar (not identical) keys I have
Map<Foo, Bar> m;
m.put(foo1, bar1);
m.put(foo2, bar2);

a method to check if keys are similar:
boolean isSimilar(Foo foo1, Foo foo2);

I would like to group the values of entries if keys are similar.
If foo1 is similar to foo2 I would like to group value into a new map:
Map<foo1, {bar1,bar2}>

Is it possible to use a groupingBy collector where the grouping is not performed on identical keys but on similar keys?
I would like to run this process in parallel. Any suggestion is welcome.
Thanks.


text:
Q: XML DTD Schema, can I create an attribute with other's value? Lets say I have an xml element as follows:
<item name="ItemName" id="itemID" .... />

Now, lets say I have some attributes which I already handle / validate with my dtd ATTLIST schema.
I want it to do the following:
if attribute 'id' not exists, set id=_name_attribute's_value, or in simple demonstration:
<item name="itemName" .... />

will turn into :
<item name="itemName" id="itemName" .... />

Is it possible?

A: You can provide a default value in the ATTLIST. Example:
<?xml version="1.0"?>
<!DOCTYPE note [
    <!ELEMENT note (to,from,heading,body)>
    <!ATTLIST note id CDATA "myid">
    <!ELEMENT to (#PCDATA)>
    <!ELEMENT from (#PCDATA)>
    <!ELEMENT heading (#PCDATA)>
    <!ELEMENT body (#PCDATA)>
]>
<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend</body>
</note>

If you display this file in e.g. IE, it will look like

As you see the id attribute incl. value is added. So technically this is possible, however keep in mind that an id attribute should be unique, this is what the DTD can not deliver.


text:
Q: PyFlink - Issue using Scala UDF in JAR I'm trying to register a Scala UDF in Pyflink using an external JAR as follows, but get below error.
Scala UDF:
package com.dummy

import org.apache.flink.table.functions.ScalarFunction

class dummyTransform(factor: Int) extends ScalarFunction {
  def eval(s: String): Int = {
    s.hashCode()
  }
}

build.sbt:
name := "hello_scala_for_flink"
version := "0.1"
scalaVersion := "2.12.11"
libraryDependencies += "org.apache.flink" % "flink-table-common" % "1.11.2" % "provided"

assembly.sbt:
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.5")

Scala project structure:
hello_scala_for_flink/
  project/
  src/
    main/
      resources/
        scala/
          com.dummy/
            dummyTransform
            hello_scala
    test
  target/
  build.sbt

shell:
cd hello_scala_for_flink
sbt assembly
cp ./target/scala-2.12/hello_scala_for_flink-assembly-0.1.jar /Users/py-r/opt/anaconda3/envs/venv_pyflink_37/lib/python3.7/site-packages/pyflink/lib/

Python:
from pyflink.dataset import ExecutionEnvironment
exec_env = ExecutionEnvironment.get_execution_environment()
#exec_env = StreamExecutionEnvironment.get_execution_environment()

exec_env.set_parallelism(1)
t_config = TableConfig()

table_env = BatchTableEnvironment.create(exec_env, t_config)
table_env.register_java_function("hash_code","com.dummy.dummyTransform")

Error (incl. after restarting Anaconda):
Py4JJavaError: An error occurred while calling o12.newInstance.
: java.lang.InstantiationException: com.dummy.dummyTransform
    at java.base/java.lang.Class.newInstance(Class.java:598)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.apache.flink.api.python.shaded.py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at org.apache.flink.api.python.shaded.py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at org.apache.flink.api.python.shaded.py4j.Gateway.invoke(Gateway.java:282)
    at org.apache.flink.api.python.shaded.py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at org.apache.flink.api.python.shaded.py4j.commands.CallCommand.execute(CallCommand.java:79)
    at org.apache.flink.api.python.shaded.py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: java.lang.NoSuchMethodException: com.dummy.dummyTransform.<init>()
    at java.base/java.lang.Class.getConstructor0(Class.java:3427)
    at java.base/java.lang.Class.newInstance(Class.java:585)
11 more

Versions:
jdk = 1.8.0_151.jdk
scala = 2.12.11
python = 3.7
apache-beam = 2.19.0
apache-flink = 1.11.2

Any idea what the issue might be ?
Thanks for your support

A: Looks like I found the issue myself. Apparently only a class instantiation was required in above code:
class dummyTransform(factor: Int) extends ScalarFunction {
  def eval(s: String): Int = {
    s.hashCode() * factor
  }
  def this() = this(1)
}

Also, I changed to Scala 2.11.12 due to another error. Now everything seems to work: awesome !


text:
Q: Why when i create the bitmap it's empty all white? private Bitmap CropImage()
        {
            Bitmap pic = pictureBoxSnap.Image as Bitmap;
            Bitmap cropped = new Bitmap(rect.Width, rect.Height);

            using (Graphics g = Graphics.FromImage(cropped))
            {
                g.DrawImage(pic, new Rectangle(0, 0, rect.Width, rect.Height),
                             rect, GraphicsUnit.Pixel);
            }
            pic.Save(@"c:\temp\testingitimage.jpg");
            cropped.Save(@"c:\temp\testingitimage1.bmp");
            return cropped;

        }

I added this two lines of Save to test what i get. The first one pic i see the correct image that is in the pictureBox.
But the second one cropped is all white and empty.
And i call this method from the pictureBox paint event:
private void pictureBoxSnap_Paint(object sender, PaintEventArgs e)
        {

            if (pictureBoxSnap.Image != null)
            {
                {
                    if (ClearGraphics == false)
                    {
                        if (cropRect == false)
                        {
                            if (rectangles[listBoxSnap.SelectedIndex] != Rectangle.Empty)
                            {
                                e.Graphics.DrawRectangle(Pens.Firebrick, rectangles[listBoxSnap.SelectedIndex]);
                            }
                        }
                        else
                        {
                            if (rect.Width > 10 && rect.Height > 10)
                            {
                                e.Graphics.DrawRectangle(Pens.Gray, rect);
                                pictureBoxSnap.Image = CropImage();
                                Image img = CropImage();
                                img.Save(@"c:\temp\testimageing.jpg");
                            }
                        }
                    }
                }
            }
        }

I used a breakpoint on the: e.Graphics.DrawRectangle(Pens.Gray, rect); and rect is not empty ( rect is Rectangle i draw on the pictureBox then when i click on a button it's making validate for the pictureBox).
I also did a save here too and testimageing i see it black on the hard disk but when i edit it with Paint i see it's white empty.
For exmaple when i draw a rectangle on the pictureBox then i use a breakpoint in the CropImage method i see that the variable rect is for example: X = 136 Y = 149 Width = 131 Height = 106
Also in the paint event this rect variable have the same values.
And the pictureBox size is: 640x480
And the pictureBox property SizeMode is set to: zoom
Wo why i get empty white image ? And not the cropped rectangle with the part of the image inside ?
EDIT:
This is the code im using now:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using DannyGeneral;
using System.Diagnostics;

namespace MinimizeCapture
{
    public partial class Form1 : Form
    {
        Boolean bHaveMouse;
        Point ptOriginal = new Point();
        Point ptLast = new Point();
        bool cropRect;
        Bitmap cloneBitmap;
        Rectangle recttest;
        private Rectangle Rect;
        private Rectangle[] rectangles;
        private Rectangle RectClone;
        private bool btn = false;
        private Point RectStartPoint = Point.Empty;
        private Point RectEndPoint = Point.Empty;
        private Brush selectionBrush = new SolidBrush(Color.Red);
        private Pen pen;
        private string selectedIndex;
        private List<string> drawnItems = new List<string>();
        private bool ClearGraphics;

        public Form1()
        {
            InitializeComponent();

            cropRect = false;
            var windows = OpenWindowGetter.FindWindowsWithText();
            ClearGraphics = false;
            this.DoubleBuffered = true;
            btn = false;
            pen = new Pen(selectionBrush);
            buttonSnap.Enabled = false;
            backgroundWorker1.RunWorkerAsync();
        }

        private void buttonSnap_Click(object sender, EventArgs e)
        {
            ClearGraphics = true;
            this.listBoxSnap.Items.Clear();
            this.pictureBoxSnap.Image = null;
            backgroundWorker1.RunWorkerAsync();
        }

        private void listBoxSnap_SelectedIndexChanged(object sender, EventArgs e)
        {

            WindowSnap snap = this.listBoxSnap.SelectedItem as WindowSnap;
            selectedIndex = this.listBoxSnap.SelectedIndex.ToString();
            this.pictureBoxSnap.Image = snap.Image;
            for (int i = 0; i < rectangles.Length; i++)
            {
                if (rectangles[i] != RectClone)
                {
                    ClearGraphics = false;
                }
                else
                {
                    ClearGraphics = true;
                }
            }

        }

        private void checkBoxForceMDI_CheckedChanged(object sender, EventArgs e)
        {
            WindowSnap.ForceMDICapturing = (sender as CheckBox).Checked;
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            listBoxSnap.Invoke(new MethodInvoker(delegate { this.listBoxSnap.Items.Add("Minimized Windows"); }));
            listBoxSnap.Invoke(new MethodInvoker(delegate { this.listBoxSnap.Items.AddRange(WindowSnap.GetAllWindows(true,true).ToArray()); }));
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {

        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            rectangles = new Rectangle[listBoxSnap.Items.Count];
            buttonSnap.Enabled = true;
        }

        private void pictureBoxSnap_Paint(object sender, PaintEventArgs e)
        {

            if (pictureBoxSnap.Image != null)
            {
                {
                    if (ClearGraphics == false)
                    {

                            if (rectangles[listBoxSnap.SelectedIndex] != Rectangle.Empty)
                            {
                                e.Graphics.DrawRectangle(Pens.Firebrick, rectangles[listBoxSnap.SelectedIndex]);
                            }

                    }
                    if (cropRect == true)
                    {
                        if (recttest.Width > 10 && recttest.Height > 10)
                        {
                            //e.Graphics.DrawRectangle(Pens.Gray, recttest);
                            e.Graphics.Clear(Color.White);
                            /*pictureBoxSnap.Image = CropImage();
                            Image img = CropImage();
                            img.Save(@"c:\temp\testimageing.jpg");*/

                        }
                    }
                }
            }
        }

        private void pictureBoxSnap_MouseMove(object sender, MouseEventArgs e)
        {

            if (btn == true)
            {
                ClearGraphics = false;
                RectEndPoint = e.Location;
                int currentindex = listBoxSnap.SelectedIndex;
                rectangles[currentindex] = RectClone;
                Rect = getRect(RectStartPoint, RectEndPoint);
                RectClone = Rect;
                pictureBoxSnap.Invalidate();
            }

            Point ptCurrent = new Point(e.X, e.Y);
        // If we "have the mouse", then we draw our lines.
            if (bHaveMouse)
            {
                // If we have drawn previously, draw again in
                // that spot to remove the lines.
                if (ptLast.X != -1)
                {
                    MyDrawReversibleRectangle(ptOriginal, ptLast);
                }
                // Update last point.
                ptLast = ptCurrent;
                // Draw new lines.
                MyDrawReversibleRectangle(ptOriginal, ptCurrent);
            }
        }

        private void pictureBoxSnap_MouseDown(object sender, MouseEventArgs e)
        {
            RectStartPoint = e.Location;
            btn = true;
            Rect = Rectangle.Empty;
            RectClone = Rectangle.Empty;

            bHaveMouse = true;
            // Store the "starting point" for this rubber-band rectangle.
            ptOriginal.X = e.X;
            ptOriginal.Y = e.Y;
            // Special value lets us know that no previous
            // rectangle needs to be erased.
            ptLast.X = -1;
            ptLast.Y = -1;
        }

        private void pictureBoxSnap_MouseUp(object sender, MouseEventArgs e)
        {
            recttest = rectangles[listBoxSnap.SelectedIndex];
            ClearGraphics = false;
            btn = false;
            RectEndPoint = e.Location;
            pictureBoxSnap.Invalidate();
            int currentindex = listBoxSnap.SelectedIndex;
            rectangles[currentindex] = RectClone;

            // Set internal flag to know we no longer "have the mouse".
            bHaveMouse = false;
            // If we have drawn previously, draw again in that spot
            // to remove the lines.
            if (ptLast.X != -1)
            {
                Point ptCurrent = new Point(e.X, e.Y);
                MyDrawReversibleRectangle(ptOriginal, ptLast);
            }
            // Set flags to know that there is no "previous" line to reverse.
            ptLast.X = -1;
            ptLast.Y = -1;
            ptOriginal.X = -1;
            ptOriginal.Y = -1;
            pictureBoxSnap.Invalidate();
        }

        Rectangle getRect(Point p1, Point p2)
        {
            Point p = new Point(Math.Min(p1.X, p2.X), Math.Min(p1.Y, p2.Y));
            Size s = new Size(Math.Abs(p1.X - p2.X), Math.Abs(p1.Y - p2.Y));
            return new Rectangle(p, s);
        }

        private void ConfirmRectangle_Click(object sender, EventArgs e)
        {
            ConfirmRectangle.ForeColor = Color.Red;
            ConfirmRectangle.Enabled = false;
            StreamWriter w = new StreamWriter(@"c:\temp\Settings.txt", true);
            w.WriteLine("Rectangle Location: " + RectClone.Location + " Rectangle Size: " + RectClone.Size + " Selected Index: " + selectedIndex);
            textBoxIndex.Text = selectedIndex.ToString();
            w.Close();
            cropRect = false;
            //pictureBoxSnap.Invalidate();
            Image img = CropImage();
            img.Save(@"c:\temp\testimageing.jpg");
            pictureBoxSnap.Image = img;

        }

        // Convert and normalize the points and draw the reversible frame.
        private void MyDrawReversibleRectangle(Point p1, Point p2)
        {
            Rectangle rc = new Rectangle();
            // Convert the points to screen coordinates.
            p1 = pictureBoxSnap.PointToScreen(p1);
            p2 = pictureBoxSnap.PointToScreen(p2);
            // Normalize the rectangle.
            if (p1.X < p2.X)
            {
                rc.X = p1.X;
                rc.Width = p2.X - p1.X;
            }
            else
            {
                rc.X = p2.X;
                rc.Width = p1.X - p2.X;
            }
            if (p1.Y < p2.Y)
            {
                rc.Y = p1.Y;
                rc.Height = p2.Y - p1.Y;
            }
            else
            {
                rc.Y = p2.Y;
                rc.Height = p1.Y - p2.Y;
            }
            // Draw the reversible frame.
            rect = new Rectangle(pictureBoxSnap.PointToClient(rc.Location), rc.Size);
            ControlPaint.DrawReversibleFrame(rc, Color.Gray, FrameStyle.Dashed);
        }

        Rectangle rect = Rectangle.Empty;

        private Bitmap CropImage()
        {
            //rect = recttest;
            Bitmap pic = pictureBoxSnap.Image as Bitmap;
            Bitmap cropped = new Bitmap(rect.Width, rect.Height);

            using (Graphics g = Graphics.FromImage(cropped))
            {
                g.DrawImage(pic, new Rectangle(0, 0, rect.Width, rect.Height),
                             rect, GraphicsUnit.Pixel);
            }
            pic.Save(@"c:\temp\testingitimage.jpg");
            cropped.Save(@"c:\temp\testingitimage1.bmp");
            return cropped;

        }
    }
}

Moved the CropImage call method from the paint and added it to the button click here:
private void ConfirmRectangle_Click(object sender, EventArgs e)
        {
            ConfirmRectangle.ForeColor = Color.Red;
            ConfirmRectangle.Enabled = false;
            StreamWriter w = new StreamWriter(@"c:\temp\Settings.txt", true);
            w.WriteLine("Rectangle Location: " + RectClone.Location + " Rectangle Size: " + RectClone.Size + " Selected Index: " + selectedIndex);
            textBoxIndex.Text = selectedIndex.ToString();
            w.Close();
            cropRect = false;
            //pictureBoxSnap.Invalidate();
            Image img = CropImage();
            img.Save(@"c:\temp\testimageing.jpg");
            pictureBoxSnap.Image = img;

        }

This lines:
Image img = CropImage();
img.Save(@"c:\temp\testimageing.jpg");
pictureBoxSnap.Image = img;

But what i get in the pictureBox is this:

Not sure why. The rectangle is in the position i drawed it's ok but instead showing the part of the original image cut in the rectangle it's doing like zoom in.

A: You are cropping multiple times.
pictureBoxSnap.Image = CropImage();    // First Time
Image img = CropImage();               // Second Time
img.Save(@"c:\temp\testimageing.jpg");

You just need to crop once. Here you are using same picturebox for source and for cropped image. first time when you crop then image. the cropped image will be set correctly to the picturebox. but, second time application will try to crop that image again.
You should do like this
Image img = CropImage();
img.Save(@"c:\temp\testimageing.jpg");
pictureBoxSnap.Image = img;

A: private Bitmap CropImage(){
    Bitmap pic = pictureBoxSnap.Image as Bitmap;
    Bitmap cropped = new Bitmap(rect.Width, rect.Height);

    using (Graphics g = Graphics.FromImage(cropped)){
        g.DrawImage(pic, new Rectangle(0, 0, rect.Width, rect.Height),
                         rect, GraphicsUnit.Pixel);
    }

    using (Graphics g = Graphics.FromImage(pic)){
        g.DrawImage(cropped , 136, 149, rect.Width, rect.Height);
        //Draw the rectangle
    }

    //pic.Save(@"c:\temp\testingitimage.jpg");
    //cropped.Save(@"c:\temp\testingitimage1.bmp");
    return pic;
}

valter


text:
Q: How to always run some ansible roles after previous failures? I have a set of playbooks that do look like
- name: Run test
  hosts: tester
  roles:
    - { role: setup_repos }
    - { role: setup_environment }
    - { role: install_packages }
    - { role: run_tests }
    - { role: collect_logs }

The current problem is that all over the first 4 roles we have ignore_errors: true which is not a good practice as it makes very hard to read the output and to debug.
The only reason why ignore_errors was abused was because we wanted to be able to perform the collect_logs at the end, regardless the outcome.
How can we refactor this in order to remove the ignore_errors and have a more of a fail-fast strategy.
Please note that we have lots of playbooks calling collect_logs role, so "moving code inside playbook" is not really a way to reuse it.

A: On ansible 2.4 or newer one should replace role: block with tasks like role_include or role_import, which gives you the ability to use normal logic used by tasks. You could use handlers, ignore_errors, and so on.

A: I belive handlers and notify would help you achive what you want.
You wont need to change your roles behavior (although it might be a good idea).
You should notify at the end of each of your roles, the handler would only run once.
http://docs.ansible.com/ansible/latest/playbooks_intro.html#handlers-running-operations-on-change
Also if you choose to start handleing errors you could use the --force-handlers to force handler execution even when the playbook failed.
http://docs.ansible.com/ansible/latest/playbooks_error_handling.html#handlers-and-failure


text:
Q: TabBar in a View Based Application with a UINavigationBar I am making a View Based Application for iPhone and I am trying to make a UIView with a TabBar and a NavigationBar. The TabBar needs three buttons which should switch between three different UIViews. What is the proper way to implement this?

A: Duplicate: Try refering previous post:

*

*Navigation Based Application with TabBar

*uitabbarcontroller / uitabbar in navigation based project


text:
Q: How to configure dymanic name in spring batches I have fifteen job configuration in my spring batch project. The jobs are been called from different source. That means I do not have control over the call.
Ten out of fifteen job perform the same task, therefore I want to create a single configuration file and execute all the ten jobs.
My question is :
Is it possible to dynamically change the job name in the configuration file.

A: The answer may not be what you are expecting. But I used this technique for a similar situation (not for the batch jobs, though).
You may have multiple bean definitions, pointing to same Java Class and receiving a property value different for each definition. Based on the value of jobSource, you may want perform necessary action needed for that source.

<bean id="job1" class="your.job.class.Here">
    <property name="jobSource" value="source1" />
</bean>

<bean id="job2" class="your.job.class.Here">
    <property name="jobSource" value="source2" />
</bean>

A: I created one context file with all the similar job and another file with the common bean definitions. This has helped me in reducing a lot of code works.


text:
Q: Not matching schema problems when appending list of CSV's into existing file geodatabase table? So far I have the following code for creating the FGDB table and defining fields which works just fine. But when I try to append a list of csv's to this table I always get a matching schema error.
Do you have any idea, what may be wrong? Code and csv structure posted below.
import arcpy
import os

arcpy.env.workspace = "C:\\Users\\SAMSUNG\\Desktop\\python_script"
gdb = "FileDatabase.gdb"

if arcpy.Exists(gdb):
    print "Database exists."
else:
    print "Database doesn't exist."
    fgdbPath = "C:\\Users\\SAMSUNG\\Desktop\\python_script"
    fgdbName = "FileDatabase.gdb"
    arcpy.CreateFileGDB_management(fgdbPath, fgdbName)
    print "Database has been created."

tabPath = "C:\\Users\\SAMSUNG\\Desktop\\python_script\\FileDatabase.gdb"
tab = "Table"
fullPath = tabPath + "\\" + tab

if arcpy.Exists(fullPath):
    print "FGDB table exists."
else:
    print "FGDB table doesn't exist. Table will be created."
    arcpy.CreateTable_management(tabPath, tab)
    arcpy.AddField_management (fullPath, "transect", "LONG", "", "", "", "", "", "REQUIRED")
    arcpy.AddField_management (fullPath, "point", "LONG", "", "", "", "", "", "REQUIRED")
    arcpy.AddField_management (fullPath, "Xcoord", "DOUBLE", "", "", "", "", "", "REQUIRED")
    arcpy.AddField_management (fullPath, "Ycoord", "DOUBLE", "", "", "", "", "", "REQUIRED")
    arcpy.AddField_management (fullPath, "date", "DATE", "", "", "", "", "", "REQUIRED")
    arcpy.AddField_management (fullPath, "depth", "LONG", "", "", "", "", "", "REQUIRED")
    arcpy.AddField_management (fullPath, "paramA", "DOUBLE", "", "", "", "", "", "REQUIRED")
    arcpy.AddField_management (fullPath, "paramB", "DOUBLE", "", "", "", "", "", "REQUIRED")
    arcpy.AddField_management (fullPath, "paramC", "DOUBLE", "", "", "", "", "", "REQUIRED")
    arcpy.AddField_management (fullPath, "notice", "TEXT", "", "", "", "", "", "REQUIRED")
    print "Table has been created."

For appending listed csv's I'm using the following script:
import arcpy

arcpy.env.workspace = "C:\\Users\\SAMSUNG\\Desktop\\python_script"

csvList = arcpy.ListFiles("*.csv")
arcpy.Append_management(csvList, workspace + "\\" + "FileDatabase.gdb" + "\\" + "Table", "TEST")

The csv files are without header and look like this:
1,5,504577.885850,1158507.476675,15.04.2015,40,3.56,0.007,23.34,"text"
1,6,504577.885850,1158507.476675,15.04.2015,40,3.56,0.007,23.34,"text"

A: Change the flag TEST to NO_TEST. Name your fields in the table you create field1, field2,,, fieldx rather than proper field names as your source csv has none.  You can assign field aliases instead when you create the table.


text:
Q: Post-hoc tests for MANOVA: univariate ANOVAs or discriminant analysis? I am using a MANOVA test to compare nine different dependent variables (from neuropsychological and neuropsychiatric assessment) between three groups. The output shows a significant influence from GROUP on my variables ($p < .001$).
Ofcourse, I am interested in how the three groups influence every dependent variable. I have studied Field's "Discovering Statistics Using IBM SPSS Statistics" chapter 16, and he states that the preferred post-hoc analysis is a discriminant analysis, because of the linear combination in which the dependent variables are related to group membership in a MANOVA. Discriminant analysis could account for this linear combination, so Field states.
Otherwise, I read some literature, on basic statistical sites, where is stated that I can use multiple univariate ANOVA's with Bonferroni correction, and use a post-hoc on these univariate ANOVA's when they are significant.
Which of these method's is better? That is, which will make my chance of a Type I or II error the least?

A: These two follow-up approaches have very different goals!

*

*Univariate ANOVAs (as follow-ups to MANOVA) aim at checking which individual variables (as opposed to all variables together) differ between groups.

*Linear Discriminant Analysis, LDA, (as a follow-up to MANOVA) aims at checking which linear combination of individual variables leads to maximal group separability and at interpreting this linear combination.
This question asked about one-way MANOVA with only a single factor, but see here for the [more complicated] case of factorial MANOVA: How to follow up a factorial MANOVA with discriminant analysis?
So e.g. if your individual variables are weight and height, then with univariate ANOVAs you can test if weight and height, separately, differ between groups. With LDA you can find out that the best group separability is given by, say, 2*weight+3*height. Then you can try to interpret this linear combination.
So the choice between these two follow-up approaches entirely depends on what you want to test.

Two further remarks
First, if you are "interested in how the three groups influence every dependent variable" (i.e. individual DVs are of primary interest), then you should arguably not run MANOVA at all, but go straight to univariate ANOVAs! Correct for multiple comparisons (note that Bonferroni is very conservative, you might prefer to control false discover rate instead; but see comment below for another opinion), but proceed with univariate tests. After all, nine DVs are not a lot. If, instead, you are interested in whether groups differed at all (and maybe in what respect they differed the most) but do not care so much about individual DVs, then you should use MANOVA. It all depends on your research hypothesis.
Second, it sounds though as if you might have no pre-specified hypothesis about which DVs should be influenced by group, and what exactly this influence should be. Instead, you probably have a bunch of data that you wish to explore. It is a valid wish, but it means that you are doing exploratory analysis. And in this case my best advice would be: plot the data and look at it!
You can plot a number of things. I would plot distributions of each DV for each of the three groups (i.e. nine plots; can be density plots or box plots). I would also run linear discriminant analysis (which is intimately related to MANOVA, see e.g. my answer here), project the data onto the first two discriminant axes and plot all your data as a scatter plot with different groups marked in different colours. You can project original DVs onto the same scatter plot, obtaining a biplot (here is a nice example done with PCA, but one can make a similar one with LDA too).

A: "Significant influence from group" means that $H_0: {\mu_1}=\mu_2=\mu_3$ has been rejected, where $\mu_i$ is the mean vector of the dependent variables in group $i$. This can happen if $\mu_1=\mu_2\neq \mu_3$. In this case, discriminant analysis between group 1 and 2 would fail. You would have first to decompose the overall hypothesis into $\mu_1 = \mu_2$, $\mu_2 = \mu_3$ and $\mu_1 = \mu_3$. There, of course, multiplicity adjustments (e.g. Bonferroni) are again necessary.
Even if it does not fail, discriminant analysis gives you rather estimates of the effects, not test results. If you are in fact interested in such a tool (e.g. in order to diagnose to which group a new patient would belong), discriminant analysis will of course still be necessary.
Multiplicity adjustments of the hypotheses $H_0 ^ {j}:\;\mu_1^{j}=\mu_2^{j}=\mu_3^{j}$, where $j$ denotes a dependent variable, can be done with Bonferroni-method. The interpretation of a significant result would be that in the dependent variable you identified not all groups have equal means. Usually you would want to decompose this result as well into pairwise comparisons as above. Also you have to keep in mind that it may happen that you can reject the global hypothesis but fail with the post-hoc analyses.
Your last question: As Bonferroni is quite conservative, you may consider using different methods, e.g. like in the SimComp R-package. This would estimate the unknown dependency between the variables. Said information would lead to a less conservative adjustment, thus, better power.


text: Q: How to consider interaction terms in the ridge / lasso / elastic net? I would like to ask a question about how to consider interaction terms in my penalized regression? My primary goal is to build the model to predict. I think in the conventional GLM, we run the model with only main effects firstly and then add the interactions with only significant main effects. But I am not sure how to operate in the penalized regression. Thanks.


text:
Q: How to limit CMake Xcode schemas generator to only some targets CMake 3.14 has a very useful mechanizm to automatically generate schema files for Xcode. The problem is that it creates schemas for all targets while I need scheme only for few of them. I have hundreds of targets in my projects and scrolling down the list is annoying.
My code is:
if(${CMAKE_GENERATOR} MATCHES "Xcode")
    set(CMAKE_XCODE_GENERATE_SCHEME YES)
endif()

All I want is to create only one scheme for ALL_BUILD target not for all targets.

A: Finally I've found some workaround to may problem. First I enable scheme generation for all targets as before:
set(CMAKE_XCODE_GENERATE_SCHEME YES)
then disable schemes generation for all targets in subfolder:
get_all_targets_recursive(all_subfolder_targets "subfolder")
foreach(subfolder_target ${all_subfolder_targets})
    set_target_properties(${subfolder_target} PROPERTIES XCODE_GENERATE_SCHEME NO)
endforeach()

you can find get_all_targets_recursive implementation here https://stackoverflow.com/a/62311397/5472544


text:
Q: Column value conditional on previous value in a dataframe Python I have a dataframe "bd" that looks like this:
    Unnamed: 0  timestamp   open    high    low close   volume  close_time  quote_av    trades  tb_base_av  tb_quote_av ignore  Ticker  log
0   0   17/04/2018  0.01000 0.02500 0.01000 0.02056 10026646.20 1.524010e+12    212822.90450    14612   3080879.33  65362.06898 0.0 ADABNB  0.720762
1   1   18/04/2018  0.02061 0.02227 0.02050 0.02131 6150235.16  1.524100e+12    131540.20910    8736    2932444.56  62649.93292 0.0 ADABNB  0.033400
2   2   19/04/2018  0.02126 0.02239 0.02125 0.02182 4029868.44  1.524180e+12    87958.85789 6894    1975139.34  43153.92312 0.0 ADABNB  0.026000
3   3   20/04/2018  0.02180 0.02429 0.02171 0.02400 4082134.58  1.524270e+12    94989.57750 7674    1489298.21  34675.98730 0.0 ADABNB  0.096144
4   4   21/04/2018  0.02400 0.02494 0.02031 0.02145 6363706.18  1.524360e+12    138161.60430    7733    3469179.07  74832.05245 0.0 ADABNB  -0.112329

I want the "Next Day" column to only be equal to log(-1) so the next day's log returns, if the Ticker Column is the same for both days. I tried creating a new column like this:
bd['Next Day'] = np.where(bd['Ticker'] == bd[['Ticker'](-1)], bd['log'].shift(-1))

I also tried the following:
bd['ND2'] = bd['Next Day'].apply(lambda x: bd['Next Day'] if bd['Ticker'] == bd['Ticker'](-1) else '')

But I get an error "list" object is not callable. Or "series" object is not callable in the second case
Thank you.


text:
Q: 2 nic 2 gateways I have a question.
I have a ubuntu server(GW0). It has 2 interfaces.

eth0: 10.20.26.10 - connected to router
eth1: 192.168.1.20 - connected to switch

eth0: 10.20.26.0/24, gw: 10.20.26.1
eth1: 192.168.1.0/24, gw: 192.168.1.254 (192.168.1.254 server placed in my network it has internet access)

I want to use this server(GW0) as my gateway for my 192.168.1.0/24 network to access 10.20.x.x subnets via 10.20.26.1 router and internet access from 192.168.1.254.
What i did.

*

*echo 1 > /proc/sys/net/ipv4/ip_forward

*route add default gw 192.168.1.254

if i do like this internet works fine from my network, but can't access 10.20.x.x.
update 1:
if i use default gw 10.20.26.1.
  iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
  iptables -A FORWARD -i eth0 -j ACCEPT

i can access 10.20.x.x, but not internet.
Than i try to use iproute.
echo 1 corp >> /etc/iproute2/rt_tables
ip route add default via 10.20.26.1 dev eth0 table corp
ip rule add from 10.20.0.0/16 table corp

How to make to this work to reach 10.20.x.x and internet.
Thanks beforehand.

A: you need a specific route to cover the /16
policy based routing is unnecessary.
ip route add default via 192.168.1.254
ip route add 10.20.0.0/16 via 10.20.26.1


text:
Q: unable to open .jar executable file from another java project There is an application inside which there are three buttons , when user clicks on the 1st the notepad exe file opens
but when user clicks on the second the java .jar file doesnot open . can someone please help
following is the code i am posting
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
       //InputStreamReader isr=new InputStreamReader(System.in);
   // BufferedReader br=new BufferedReader(isr);
  try {
    ProcessBuilder p = new ProcessBuilder();

    // Use command "notepad.exe" and open the file.
    p.command("java.exe", "C:\\Users\\zareeba\\Desktop\\KictCHE_UAT");
    p.start();}
  catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
       // TODO add your handling code here:
    }

A: Try to add -jar:
p.command("java.exe", "-jar", "C:\\Users\\zareeba\\Desktop\\KictCHE_UAT");

A: Try doing this by adding -jar also as argument
p.command("java.exe", "-jar", "C:\\Users\\zareeba\\Desktop\\KictCHE_UAT.jar");

A: You are missing the -jar flag. You need to add the -jar flag like this:
p.command("java.exe", "-jar", "C:\\Users\\zareeba\\Desktop\\KictCHE_UAT");

A: You can use below code to run exe file:
 try {
     ProcessBuilder pb = new ProcessBuilder("cmd", "/C", "C:\\Users\\user\\Desktop\\Test.jar");
     Process process = pb.start();
    } catch (Exception e) {
        System.out.println("e="+e);
    }


text:
Q: How retray a field text from SQLite I am dealing with SQLite (on ESP32 board) and I would extract text field:

    ...
    if (sqlite3_step(res) == SQLITE_ROW) {
      const unsigned char * Auth = sqlite3_column_text(res, 0);
      const unsigned char  * Cite = sqlite3_column_text(res, 1);
      sqlite3_finalize(res);
      sqlite3_close(db);
      response->printf("%s\n%s",Auth,Cite);
    }
    ...

Instead of receiving, for example:
Alan Kay
You probably know that arrogance, in computer science, is measured in nanodijkstras.
I receive:
���? Kay
���?probably know that arrogance, in computer science, is measured in nanodijkstras.
I think that there is a length in front of text but I don't know how deal with sqlite3_column_bytes.
Thanks

A: I apologize, I found a clue on sqlite3_column_text returned data gets corrupted during finalize/close.
I deplaced sqlite3_finalize(res); and sqlite3_close(db);

    ...
    response->printf("%s\n%s",Auth,Cite);
    request->send(response);
    sqlite3_finalize(res);
    sqlite3_close(db);
    ...

So I receive a correct answere like:
Alan Perlis
A language that doesn't affect the way you think about programming is not worth knowing.
Best regards
Giovanni Rossati


text:
Q: Extracting text between Number and Parantheses in a String field in Excel I have a bunch of values like the one below in a text field in Excel and was wondering if anyone knows a method of extracting the Suburb name (i.e. Liverpool) which is usually before the first parantheses and after the last number i.e. postcode (3860 in this case)
PARK RD INT OF QUEENS DR LONDON 3860 LIVERPOOL (AGA) VIC
Thanks in advance

A: Office 365:
=LET(a,1+MATCH(1,0/ISNUMBER(0+MID(A1,SEQUENCE(LEN(A1)),1))),b,FIND("(",A1),TRIM(MID(A1,a,b-a)))

A: Put your complex value into A1 and try this in B1:
=IF(ISERROR(FIND(" ";LEFT(A1;FIND(" (";A1)-1)));LEFT(A1;FIND(" (";A1)-1);RIGHT(LEFT(A1;FIND(" (";A1)-1);LEN(LEFT(A1;FIND(" (";A1)-1))-FIND("~";SUBSTITUTE(LEFT(A1;FIND(" (";A1)-1);" ";"~";LEN(LEFT(A1;FIND(" (";A1)-1))-LEN(SUBSTITUTE(LEFT(A1;FIND(" (";A1)-1);" ";""))))))
This will give you the word before  (.
In your example it will return Liverpool.
But fyi: this will work for single words.

A: Try below formula-
=TRIM(RIGHT(SUBSTITUTE(TRIM(LEFT(SUBSTITUTE(A1,"(",REPT(" ",300)),300))," ",REPT(" ",100)),100))

You may also try-
=FILTERXML("<t><s>"&SUBSTITUTE(FILTERXML("<t><s>"&SUBSTITUTE(A1,"(","</s><s>")&"</s></t>","//s[1]")," ","</s><s>")&"</s></t>","//s[last()]")

A: This type of thing is best done in steps, to make it easier to understand and modify. That is:

*

*A1: Text you want to extract from

*B1: Position of first character after the last digit and space =IFERROR(MATCH(10^6, INDEX(--MID(A1, ROW( INDIRECT("1:"& LEN(A1))), 1), )), 0)+2

*C1: Position of opening parenthesis =FIND("(",A1)

*D1: Extract text =MID(A1,C1,D1-C1-1)

This works with multi-word text.

A: Tried this and worked however there is a space at the beginning of every output but I feel that is still manageable
=IFERROR(LEFT(RIGHT(J13,LEN(J13)-MAX(IFERROR(FIND({1,2,3,4,5,6,7,8,9,0},J13,ROW(INDIRECT("1:"&LEN(J13)))),0))),MAX(FIND("(",RIGHT(J13,LEN(J13)-MAX(IFERROR(FIND({1,2,3,4,5,6,7,8,9,0},J13,ROW(INDIRECT("1:"&LEN(J13)))),0))))-1)),RIGHT(J13,LEN(J13)-MAX(IFERROR(FIND({1,2,3,4,5,6,7,8,9,0},J13,ROW(INDIRECT("1:"&LEN(J13)))),0))))


text:
Q: Function for multiple line chart I have written the function for plotting a line graph.
def plt1(plot,xaxis,yaxis):

    plt.title('Distribution of {yaxis} across {xaxis}'.format(xaxis=xaxis, yaxis=yaxis))
    plt.ylabel(yaxis)
    plt.xlabel(xaxis)
    plt.legend(df.columns.values)
    plt.savefig("C:\\User\\folder\\plot.csv")
    plt.show()
    return(plt);

plt1(df,'x','y')

Now I need to make multiple line chart that has same x axis and different columns of the same csv file as y axis (different colors for different columns).Except for the y-axis value, the rest of the formats remain the same. Any help will be greatly appreciated!
I would need something similar to this graph


text:
Q: PHP Add Column Data to Table IF Condition True This is a tough one. I'm not sure how to explain this but I'll try my best. I have a table where all values are coming from DB based on a search form:

The last column "Map Link" appears if a certain condition is true:
$path = 'C:/my/path/here/maps/';

$find_ein = array_column($data, 'ein');

foreach($find_ein as $map_ein){
    $map = $path.$map_ein.'_integration_map.xlsx';
    if(file_exists($map)){
        echo 'Map Link	';
        $map_link = $map;
    }else{
        //echo "no";
    }
}

I'm trying to echo $map_link into this column. In this example, $map_link only belongs to the 2nd row because not all EIN's have a map link. For the ones that do, the EIN # is included in the file name which is why I check for if(file_exists). $map_link is instead getting added to each column: (you can barely see but at top of table, I echo $map_link to show what I am getting back, so there should only be 1 value going into Map Link column):

foreach ($data as $entry){
    // create a new row in the table
    echo '
';

    $count = count($entry);
    $y = 0;
    while ($y < $count){
        $current_row = current($entry);
        // then fill the columns
        echo ''.$current_row.'	<button>Map Link</button>	';

        next($entry);
        $y = $y + 1;
    }
    echo '
';
}

I don't know if any of this makes sense however this is the smartest community I have found out there, so I am hopeful someone might be able to help! Also I am very, very new.


text:
Q: Process contact from outlook csv I want to import contacts from outlook csv to my program. I don't want to renovate a wheel. May be someone did it already?
Thanks!

A: Well a CVS file is simply a text file in which data is separated by a tab character as delimiter. Therefore you can easily read the file using:
 var Data = System.IO.File.ReadAllLines("CVS File");

Then make up a model for the file:
 class Model{
    public string Email {get; set;}
    public string First_Name {get; set;}
    // bla bla
  }

 foreach(var i in Data.Skip(1)) {
      var Temp = i.Splite('\t');
      Model model = new Model{ Email = Temp[0], First_Name = Temp [1]};
 }

or you could read the first line by removing the Skip(1) to find the position for different headers.


text:
Q: What happens to classes removed from collections and arrays I have created multiple instances of a class myClass, and have stored them in a collection. I would like to know what happens to the object in memory when it is removed from the collection. i.e.
Sub createCollection()
Dim c As New Collection
Dim i As Long
For i = 1 To 5
    c.Add New myClass
Next i
c.Remove(5) 'remove last item
End Sub

Is the class still there in memory, does removing it from the collection remove it entirely, as it is not referenced anywhere else? What is the effect (if any) of using a collection declared publically instead, or removing the item with a different Sub, say a button press?
What about for an Array:
Sub createCollection()
Dim a() As myClass
Redim a(1 To 5)
Dim i As Long
For i = 1 To 5
    Set a(i) = New myClass
Next i
Redim Preserve a(1 To 4) 'remove last item
End Sub

A: In OOP object is removed from memory when last reference to it is removed. So, when there's no reference to ceratin object it will be removed on next garbage collection. In your case, your array is an array of references and the way you create this, they are the only references. So if you remove last item, you also remove last reference to this object. So in next garbage collection, the object will be removed from memory.

A: Objects lives as long as somewhere a reference exists to it. When no reference exists the object is released from memory.
Dim a As myClass
Set a = New myClass

Here a holds reference to a place in memory where the object of type myClass resides. As long as this reference exists the object will be in the memory.
  Set a = Nothing

Now the a doesn't reference the location of memory where the object resides. When this was the last reference then this object will be released.
Dim a As myClass
Dim b As myClass
Set a = New myClass
Set b = a

Set a = Nothing

Now the object still continues to live because there is reference to it held in variable b. You can still say e.g. b.Something = 1000.
Set b = Nothing

Now the object can be removed from memory if the reference held in b was the last one.

I would like to know what happens to the object in memory when it is removed from the collection

In this case you can watch it by yourself when slightly modifying the code.
Sub createCollection()
    Dim c As New Collection
    Dim i As Long
    For i = 1 To 5
        c.Add New myClass
        c(i).Id = i
    Next i
    c.Remove (5) 'remove last item
End Sub

myClass Class

Private m_id As String

Private Sub Class_Terminate()
    MsgBox "Object termination: " & m_id
End Sub

Public Property Let Id(ByVal vNewValue As Variant)
    m_id = vNewValue
End Property

The references to those five objects are held in the collection. So when object is created the New operator returns the reference to memory and this reference is stored in the VBA.Collection. When you remove the object from the collection then the object will be released from memory and the message box from Class_Terminate will confirm that. After the method createCollection finishes then the variable c which is holding the reference to the collection goes out of scope and then the collection can be released because no other reference exists to it. Then the four remaining objects will be released as well which will be confirmed with the message from Class_Terminate. HTH


text:
Q: JqGrid setting the last page for datatype local I have a Jqgrid which has datatype as local. I am loading data at run time using addRowData, setCell. Every thing is working great. Note that I am not loading the entire data into grid so grid does not know how many pages are there. My server returns the count which I need to set it to the grid. The docs say that lastpage is ReadOnly? How do I set my last page(number of pages) to the grid? Any suggestions.
Thanks,
Sarath

A: The usage of addRowData method to fill jqGrid is the most old and the most ineffective way to fill the data in jqGrid. The problem is easy. If you place an element on the page the position of all other elements on the page have to be recalculated. It makes many resources of the web browser. The filling of the whole jqGrid body in one step is much more effectively especially with the large number of inserted rows. It's really needed to use addRowData method only in seldom cases.
Much more effective will be to use data parameter of jqGrid which allows to fill the grid with the data, sort the data corresponds to sortname and sortorder and display the first page where rowNum defines the number of rows per page. Additionally one should not use afterInsertRow callback and use gridview: true. In the case the filling of jqGrid is the most effective.
The number of pages of the grid will be calculated automatically based on the number of rows in the grid. Only if you use server side datatype ('json' or 'xml') the client part don't know the total number of pages and so one have to fill in the input data total, page and records together with the main data (see documentation). If one uses low level method addJSONData one can fill grid with the data and still set total, page and records to any values which you want.
Another way which you can use in some scenarios is datatype: 'jsonstring'. The data can be placed as the value of datastr option. By the way the value of datastr must be not only the JSON string but can be an object too.


text:
Q: Win32com arguments input I can not get Full Address of cell with win32COM in python:
cell.Address(external=True) get error while cell.Address only gives string

1. How to get config to get full Address of cell ?
 2. I want to do Formula Evaluate likes in Formula Ribbon programmatically with Python ? Have anyway to access such features by win32COM ?

A: Just found answer:
cell.GetAddress(external=True) - the win32com has .Get for method with arguments.


text:
Q: Porting express generated folder vs fresh npm install? I "express generated" a folder on ubuntu and synced everything into git. Now, I have the need to work on a mac. Can I simply pull the folder from git onto my mac, assume that all the important stuff (for instance my node_modules) will be ported and continue working on it there? Or would I have to do a fresh npm install using the package.json?

A: If there are any native addons in the modules (compiled modules) you'll need to do a fresh install (at least on those) as they wont be binary-compatible.


text:
Q: The difference between parsing using a string or a stream (Poco c++) I have written a simple hierarchical json-parser, using POCO JSON, to be used as a sax parser.
Is their any difference in the result if i use a string or a stream as input to the parse method, see call below, or are the different constructors equivalent?
Parser parser;
DefaultHandler handler;
parser.setHandler(&handler);
parser.parse(input);

In terms of memory consumption, speed etc?

A: std::string version is just a wrapper that creates stream on your behalf, so at the end the total will be roughly the same, string is just more convenient for user.
[EDIT]
This was changed for 1.5.2 - wrapping was removed so that now both (stream and string) versions iterate. The Benchmark Example can be used to determine how much is stream slower than string.
[/EDIT]
Please note that there are some breaking changes coming in 1.5.2 - DefaultHandler name was removed and internally handler has been turned into auto-created smart pointer (that's the main reason we had to obsolete DefaultHandler so existing code would not pass stack-created handler to the smart pointer, it was not a good design to start with). So, in 1.5.2, explicit handler creation will not be needed anymore for default parsing:
std::string json = "{ \"test\" : null }";
Parser parser;
Var result = parser.parse(json);

If you are concerned with performance, note also that Poco::JSON parser speed, as it stands now, is poor and we will be using either the very fast parser from Poco::Web::JSON or something faster (if we can find/write it). Bottom line, 1.5.x is still W.I.P.
Hope this helps.
EDIT:
Benchmarks on Windows and Mac (~15MB JSON file):
Windows

Poco::JSON:      1 195 313 [us]
  Poco::Web::JSON: 403 320 [us]
  json-parser:     321 289 [us]
  libjson:         610 352 [us]

MAC (clang)

Poco::JSON:      480 965 [us]
  Poco::Web::JSON: 176 297 [us]
  json-parser:     220 172 [us]


text:
Q: Autohide panel? Is there any way to get a panel to ALWAYS stay auto-hidden? I have Ubuntu Studio 21.04. I have my panels set to autohide. EVERY TIME I open a program, the panel un-autohides itself and intrudes onto the monitor, with the newly opened program highlighted as though it needs attention. I click on it, the program comes into my foreground, the panel autohides again, and I open the panel to find the program that I was working on in the first place. It is surprisingly cumbersome when using dual monitor and opening a program that opens in multiple windows, like a restored session of Firefox or Zoom, which opens in three windows. (The program doesn't have an action waiting or anything. It's just freshly opened, stays in the background, and immediately highlights itself in the panel, thinking that it needs attention.) I think it might stay autohidden if the computer would open programs in the foreground instead of the background. But better still, I would like to set it so it doesn't think every freshly opened program needs attention. The weird thing is that when a program really does have a popup window waiting on input, the panel doesn't always unhide. Worst of both worlds, under my current settings.

A: In the panel properties, you can select 3 Auto-hide modes:

*

*always

*never

*intelligent

I think your mode is set to "intelligent".


text:
Q: How to make the Logitech 300s move wider?
I am using an wired mouse Logitech 300s (As seen in the screenshot)
Whenever I move the mouse from edge to edge of the mouse pad, the cursor only moved about slightly over 1/2 of the way on the monitor.
I really want the mouse cursor move a longer distance. Is there any way I can fine tune it?
EDIT:
Add screen shot of Mouse pane in System Preferences

A: Go to System Preferences - Mouse. Click on the "Point and Click" tab. In the middle of this pane is a slider for Tracking Speed.  By moving the slider to the right to make it faster will do what you want.  See the image below.

A: I can use the G8 button on the mouse to switch to "Productivity" profile. The light on the side will change to blue, and the mouse will travel longer distance when moving from side to side.