text:
Q: try catch not working I can't figure out how to get the try catch to work. Need to have an error message box pop up when a non number is entered in the text boxes.
private void btnAdd_Click(object sender, EventArgs e)

    {
        int x = int.Parse(txtIn1.Text);
        int y = int.Parse(txtIn2.Text);

        txtIn1.Text = x.ToString();
        txtIn2.Text = y.ToString();

        lstOut.Items.Add((x + y).ToString("N0"));

        try
        {
            int.Parse(txtIn1.Text);
            int.Parse(txtIn2.Text);

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            return;
        }

A: With minimal modifications: move all the code into the try so it catches when any Exception is hit. You're encountering your exception outside of the try block. You are only going to ever see your catch triggered if something within the corresponding try block is throw an exception.
private void btnAdd_Click(object sender, EventArgs e) {
    try {
      int x = int.Parse(txtIn1.Text);
      int y = int.Parse(txtIn2.Text);

      txtIn1.Text = x.ToString();
      txtIn2.Text = y.ToString();

      lstOut.Items.Add((x + y).ToString("N0"));
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        return;
    }
}

Edit: As suggested by commenters, I think this answer is incomplete without stating that a Try/Catch block is overkill in this instance.
A better approach would be to use the built-in TryParse method (which can return a boolean regarding the success of the parse attempt, and an output value). Here is one way you could accomplish this:
private void btnAdd_Click(object sender, EventArgs e) {
  var xSuccess = int.TryParse(txtIn1.Text, out int x);
  var ySuccess = int.TryParse(txtIn2.Text, out int y);

  if(!xSuccess)
    MessageBox.Show($"{x} could not be parsed to int!");
  if(!ySuccess)
    MessageBox.Show($"{y} could not be parsed to int!");

  if(xSuccess && ySuccess)
    lstOut.Items.Add((x + y).ToString("N0"));
}

A: You shouldn't use try-catch as a control block as explained in this SO post. Use if for that. Try catch is really meant to be used when you can't do otherwise or when something that you didn't expect happened.
You can use this SO post as an example and your code could look like this
private void btnAdd_Click(object sender, EventArgs e)
{
    int x;
    int y;

    if(!int.TryParse(txtIn1.Text, out x) || !int.TryParse(txtIn2.Text, out y))
        MessageBox.Show("Parse failed !");
}

You can use
Console.WriteLine(x);
Console.WriteLine(y);

to verify that the vars were properly given a value
For more information about the int.TryParse() method vs int.Parse() see this post

A: As other have mentioned, it's the first int.Parse() functions that are tripping things up - the ones outside the Try/Catch block.
I wanted to expand on the TryParse() function - and why should probably be using that.
Exceptions are expensive - they're a rather large overhead in terms of Time/CPU/etc.  They're also not user-friendly.  You want to say "Please enter a valid number" to the user, not "An exception occurred: ..."
Instead, you can use TryParse, which returns whether the parsing worked; the output of the parse is an "out" parameter in the inputs list:
int myValue;
bool parseWorked = int.TryParse("3", out myValue);

This doesn't have the Exception overhead - it runs quickly, regardless of whether the input's valid.

A: Why not use a different approach?
Use the TextBox.KeyPress event:
private void txtIn1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsDigit(e.KeyChar) /* || add more conditions*/)
        e.Handled = true; // Prevent key to be added to the TextBox' text.
}

Now you don't have to check if there are non-numbers in your string.
Your statement int.Parse(txtIn1.Text); will surely work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: file upload angular js and spring Rest API I have a task to upload documents up to 10 mb. I am using angular.js and spring Rest API. However i have data to be posted with uploaded files.
My code is as below.

  $scope.submit=function(mymodel){
            var request = {
        method: 'POST',
        url: '/myurl/update',
        headers: {
            'Content-Type': undefined
        },
        transformRequest: function(data) {
            var formData = new FormData();

            formData.append('mymodel', new Blob([angular.toJson(data.mydata)], {
                type: "application/json"
            }));
            //angular.forEach( $scope.files,function(file){
            formData.append('file', data.file);
            //});
            return formData;
        },
        data: {
            data: mydata,
            file: $scope.files[0]
        }

    }
    $http(request).success(function() {

    }).error(function() {

    });

    }
3. API code

@RequestMapping(value = "/update", method = RequestMethod.POST,consumes = {"multipart/form-data"}) //consumes = {"multipart/form-data"}
public @ResponseBody
void updateExceptionSummary(@RequestPart(value="mymodel") MyModel mymodel ,@RequestPart("file") MultipartFile file)
{

}

I am getting below error:
    org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'mymodel' is not present.
    at org.springframework.web.servlet.mvc.method.annotation.RequestPartMethodArgumentResolver.resolveArgument(RequestPartMethodArgumentResolver.java:194)
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:78)
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162)

Can anybody please help
what i found is json data posted from request is always empty.
Payload
------WebKitFormBoundaryJIRCCmCILVsxKIBc
Content-Disposition: form-data; name="mymodel"; filename="blob"
Content-Type: application/json

------WebKitFormBoundaryJIRCCmCILVsxKIBc
Content-Disposition: form-data; name="file"; filename="1.png"
Content-Type: image/png


text:
Q: What does "fleet aside" mean here? Does it mean "so badly that even improvements in 2019 couldn't save Reebok" ?
Some of that percentage drop has stemmed from the namesake Adidas brand's healthier growth. Still, it's hard to deny that Reebok has been flailing for too long, fleeting improvements in 2019 aside.
Source: Some of that percentage drop has stemmed from the namesake Adidas brand's healthier growth. Still, it's hard to deny that Reebok has been flailing for too long, fleeting improvements in 2019 aside.

A: "fleeting" here means that the improvements in 2019 were temporary.
"X aside" means X is a notable exception but didn't affect the overall performance.


text:
Q: WPF Prism basic mvvm quickstart project error 'out of the box' I downloaded prism5.exe from Microsoft and expanded it which left a variety of quick start projects.  I simply opened the 'stock' BasicMVVMQuickstart_Desktop solution.
At first I received a 'couldn't find name in the namespace error' (on the same line as noted below, BTW), but after closing and reopening Visual Studio per one stack overflow post, I am now receiving this error:
Your views must implement IView

This is the XAML code and the line with the error:

I have referenced other stack overflow questions but still cannot resolve this.
One post suggested upgrading to Prism 6.  I performed the only upgrade available in NuGet which updated Microsoft.Practices.Prism.Mvvvm to v 1.1.1.0.
I don't see Prism.Core anywhere in my project, so I'm guessing that's something about Visual Studio and packages that I don't quite understand.  Anyway, I uninstalled Prism.Core 4.0 and then Installed Prism.Core 6.2, but since I don't see Prism.Core anywhere in Visual Studio I don't know if anything was changed.
So in addition to trying to understand how to remedy the error above, I'd also like to understand how I use Prism 6 instead of Prism 5.  It's a little confusing to me.

A: You are using an older version of Prism. I would (highly) recommend starting over with the latest bits from the Prism team. You can get that from the link below. There are plenty of samples to choose from, too. The documentation is up to date, which is always nice. This will be much easier than trying to upgrade the code you downloaded from Microsoft. There are plenty of breaking changes between that version and the latest.
Prism Library
Prism WPF Samples
You can get Prism from NuGet, too. Get one of the packages that have the IOC container already included, like Unity (Prism.Unity), or MEF (Prism.Mef). Just getting the Core package will leave much to be desired.
The packages with an IOC contain include all the dependencies (Prism.Core, Prism.Wpf, etc.) needed to get started. I am assuming you are doing a WFP application. I use the Unity version, and I would recommend that over the MEF version, because I found MEF to be interesting to troubleshoot. Go with what you like, though.
Good luck!

A: If you are using Prism 5 then just go to your view.xaml.cs and implement the interface IView. Like
public class MainWindow: Window, IView
{...}

With Prism 6 (Prism.Wpf) nuget package, you don't need the IView implementation on your views


text:
Q: Using javascript to make header buttons click thru I created a child theme for my site, tdotargetmarketing.com. If you look, you'll see the header has three buttons. I broke the header down to the table you see below. Slice 3, 5 and 7 are the buttons on the site that need to click thru. I created pages for those three buttons so I have the url/page. I added this table below in the editor section of the childtheme's css file. Now, I think I need to add javascript code but this is where I'm stuck. Not sure of the proper sequence.
Don't laugh, lol… I just finished the HTML/CSS/javascript basic course on Codecademy so I'm getting it but just not quite there. Can anyone help with this?

A: You don't need javascript for this. Use an a tag to make hyperlinks in HTML.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Example.3A_Creating_a_clickable_image
unless I read the question wrong lol


text:
Q: Jenkins - SSL without displaying httpsKeyStorePassword in process string? Is there any way to configure jenkins for SSL without passing the httpsKeyStore and httpsKeyStorePassword arguments to the jenkins.war?
I've tried setting the values as JAVA_ARGS, and JENKINS_HTTPS_KEYSTORE/JENKINS_HTTPS_KEYSTORE_PASSWORD environment variables, but neither make their way to the winstone web container.
Any ideas? If I install as a system package vs. launching the .war directly, can you configure this in the init script or a file on the host? My main goal is to hide the keystore password in the process string, but I'm not sure how it's possible when launching Jenkins directly from the .war file.

A: For anyone else who needs this - https://github.com/jenkinsci/winstone#configuration-file
You can set the keystore path and password in the winstone.properties configuration file.


text:
Q: Variable in Java Not Recognized For an assignment I'm creating a command line program to change an inputted temp from Celsius (C) to Fahrenheit (F) & vice versa. The program runs fine until the user inputs the temp type (C/F), and then it doesn't seem to recognize the user input. What I am doing wrong?
public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Please enter the temperature:"); //Prompts user for temperature
        String temp = input.nextLine(); //Allows user to input temp data
        double tempDouble = Double.parseDouble(temp); //Changes input from string to double

        System.out.println("Is " + temp + " degrees in Celsius or Fahrenheit? (Enter C or F):"); //Prompts user for type of temp
        String type = input.nextLine(); //Allows user to input temp type

        if (type == "C") { //Checks if temp is Celsius
            double tempF = 0;
            tempF = (tempDouble * 1.8) + 32; //Converts temp to Fahrenheit
            System.out.println(tempDouble + "C equals " + tempF + "F."); //Displays conversion of C to F
            //Tf = Tc * 1.8 + 32

        } else if (type == "F") { //Checks if temp is Fahrenheit
            double tempC = 0;
            tempC = (tempDouble - 32) / 1.8; //Converts temp to Celsius
            System.out.println(tempDouble + "F equals " + tempC + "C.");
            //Tc = (Tf - 32) / 1.8
        }
        System.out.println("Incorrect input for Celsius or Fahrenheit"); //Tells user they didn't input C or F correctly
    }

A: There are two problems in the code

*

*You are checking object equality not the value of the object. User String.equals method for that.

*The construct of the if-else block is wrong, it will always print "Incorrect input for Celsius or Fahrenheit".

Here is the correct one -
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.println("Please enter the temperature:"); //Prompts user for temperature
    String temp = input.nextLine(); //Allows user to input temp data
    double tempDouble = Double.parseDouble(temp); //Changes input from string to double

    System.out.println("Is " + temp + " degrees in Celsius or Fahrenheit? (Enter C or F):"); //Prompts user for type of temp
    String type = input.nextLine(); //Allows user to input temp type

    if ("C".equals(type)) { //Checks if temp is Celsius
        double tempF = 0;
        tempF = (tempDouble * 1.8) + 32; //Converts temp to Fahrenheit
        System.out.println(tempDouble + "C equals " + tempF + "F."); //Displays conversion of C to F
        //Tf = Tc * 1.8 + 32

    } else if ("F".equals(type)) { //Checks if temp is Fahrenheit
        double tempC = 0;
        tempC = (tempDouble - 32) / 1.8; //Converts temp to Celsius
        System.out.println(tempDouble + "F equals " + tempC + "C.");
        //Tc = (Tf - 32) / 1.8
    }else{
        System.out.println("Incorrect input for Celsius or Fahrenheit"); //Tells user they didn't input C or F correctly
    }
}


text:
Q: Read Laptop Battery Status in Float/Double I have a program that reads battery status in Windows that looks like this (simplified code):
#include <iostream>
#include <windows.h>

using namespace std;

int main(int argc, char *argv[]) {
    SYSTEM_POWER_STATUS spsPwr;
    if( GetSystemPowerStatus(&spsPwr) ) {
        cout << "\nAC Status : " << static_cast<double>(spsPwr.ACLineStatus)
             << "\nBattery Status : " << static_cast<double>(spsPwr.BatteryFlag)
             << "\nBattery Life % : " << static_cast<double>(spsPwr.BatteryLifePercent)
             << endl;
        return 0;
    } else return 1;
}

spsPwr.BatteryLifePercent holds remaining battery charge in percent and is of type BYTE, which means it can only show reading in round numbers (i.e. int). I notice that an application called BatteryBar can show battery percentage in floating point value.
BatteryBar is a .NET application. How can I get battery percentage reading in float/double using pure C/C++ with Windows API? (Solution that can be compiled with MinGW is preferable)

A: You can get this information using the WMI . try using the BatteryFullChargedCapacity and BatteryStatus classes both are part of the root\WMI namespace.
To get the remaining battery charge in percent just must use the  RemainingCapacity (BatteryStatus) and FullChargedCapacity (BatteryFullChargedCapacity)  properties.
The remaining battery charge in percent is
(RemainingCapacity * 100) / FullChargedCapacity
for example if the FullChargedCapacity property report a 5266 value and the  RemainingCapacity reports a  5039, the reuslt will be 95,68932776 %
If you don't know how access the WMI from C++ read these articles

*

*WMI C++ Application Examples

*Making WMI Queries In C++

A: Well, as you said, the Windows API provides only an integral percentage value. And, as you implied, .NET provides a floating-point one.
That means that, to use the floating-point one, you have to use .NET. That said, the .NET value is between 0.0 and 1.0, and it's not clear from the documentation whether you actually gain more precision.

A: The tool states that it does "Statistical Time Prediction" so I doubt it uses the direct value of SYSTEM_POWER_STATUS.
Personally, I hardly can imagine what a floating-point precision would be good for, but anyway you could use ILSpy to see how they are doing it, or maybe you also could ask them how they do.

A: The .NET version doesn't actually provide you any more precision. It simply divides the BatterLifePercent byte value by 100.0 and returns the result. Here are the contents of the getter in .NET.
public float BatteryLifePercent
{
    get
    {
        this.UpdateSystemPowerStatus();
        float num = ((float) this.systemPowerStatus.BatteryLifePercent) / 100f;
        if (num <= 1f)
        {
            return num;
        }
        return 1f;
    }
}

UpdateSystemPowerStatus() calls WINAPI's GetSystemPowerStatus(), which in turn updates systemPowerStatus.


text:
Q: Limiting the output of text to 50 characters in PHP I'm trying to limit my text export in PHP to only 50 characters only
How could I modify the following statement to allow this?
$list[$key]['goods_attr'] = $rows['goods_attr'];

A: You should do this in your SQL query if possible.
SELECT LEFT(subject , 50) FROM table

Or you could do it by using substr like this:
$list[$key]['goods_attr'] = substr($rows['goods_attr'], 0, 50);

A: There is an inbuilt function of php substr. It works as follow:
$string = "Hello world";
$string = substr($string,0,5);

it will print "Hello".
so in your case, it should be:
$list[$key]['goods_attr'] = substr($rows['goods_attr'],0,50);

That's it.


text:
Q: How to add Spark DataFrames to a Seq() one by one in Scala I created an empty Seq() using
scala> var x = Seq[DataFrame]()
x: Seq[org.apache.spark.sql.DataFrame] = List()

I have a function called createSamplesForOneDay() that returns a DataFrame, which I would like to add to this Seq() x .
val temp = createSamplesForOneDay(some_inputs) // this returns a Spark DF
x = x + temp // this throws an error

I get the below error -
scala> x = x + temp
<console>:59: error: type mismatch;
 found   : org.apache.spark.sql.DataFrame
    (which expands to)  org.apache.spark.sql.Dataset[org.apache.spark.sql.Row]
 required: String
       x = x + temp

What I am trying to do is create a Seq() of dataframes using a for loop and at the end union them all using something like this -
val newDFs = Seq(DF1,DF2,DF3)
newDFs.reduce(_ union _)

as mentioned here - scala - Spark : How to union all dataframe in loop

A: you cannot append to a List using +, you can append like this :
x = x :+ temp

But as you have a List, you should rather prepend your elements:
x = temp +: x

Instead of adding elements one by one, you can write it more functional if you pack your inputs in a sequence too:
val inputs = Seq(....) // create Seq of inputs

val x = inputs.map(i => createSamplesForOneDay(i))


text:
Q: Facebook API silent login I am trying to use facebook API to provide a silent login feature.
Application has to login onto facebook without prompting for user name and password. The authentication can be done through the application.
I want to know whether this can be done using the facebook API. I'd also want to know whether some paid facility is available to do that.

A: Facebook does not support silent login. Facebook only permits authorization through its own servers and browser windows, because it does not trust third party developers to handle their passwords.
You will have to authenticate once, then get an access token, and you can keep using the access token to auto login the user, until it expires. Have a look here or search google on "how to get Facebook access token c#"
Auto Facebook OAuth from ASP.NET C#


text:
Q: Extract or filter specifics keys and values of a multidimensional array to another one I want to filter or keep selected keys and their values in a multidimensionnal array.
I tried severals methods with array_columns, array_filter, etc ... but I'm not able to keep original structure of my array.
here is original example :
Array
(
    [0] => Object
        (
            [not_wanted_key1] => some value
            [wanted_key1] => wanted value
            [wanted_key2] => wanted value
            [not_wanted_key3] => some value
            [wanted_key3] => wanted value

       )

    [1] => Object
        (
            [not_wanted_key1] => some value
            [wanted_key1] => wanted value
            [wanted_key2] => wanted value
            [not_wanted_key3] => some value
            [wanted_key3] => wanted value
        )
)

expected result :
Array
(
    [0] => Object
        (
            [wanted_key1] => wanted value
            [wanted_key2] => wanted value
            [wanted_key3] => wanted value
       )

    [1] => Object
        (
            [wanted_key1] => wanted value
            [wanted_key2] => wanted value
            [wanted_key3] => wanted value
        )
)

Someone can guide me ?

A: array_filter() should do the work.
Simple example:
$original = ['a' => 2, 'b' => 5, 'c' => 6];

$filtered = array_filter($original, function($item) {
    // This anonymous function must return true for keeping your item, or false for not keeping it

    // There I want to keep items with a value more than 4.
    return ($item > 4);
});

// Output of $filtered: ['b' => 5, 'c' => 6]

Same example with an array of objects, supposing these have a value property:
$filtered = array_filter($original, function($item) {
    // There I want to keep items with a value more than 4.
    return ($item->value > 4);
});

// Output of $filtered: ['b' => 5, 'c' => 6]

If your logic is about filtering from keys, the third parameter flag must be set to ARRAY_FILTER_USE_KEY. Then $item will be your keys, not values.

A: You can do it like this:
//test data
$array[] = new stdClass;
$array[0]->not_wanted_key1 = '1';
$array[0]->not_wanted_key2 = '3';
$array[0]->wanted_key1 = '4';
$array[0]->wanted_key2 = '5';
$array[0]->wanted_key3 = '6';

print_r($array);

$map = array_flip(['wanted_key1', 'wanted_key2', 'wanted_key3']);

$res = array_map(function($item) use ($map){
    return array_intersect_key((array) $item, $map);
}, $array);

print_r($res);

Output
//input array
Array
(
    [0] => stdClass Object
        (
            [not_wanted_key1] => 1
            [not_wanted_key2] => 3
            [wanted_key1] => 4
            [wanted_key2] => 5
            [wanted_key3] => 6
        )

)
//output array
Array
(
    [0] => Array
        (
            [wanted_key1] => 4
            [wanted_key2] => 5
            [wanted_key3] => 6
        )

)

Sandbox
Pretty simple, the trick is (array) casting the object to an array, and then I like to use array_intersect_key  but I am to lazy to manually do $map so I just flip the values around to be the keys.
This way you can easily add/remove keys you want to keep, just by adding/removing them from $map.
If you want to keep the inner array as an object you can cast it back too! so change this:
 return array_intersect_key((array) $item, $map);

To
 return (object)array_intersect_key((array) $item, $map);

Output
Array
(
    [0] => stdClass Object
        (
            [wanted_key1] => 4
            [wanted_key2] => 5
            [wanted_key3] => 6
        )
)

Sandbox
To be clear all you need is this, the rest is for testing:
$map = array_flip(['wanted_key1', 'wanted_key2', 'wanted_key3']);
$res = array_map(function($item)use($map){return array_intersect_key((array)$item,$map);},$array);

A: Similar to ArtisticPheonix's answer, loop through and keep the keys we want by using an intersection:
<?php

$data =
[
    ['fruit'=>'apple',  'veg'=>'carrot'],
    ['fruit'=>'banana', 'veg'=>'marrow']
];

$flipped_wanted_keys = array_flip(['fruit']);
foreach($data as &$item)
    $item = array_intersect_key($item, $flipped_wanted_keys);

unset($item);
print_r($data);

Output:
Array
(
    [0] => Array
        (
            [fruit] => apple
        )

    [1] => Array
        (
            [fruit] => banana
        )

)

As you have objects in your array, removing properties requires a different approach, but if you are happy to have a multidimensional array as above as the output, then you just need to cast your object to an array before the key intersection (assuming these are accessible properties).
$item = array_intersect_key((array) $item, $flipped_wanted_keys);


text:
Q: Angularjs: Controller Register Error i am newbie of angularJS follwing this tutorial AngularJS Fundamentals In 60-ish Minutes on youtube, I've written same code as this guy does everything is working fine till adding the controller. Whenever i add controller i get this error.

Error: [$controller:ctrlreg] The controller with the name 'SimpleController' is not registered.

Here is my code
<!DOCTYPE html>

    <title>First page</title>
    <meta charset="utf-8" />

            Name: <input data-ng-model="name" type="text" name="customerName" />

{{ name }}

{{ cust.name+'-'+cust.city}}

A: This is fixed version of your code.
You need to name a ng-app and attach a controller to that app like below
<!DOCTYPE html>

    <title>First page</title>
    <meta charset="utf-8" />

        Name: <input data-ng-model="name" type="text" name="customerName" />

{{ name }}

{{ cust.name+'-'+cust.city}}

A: You need to register the controller SimpleController with the module.
DEMO

var app = angular.module("myApp", []);
app.controller("SimpleController", function($scope) {
    $scope.customers = [
                { name: 'Ali', city: 'lahore' },
                { name: 'Ahsan', city: "lahore" }
            ];
});
<!DOCTYPE html>

            Name: <input data-ng-model="name" type="text" name="customerName" />

{{ name }}

{{ cust.name+'-'+cust.city}}

A: Guess the guy in the video is using angularjs1.2-, you can install the specified version by npm install angular@1.2.x.

function SimpleController($scope) {
  $scope.customers = [{
      name: 'Ali',
      city: 'lahore'
    },
    {
      name: 'Ahsan',
      city: "lahore"
    }
  ];
}
<!DOCTYPE html>

  <title>First page</title>
  <meta charset="utf-8" />

      Name: <input data-ng-model="name" type="text" name="customerName" />

{{ name }}

{{ cust.name+'-'+cust.city}}

And the way to define a controller have changed since angularjs1.3.0, changelog here.

var app = angular.module("app", []);

app.controller("SimpleController", function($scope) {
  $scope.customers = [{
      name: 'Ali',
      city: 'lahore'
    },
    {
      name: 'Ahsan',
      city: "lahore"
    }
  ];
});
<!DOCTYPE html>

  <title>First page</title>
  <meta charset="utf-8" />

      Name: <input data-ng-model="name" type="text" name="customerName" />

{{ name }}

{{ cust.name+'-'+cust.city}}


text:
Q: Using File Extension Wildcards in os.listdir(path) I have a directory of files that I am trying to parse using Python. I wouldn't have a problem if they were all the same extension, but for whatever reason they are created with sequential numeric extensions after their original extension. For example: foo.log foo.log.1 foo.log.2 bar.log bar.log.1 bar.log.2 etc. On top of that, foo.log is in XML format, while bar.log is not. What's the best route to take in order to read and parse only the foo.log.* and foo.log files? The bar.log files do not need to be read. Below is my code:
import os
from lxml import etree
path = 'C:/foo/bar//'
listing = os.listdir(path)
for files in listing:
    if files.endswith('.log'):
        print files
        data = open(os.path.join(path, files), 'rb').read()
        tree = etree.fromstring(data)
        search = tree.findall('.//QueueEntry')

This doesn't work as it doesn't read any .log.* files and the parser chokes on the files that are read, but are not in xml format. Thanks!

A: This'll give you bash-like regexes:
import glob
print(glob.glob("/tmp/o*"))

Alternatively, you could os.listdir the entire directory, and throw away files that don't match a regex via the re module.

A:
What's the best route to take in order to read and parse only the foo.log.* and foo.log files? The bar.log files do not need to be read.

Your code does this:
if files.endswith('.log'):

You've just translated your English description into Python a bit wrong. What you write in Python is: "read and parse only the *.log files", meaning bar.log is included, and foo.log.1 is not.
But if you think for a second, you can translate your English description directly into Python:
if files == 'foo.log' or files.startswith('foo.log.'):

And if you think about it, as long as there are no files named foo.log. (with that extra dot) that you want to skip, you can collapse the two cases into one:
if files.startswith('foo.log'):

However, if you know anything about POSIX shells, foo.log* matches exactly the same thing. (That's not true for Windows shells, where wildcards treat extensions specially, which is why you have to type *.* instead of *.) And Python comes with a module that does POSIX-style wildcards, even on Windows, called glob. See stranac's answer for how to use this.
I think the glob answer is better than manually filtering listdir. It's simpler, it's a more direct match for what your question title says you want to do (just do exactly what you hoped would work with os.listdir, but with glob.glob instead), and it's more flexible. So, unless you're worried about getting confused by the two slightly different meanings of wildcards, I'd suggest accepting that instead of this one.

A: Maybe the glob module can help you:
import glob

listing = glob.glob('C:/foo/bar/foo.log*')
for filename in listing:
    # do stuff

A: As several already mentioned: you could use glob.glob to find files using wildcards.
I can't write a comment and it is a very old question, but... Someone suggested, the glob.glob can't expand ~ in the path. So, you can use os.path.expanduser for it, and os.path.expandvars to expand environment variables.


text:
Q: LinGDX Mouse over scene object I am currently working on a LibGDX project in java and i was wondering how to detect mouse over shapes that aren't rectangles or circles. Let's say for example i have a spaceship. While rendering it you will have sprite that is a square and inside that square you have the spaceship. The problem is that the spaceship isn't a square so you will have blank space around edges of that sprite (most likely that blank space will be transparent so it won't cause any troubles over background or other scene objects). How do you detect mouse over the spaceship not the entire square? Is there any method?

A: There are several methods for making hit detection more precise.
Rectangles
First, I recommend you ignore the issue and use a rectangle slightly smaller or larger than the actual object (depending on if you want the 'hit' to be easier or harder).  If there are gameplay problems, then you can make it more precise.
+----+
|    |
|    |
+----+

Multiple Rectangles
Once you've got support for a rectangle that is different from the rectangle used to draw the sprite, then you can get into breaking the space down more precisely.  As the next level of approximation, you can subdivide the space in smaller parts (e.g., use several rectangles or a rectangle and a triangle).
+-+
| |++
| |++
+-+

Non-rectangles
Point-in-triangle tests are pretty quick (see Intersector.pointInTriangle, and actually lots of other useful methods in there).  So you could represent your space ship by a rectangle for the base, and a triangle for the tip.
+-+
| |\
| |/
+-+

It often makes sense to 'nest' more complicated hit detection (so you have a big coarse box around the object, and only if that 'hits' do you check the more precise constraints to see if the location is within those bounds).
Pixels
In systems (not OpenGL!) where video memory is readable, and your game has a more direct knowledge of the pixels on the screen, you can test the alpha channel of an object (or even build a special 1-bit texture representing the transparent-or-notness) to detect if a particular click point is "inside" the object or not.  This is really tough in OpenGL because the pixels on screen are rather abstracted.  (Its not impossible, of course, but I think that's a different question, and one I don't know the answer to.)
So, most OpenGL-based games (I would guess) use abstract geometry (rectangles, triangles, circles, etc) to represent the object, and compute hit-or-not based on that, and not via texture pixels.
See also https://gamedev.stackexchange.com/questions/30866/collision-detection-with-non-rectangular-images


text:
Q: Anyway to round up to the nearest integer in a list in C#? Hi sorry if this question has already been answered somewhere else. I am working on a one of my first major personal projects and I've kind of got stumped. Right now my program will generate a list of numbers that correspond to a type. For example type X generates the numbers below and Type Y generate its own list of numbers (I've simplified this for explanations sake).
case ("x"):
                    temp.AddLast(1);
                    temp.AddLast(8);
                    temp.AddLast(16);
                    temp.AddLast(20);
                    temp.AddLast(23);
                    temp.AddLast(26);
                    temp.AddLast(29);
                    break;

case ("y"):
                    temp.AddLast(2);
                    temp.AddLast(5);
                    temp.AddLast(11);
                    temp.AddLast(17);
                    temp.AddLast(23);
                    temp.AddLast(28);
                    break;

Then my program will take an object that has a Type and an Integer and round up or down to the closest number depending on another condition.
Object o = new Object(Type, Value, Rounding);

I've tried using LINQ but I always run into the issue of my numbers not rounding correctly. I can't change the numbers I'm using so I was wondering if there is anything I can do to make this round in the way that I want.
I would really appreciate any advice I can get on this. Thank you!
EDIT
Sorry for not being clear!
So what I am trying to accomplish is to have my program accept an object, which is already has predefined properties and values from a database, but that's besides the point.
It will look at the Type (X or Y on the above example), and generate a list based on that Type (The Switch Case in my example). Then my program is suppose to take the Value and find the next highest integer.
EX. If my Object:
Object o = new Object(X, 8, Up);

The result that would be displayed would be 16.
The issue that I'm running into is that I'm trying to 'round' it up, but I keep getting the closest value, not the next highest value, if that makes sense.
So far I've tried to using the Math().Round methods, but because I'm dealing with ints that didn't really help all that much. I tried to do some research on here before asking but I didn't find anything useful.

A: For Up option, you can search temp to look for the value that is greater than your value and take it.
for (int i = 1; i < temp.Count; i++)
    if (temp [i] > value)
    {
        value = temp[i];
        break;
    }

If your value is grater than or equal the last value, you take the last value:
if (value >= temp[temp.Count - 1])
    value = temp[temp.Count - 1];

And you can do the opposite for Down option.


text:
Q: Migrating from Weblogic 11 to Weblogic 12, getting ClassNotFoundException We are migrating an Application consisting of several ear files from Weblogic 11 to Weblogic 12. Three of the ear files are running well, when we deploy the 4th it throws a ClassNotFoundException on startup.
Two of the three running ears aren't important in this regard. So, the situation is that A.ear runs fine, B.ear fails to start.
B.ears pom.xml refers to a module of A.ear as dependency with provided and ejb-client, and using maven-ear-plugin it refers to the module as ejbClientModule.
Due to the maven-ear-plugin, a jar is created in B.ear mirroring the module in A.ear, adding "-client" to its name, but it only contains a subset of classes from the module in A.ear.
One of this classes is derived from the class the ClassNotFoundException refers to.
The application worked this way on Weblogic 11.
Can somebody please tell me how to fix this problem and make the application work on Weblogic 12?

A: As we figured, such deep connections between ear files are not allowed in weblogic, even in weblogic 11, the classloader hierarchy is as per oracles documentation unable to find the ancestor class in another ears jar. That it was working in weblogic 11, seems to be an error, that has been fixed in weblogic 12.
The solution for us was to put the two ear files into one.


text:
Q: array with keys - node Hello I have basic problem...
    socket.on('addPlayer', function(){

    socket.player = {
        id: server.lastPlayderID++,
        x: randomInt(100,400),
        y: randomInt(100,400)
    }
    players[socket.id] = socket.player;
    console.log(players);
    socket.emit('allplayers', players);

});

Client.socket.on('allplayers',function(data){
console.log(data);});

my allplayers says that data is empty even if players[] are not empty and server console.log shows content of players.


text:
Q: Does "take the crown" mean anything like "take the cake" or anything at all? I just spontaneously used the phrase "take the crown" while complimenting someone's work.
"Harry, this one takes the crown. Keep it up."
Does it exist as an idiom?
Does it actually mean "best of all" or something like "take the cake"?
Thanks.

A: To take the crown is a synonym for to win - see the 2nd meaning here.


text:
Q: mp.pause(); is crashing the application Trying to put a "pause" button into my application that plays a few sound clips looping.
When I call mp.pause(); all hell breaks loose, I'm totally lost!
Here is the method I'm using..
    protected void managerOfSound(String theText) {
    if (mp != null) {
        mp.reset();
        mp.release();
    }

        if (theText.equals(campfire))
            mp = MediaPlayer.create(this, R.raw.campfire);
        else if (theText.equals(calmthunder))
            mp = MediaPlayer.create(this, R.raw.calmthunderstorm);
        else if (theText.equals(rainthunder))
            mp = MediaPlayer.create(this, R.raw.rainthunder);
        else if (theText.equals(whalesgulls))
            mp = MediaPlayer.create(this, R.raw.whalesandgulls);
        else if (theText.equals(stopplaying))
            mp.pause();

    mp.start();
    mp.setLooping(true);
}

And here's a logcat (Meow ^_^)
threadid=1: thread exiting with uncaught exception (group=0xb2f6c648)
FATAL EXCEPTION: main
java.lang.IllegalStateException
at android.media.MediaPlayer.setLooping(Native Method)
at com.tags4apps.soothingsounds.MainActivity.managerOfSound(MainActivity.java:83)
at com.tags4apps.soothingsounds.MainActivity$1.onClick(MainActivity.java:34)
android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)

I'm open to any suggestions right now
edit: What's with the downvotes, I'm 7pm I've been looking for a way to resolve this since 3pm. So downvoting it saying that It's lack of research is kind of unfair..

A: This may not be a complete answer, but I'll attempt to address a fairly obvious problem in the current code:
protected void managerOfSound(String theText) {
    if (mp != null) {
        mp.reset();
        mp.release();   //from this point on it is illegal
                        //to operate on the existing mp object
    }
//if you take one of these branches you will get a new mp instance, and be fine
    if (theText.equals(campfire))
        mp = MediaPlayer.create(this, R.raw.campfire);
   else if (theText.equals(calmthunder))
        mp = MediaPlayer.create(this, R.raw.calmthunderstorm);
    else if (theText.equals(rainthunder))
        mp = MediaPlayer.create(this, R.raw.rainthunder);
    else if (theText.equals(whalesgulls))
        mp = MediaPlayer.create(this, R.raw.whalesandgulls);
//but if you take this branch, you will be illegally operating on a released instance
    else if (theText.equals(stopplaying))
        mp.pause();

    mp.start();
    mp.setLooping(true);
}

Instead, do something like this:
protected void managerOfSound(String theText) {
    if (theText.equals(stopplaying)) {
        if (mp != null) mp.pause();

    } else {  //we are not pausing
        if (mp != null) {  //lets release any old one
            mp.reset();
            mp.release();
        }
        //and then get an appropriate new instance
        if (theText.equals(campfire))
            mp = MediaPlayer.create(this, R.raw.campfire);
        else if (theText.equals(calmthunder))
             mp = MediaPlayer.create(this, R.raw.calmthunderstorm);
        else if (theText.equals(rainthunder))
             mp = MediaPlayer.create(this, R.raw.rainthunder);
        else if (theText.equals(whalesgulls))
             mp = MediaPlayer.create(this, R.raw.whalesandgulls);
        //Note this will still fail if there is some OTHER possibility
        mp.start();
        mp.setLooping(true);
      }
}


text:
Q: Line Breaking in Chameleon I have used the pyramid framework to build a large web application.
Among other things, this application allows the user to enter text into a text area form field. This text is then saved to a database and of course can be readout again and displayed later.
To display content I am using the Chameleon Template Engine.
This works fine, except that line breaking is not displayed correctly (not displayed at all). This is probably due to the fact that the newlines entered into the text area do not cause a new line in HTML when displayed through Chameleon. How can one fix this?
It does not help to replace the newlines by
-Tags because by default Chameleon escapes all HTML-Tags. I am aware of the fact that one can deactivate this feature, but I do not want to do that to avoid cross-site scripting.

A: You need to break the text into separate lines, then render this using a loop and
 tags:

  ${line}

This uses the str.splitlines() method to split the text on newlines, then the loop adds a
 break tag after each line of the text.
You are quite right not doing this in the view, then forcing Chameleon to accept your inserted
 tags by setting the structure: flag. Luckily there is absolutely no need for that anyway.

A: Another possibility is to do something like the following:
import webhelpers.html.tags as t
s = t.literal(t.BR).join(s.split(t.NL))

You can of course create a helper function from it.


text:
Q: How to Convert Date String into Different format? I have a date that gets sent from a database which comes in a string format of '2018-01-01'. What I want to do is convert it into a string of month and year. E.G. 'January 2018'.
What would be the best way of doing so using PHP?

A: Try using the strtotime function to turn your string into a timestamp and the date function with the F Y format to get what you want:
$date = "2018-01-01";
$formatted = date("F Y", strtotime($date));


text:
Q: Select multiple columns but apply Avg() with only one column? How to return the program name, campus name, tuition fee of the program, and the average tuition fee for all the programs that are taught on the each campus?
CREATE TABLE Campus
(
    Campus_ID INTEGER NOT NULL,
    Campus_Name    varchar(24),
    Campus_Address varchar(24),
    Campus_City varchar(12)
);

CREATE TABLE Program
(
    Program_ID INTEGER NOT NULL,
    Program_Name varchar(24),
    Program_Description varchar(2000),
    Tuition_Fess numeric(7,2),
    Program_Coordinator_ID INTEGER,
    Campus_ID INTEGER
);

This is what I expected but didn't work since group by needs every columns that being used.
SELECT
Program.Program_Name,
Campus.Campus_Name,
Program.Tution_Fees,
AVG(Program.Tution_Fees) AS AVERAGE
FROM Program
INNER JOIN Campus
ON Program.Campus_ID=Campus.Campus_ID
GROUP BY Campus.Campus_Name;

A: You should use something called 'window functions'. They're similar to 'aggregate functions', but the act on every row (partitioning by some field value). I'm sure you will find out how to do it if you check the documentation. You're code will end up looking something like:
SELECT Program.Program_Name,
    Campus.Campus_Name,
    Program.Tution_Fees,
    AVG(Program.Tution_Fees) OVER(PARTITION BY Campus_ID) AS CAMPUS_AVERAGE
FROM Program
    INNER JOIN Campus
    ON Program.Campus_ID=Campus.Campus_ID
;


text:
Q: Need help using PHP to replace text strings with the contents of a set of external files I am working on a project to improve public accessibility to the inner workings of a legislative body and I've hit a roadblock. Hoping to get some help since I've been searching for hours and getting nowhere.
Basically, I have some data I want to manipulate. The source currently looks like this:

HB 2434 HB 1980 SB 5234 SB 6185 HB 1320 SB 5238 HB 2239 HB 2224 HB 1052 HB 1032 SB 6178 SB 6185 HB 1320

On another day it might look like this:

SB 5234 SB 6185 HB 1320 SB 6178 SB 6185 SB 5238 HB 2239 HB 2224 HB 1980 HB 1032 HB 1320 HB 1052 HB 2434

Each of these (i.e. HB 2434 or SB 5324) is a bill number, referring to a piece of legislation. The order is important - these bills are listed by date modified, with the most recently modified bill first. The order changes on a regular basis as the file is regenerated. The format doesn't change; it's always just a text file with a list of bills separated by a space.
I want to replace each of the bill numbers listed above with content housed in external files, and then include that content on a webpage. I have a set of external files with explanatory info corresponding to each bill number (i.e. SB5324.html).
So "SB 5324" would be replaced with the contents of SB5324.html, which resemble something like this:

HB 5324 Information

John Doe is the primary sponsor of this bill. The bill was introduced on January 1st, 2013 by Reps. Doe of Cooltown and Jane Smith of Anytown. It is scheduled for a hearing in the Committee that Doesn't Matter on March 18th, 2013. Comments regarding the bill may be directed to Rep. Doe.

Recent comments about the bill:

First comment

Second comment

Third comment

Each of the other bills would be replaced with something similar.
The order is important to the end result because I want the divs that appear at top of the page to correspond to the bills with the recent activity, and inactive bill divs to be at the bottom.
What is the best way to go about this with PHP and cURL? I understand basic usage of cURL but I'd like to include the source file and then replace each bill number in order with a small file consisting of nothing but content wrapped in a div like the above. The files are all stored in the same place, and accessible like this:
http://website.tld/bills/divs/SB5324.html
and
http://website.tld/bills/divs/HB1980.html
I've been trying to get this to work with just two of the bills, but I'm sure I'm going about this wrong:
<?php function getBills($billlistid) {$ch = curl_init(); $timeout = 5;
curl_setopt ($ch, CURLOPT_URL, 'http://website.tld/bills/' .
$billlistid . '.html'); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $file_contents =
curl_exec($ch); if (curl_errno($ch)) {echo "
Sorry, can't show the bills! Try refreshing the page.
"; } else {
curl_close($ch);
$file_contents = preg_replace('/SB 5324/', file_get_contents($_SERVER['DOCUMENT_ROOT'].'/bills/divs/SB5324.html'), $file_contents);
$file_contents = preg_replace('/HB 1980/', file_get_contents($_SERVER['DOCUMENT_ROOT'].'/bills/divs/HB1980.html'), $file_contents);
echo $file_contents; }}?>

<?php getBills('MyBillList.txt') ?>

I'm new to PHP so would appreciate some pointers. Thanks.
POSTSCRIPT: The PHP code I have now is producing this:

SB 5234 Information

John Doe is the primary sponsor of this bill. The bill was introduced on January 1st, 2013 by Reps. Doe of Cooltown and Jane Smith of Anytown. It is scheduled for a hearing in the Committee that Doesn't Matter on March 18th, 2013. Comments regarding the bill may be directed to Rep. Doe.

Recent comments about the bill:

First comment

Second comment

Third comment

HB 2434 HB 1980 HB 1032 SB 6178 SB 6185 HB 1320 SB 5234 SB 5238 HB 2239 HB 2224 SB 6178 SB 6178 SB 6178 SB 5234 SB 5234 SB 5234 SB 5234 HB 1052 SB 5234 SB 5234 SB 5234

Replacement divs appear on top of the list of bills which is not what I want. I want each div to appear in place of the bill number it is replacing. Like this:
HB 2434 HB 1980 HB 1032 SB 6178 SB 6185 HB 1320

SB 5234 Information

John Doe is the primary sponsor of this bill. The bill was introduced on January 1st, 2013 by Reps. Doe of Cooltown and Jane Smith of Anytown. It is scheduled for a hearing in the Committee that Doesn't Matter on March 18th, 2013. Comments regarding the bill may be directed to Rep. Doe.

Recent comments about the bill:

First comment

Second comment

Third comment

 SB 5238 HB 2239 HB 2224 SB 6178 SB 6178 SB 6178 SB 5234 SB 5234 SB 5234 SB 5234 HB 1052 SB 5234 SB 5234 SB 5234

Of course, the other bill numbers would also ultimately be replaced with divs. But replacing just one should result in the above.

A: What about using regexp like this?
$s='HB 2434 HB 1980 HB 1032 SB 6178 SB 6185 HB 1320 SB 5234 SB 5238 HB 2239 HB 2224 SB 6178 SB 6178 SB 6178 SB 5234 SB 5234 SB 5234 SB 5234 HB 1052 SB 5234 SB 5234 SB 5234';

$count=preg_match_all('/([A-Z]+) ([0-9]+)/', $s, $matches);

for($i=0; $i<$count; $i++)
  include("{$matches[1][$i]}{$matches[2][$i]}.html");


text:
Q: Getting free apple certificate outside of xCode I am building an app using phonegap. Since im on ubuntu i have to build my app each time using build.phonegap.com.
Now i want to test my application on my Iphone. And here comes the problem.
I need a certificate for it to build on IOS. So i went and created an account but quickly found out that i have to pay 99$ for the certificate.
Im not a professional app builder (yet) and all i want to do is to test my very unfinshed app.
Looking around the internet i found that i am able to get a certificate if i use xCode. However since i am on an ubuntu machine i am unable to download the program.
So my question is: is there another way around?

A: Unfortunately no. You NEED Xcode to build your app. Xcode now gives you one free certificate which you can use, but to distribute an app on the App Store you will need to pay the $99 (outside of using PhoneGap Build).


text:
Q: Get the first day of the week from a previously selected week I have a datepicker plugin where I get the day of the week (so far everything is fine and working). If I click again in the week field, the datepicker opens, but the selected day is today's (the current day). What I want is when I click in datepicker, its select the first day of the week select (Monday).
For example, if I have chosen the week 28 of 2017, I want the day July 10, 2017 to appear selected when I click the datepicker

A: You can try a simple logic.

*

*Accept week number and multiply it by 7. You will have nth day.

*Create a variable (baseDay) that will hold the day to be selected.

*Create a date object for this day.

*Now fetch the day of this date and subtract baseDay from it. You will get number of days to subtract to get necessary date.

*Subtract those days and you have your date.

function getStartOfWeek(weekNo) {
  var baseDay = 1; // For Monday
  var today = new Date();
  var date = new Date(today.getFullYear(), 0, weekNo * 7);
  var day = date.getDay();

  console.log(date, date.getDay())
  if (day > baseDay)
    date.setDate(date.getDate() - (day - baseDay))
  console.log(date, date.getDay())
}

getStartOfWeek(28)

Note: this is not the complete solution. Above logic is to get the necessary date. Once you have a date, you will have to set it to the datepicker. This part will be specific to plugin used and can be incorporated easily.


text:
Q: Soflayer Billing API using Ruby- Extracting per user billing details Have a question about Softlayer billing API. When I try to run the API code to extract the data into an object mask I receive an error as below:
/Library/Ruby/Gems/2.0.0/gems/softlayer_api-3.2.1/lib/softlayer/APIParameterFilter.rb:82:in object_mask': object_mask expects strings (ArgumentError)
    from /Library/Ruby/Gems/2.0.0/gems/softlayer_api-3.2.1/lib/softlayer/Service.rb:156:inobject_mask'
    from testAuthentication_old.rb:53:in `'
require 'softlayer_api'
require 'pp'

user_id = "your user id"
 api_key = "your API key"

object_mask = {"orderItem" => {"order" => {"userRecord" => {"username" =>   ""}}},
"invoiceItem" => {"totalRecurringAmount" => ""}}

billing = SoftLayer::Service.new("SoftLayer_Account",:username => user_id,:api_key => api_key)
user_bill=billing.object_mask(object_mask).getNextInvoiceTopLevelBillingItems

pp user_bill
for item in user_bill do
if item.key?("orderItem") &&
item["orderItem"]["order"]["userRecord"]["username"] == ""
pp("User " + "" + " has an invoice item of " +
item["invoiceItem"]["totalRecurringAmount"].to_s())
end`

The authentication worked okay but somehow its complaining of the object mask. Can you please provide insight. In a different post on Softlayer there was a mention in changing Billing APIs. If so, do i need to define the object mask differently? Can you please let me know? Any help would be greatly appreciated.

A: It seems that SoftLayer API for Ruby is expecting a string in the object_mask and not an object that is shows in the example specified here.
Anyway, try this mask please:
object_mask = "mask[orderItem[order[userRecord[username]]], invoiceItem[totalRecurringAmount]]"

billing = SoftLayer::Service.new("SoftLayer_Account",:username => user_id,:api_key => api_key)
user_bill=billing.object_mask(object_mask).getNextInvoiceTopLevelBillingItems

I will let you know if the other masks (object type) are not longer supported by the client.


text:
Q: "Host key verification failed" error when running GitHub Actions on self-hosted runner (Windows 10) I'm trying to run a simple GitHub Action on my self-hosted runner (Windows 10), but I'm getting the error Host key verification failed. [error]fatal: Could not read from remote repository. Here's the code for the GitHub Action:
name: GitHub Actions Demo
on:
  push:
    branches: ["feature"]
jobs:
  build:
    runs-on: self-hosted
    steps:
      - name: Check out repository code
        uses: actions/checkout@v3

I've verified that the self-hosted runner is properly configured and connected to the repository, and I can manually clone and fetch the repository on the same machine without any issues. I've also tried running the ssh-keyscan command and adding the resulting host key to the known_hosts file, but that doesn't solve the problem.

A: Instead of running directly the checkout action, try first running a
    steps:
      - name: Test SSH access
        run: ssh -Tv git@github.com

The is to see which key is communicated, and it the account used is the same as the one you are with, when you do your manual test (when the clone/fetch is working).
The OP ysief-001 then sees (in the comments)

After 1h30m I cancelled the workflow.
The last two lines are
Found key in C:\\Users\\ysief/.ssh/known_hosts:4
read_passphrase: can't open /dev/tty: No such file or directory

That simply means a passphrase-protect (IE: encrypted) private key is not supported.
You need one without passphrase. (Or you can remove the passphrase from your existing key)


text:
Q: Regex to Match 5ABCDEXXX I have mobile numbers consisting of 9 digits.
What I tried
I have a regex to match this pattern 5ABCDEXXX. A sample 582694666.
.{5}(?!(\d)\1)\d(\d){3}

5ABCDEXXX:

*

*starts with 5

*4 different numbers ABCDE

*3 similar numbers at the end XXX
My problem is that this regex will match any mobile number that has 3 repeated numbers despite their index. For example, the regex will also match 552728495 because it has 3 fives.
What I want
I want to remodify my regex to match this pattern only 5ABCDEXXX. The three similar numbers should be at the end of the mobile number.

A: What about:
^5(?:(\d)(?!\d*\1\d*\d{3}$)){5}(\d)\2\2$

See an online demo

*

*^5 - Start-line anchor followed by a literal '5';

*?:(\d)(?!\d*\1\d*\d{3}$)){5} - 5 Times a non-capture group to match a 1st capture group of a single digit that is not followed by 0+ digits and a representation of itself before the last three digits and the end-line anchor;

*(\d)\2\2 - A 2nd capture group to match a single digit and twice a representation of itself;

*$ - End-line anchor.

A: You can use
^5(\d)(?!\1)(\d)(?!\1|\2)(\d)(?!\1|\2|\3)(\d)(?!\1|\2|\3|\4)(\d)(\d)\6{2}$

See the regex demo.
Details:

*

*^ - start of string

*5 - a 5 char

*(\d) - a digit captured into Group 1 (\1)

*(?!\1)(\d) - a digit (captured into Group 2) that is not the same digit as captured into Group 1

*(?!\1|\2)(\d) - a digit (captured into Group 3) that is not the same digit as captured into Group 1 and 2

*(?!\1|\2|\3)(\d) - a digit (captured into Group 4) that is not the same digit as captured into Group 1, 2 and 3

*(?!\1|\2|\3|\4)(\d) - a digit (captured into Group 5) that is not the same digit as captured into Group 1, 2, 3 and 4

*(\d) - a digit captured into Group 6

*\6{2} - two digits that are captured into Group 6

*$  - end of string.


text:
Q: Audiojs player. How to make it via div? I'm new into Javascript (I code in php only)
I want to remake this player into DIVs. But I can't understand how to pass DIV blocks to the Audiojs function. Please look at the player. Need an advice.
This is the source http://kolber.github.com/audiojs/demos/test6.html - click here to view the player

wait what notorious xx (2009)

  <audio preload></audio>

            add

play

            add

play 2

            add

play 3

The problem is that I want to put more divs inside of
But this script takes the next DOM element.
I think that problem with var next = $('#ol #li.playing').next();


text:
Q: Lookup Inline Edit javascript onchange event not detecting I am using
<apex:outputField value="{!rhlead.Matched_Company__c}"/>

Inline Edit is enabled on this field.
How to call action support or javascript on change of Inline edit.
I am using this code to detect changes in VF form.
Surprisingly it works when I enter a value manually. but when the value is selected from popup It does not detect change
var $j = jQuery.noConflict();

        $j(document).ready(function(){
            $j('form input, form div, form textarea,form span').on('input propertychange change', function() {
                console.log('Textarea Change');
                clearTimeout(timeoutId);
                timeoutId = setTimeout(function() {
                    // Runs 1 second (1000 ms) after the last change
                    saveToDB();
                }, 2000);
         //$j(this).removeClass("inlineEditModified");
            });
        });


text:
Q: How to add list automatically after insert without page refresh in angular 5 I have main component employees under this there are two components.
a) employee b)employee-list
the left side part is employee and right side part is employee-list
how can i update employee-list details array after insert in left side without page load in angular 5.
Please click on the link in description to see the image for better understand my problem.

A:  child component 1 // employee component
 @Output()
 employeeListDetails = new EventEmitter(); // emit your submitted details array

 Main component: // parent component

 @Input()
 employeeListDetails: any; // this is the array of your submitted data in employee component

 Parent HTML:
 <app-employee (employeeListDetails)="employeeListDetails= $event"> </app-employee>
 <app-employee-list [employeeData] = "employeeListDetails"> </app-employee-list>

 child component 2 // employee list component
 @Input()
 employeeData: any;

ngOnChanges(simpleChanges: SimpleChanges) { // you have to import OnChange and SimpleChanges
if (employeeData !== undefined){

 // assign employee data to the variable you are iterating
}

}


text:
Q: The only proper use of a scriptlet in JSP Let me preface this post by saying the following (so no one marks it as a duplicate).
-- I know that, per the JSP specification, that scriptlets in JSP pages should be avoided at all costs. And that their purpose, if necessary, can be to transform data returned from processing the client's requests into a proper client-ready format.
So, my question is this: Does the following case fall into that category? Is it an appropriate use of a scriptlet?
At the top of my JSP page I use a scriplet to capture server-side data:
<% User user = User.getUser(request); %>

Then in the JSTL I use a scriptlet to reference this object:
<c:set var="userName" value="<%=user.getLoginName()%>" />

Later on when I'm submitting my form via AJAX I populate a value using EL:
params.userName = "${userName}";

I know that using scriptlets in JSP is considered very bad form but how else can I get the User object?
Do I need to force the backend developer to pass that value back to me so I can reference it via JSTL? I'm guessing that is what I must do.

A: Expose the user to JSP in the Java code and retrieve it via EL.
That can be done with the servlet backing your JSP, a filter, etc. depending on what framework you're using. There's no reason to use scriptlets in this case.


text:
Q: Netlogo modifying library Mouse Drag Multiple Example to a non wrapping world Could anyone give some hints (or a full solution!) to how to convert the model library code example 'Mouse Drag Multiple Example' to a non wrapping world. My attempts destroy the selection rectangle (the sides of the rectangle pile up at the edge - because each part is treated separately). Similarly the selected turtles just pile up at the edge. Thank you.
Here's the main procedure from the model - it gives a runtime error on the second setxy when the side of the selection rectangle gets to the edge of the non-wrapping world:
to handle-drag
;; remember where the mouse pointer was located when
;; the user pressed the mouse button
let old-x mouse-xcor
let old-y mouse-ycor
if selected? old-x old-y [              ;; selected? is a reporter defined below
while [mouse-down?] [
  let new-x mouse-xcor
  let new-y mouse-ycor
  ;; we need to move both the selected turtles and the sides
  ;; of the selection rectangle by the same amount that the
  ;; mouse has moved.  we do this by subtracting the current
  ;; mouse coordinates from the previous mouse coordinates
  ;; and adding the results to the coordinates of the turtles
  ;; and sides.
  ask selected
    [ setxy xcor + new-x - old-x
            ycor + new-y - old-y ]
  ask sides
    [ setxy xcor + new-x - old-x
            ycor + new-y - old-y ]
  set old-x new-x
  set old-y new-y
  ;; update the view, otherwise the user can't see
  ;; what's going on
  display
]
]
end

A: This is completely untested. It sounds like what you need is to pretest the potential position to make sure if doesn't go past the edge of the world and, if it does, reduce the amount of movement accordingly.
Try amending this section:
ask selected
[ setxy xcor + new-x - old-x
        ycor + new-y - old-y ]
ask sides
[ setxy xcor + new-x - old-x
        ycor + new-y - old-y ]

with:
let move-x new-x - old-x
let proposed-max-x max [x-cor] of selected + move-x
let proposed-min-x min [x-cor] of selected + move-x
if proposed-max-x > max-pxcor + 0.5 [let move-x max-pxcor + 0.5 - max [x-cor] of selected]
if proposed-min-x < min-pxcor - 0.5 [let move-x min-pxcor - 0.5 + min [x-cor] of selected]
ask selected
    [ setxy xcor + move-x ]

You will need to add in the sides (this only does selected) and do similar for y coordinates.


text:
Q: How to split the query column value into two line inside of anchor tag using coldfusion? I've cfquery loop, then I've displayed the one query column value(Text) into anchor tag.
For Example
<cfloop query="testQuery">
   #testQuery.Title#
</cfloop>

Assume that testQuery.Title variable is return "Defines an explanation/pronunciation of characters (for East Asian typography)"
But I need to break the sentence for Example
"Defines an explanation/pronunciation of
characters (for East Asian typography)"

A: Just put the link into a wrapper and set some width.
<cfloop query="testQuery">

#testQuery.Title#

</cfloop>

Let me know if you have any more problem/it is not working.