text:
Q: Java GUI Problems I'm designing a really simple GUI but without any luck.  Basically the outer layout has two columns which is a splitter pane (this is for an IRC client I'm writing).  On the left-hand side is the server/channel/user tree and on the right is the chat pane.  Now I break this down so on the right-hand side there's the output pane at the top, and a single-lined input box at the bottom.
This is the code for creating the GUI on a whole (this is just a snippet)
ChatModel cm = new ChatModel();
ChatView cv = new ChatView(cm);

treeViewChatSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, serverTreeView, cv);
treeViewChatSplitPane.setSize(500, 500);
treeViewChatSplitPane.setBorder(null);
treeViewChatSplitPane.setDividerSize(3);
this.getContentPane().add(treeViewChatSplitPane);

this.setSize(500, 500);

The ChatView constructor has this in it (it extends java.awt.Container)
this.model = model;
this.setLayout(new BorderLayout());

mainTextArea = new JTextArea();
mainTextArea.setLineWrap(true);
mainTextArea.setBackground(new Color(255, 255, 255));

inputField = new JTextField();

this.add(mainTextArea, BorderLayout.CENTER);
this.add(inputField, BorderLayout.PAGE_END);

Now it looks fine initially, but the problem I'm having with it is that you can move the splitter to the left, but not to the right.  In fact, if you move it left, you can no longer move it right.  I did have it working earlier, but the implementation wasn't as good and I've forgotten what I had done.
Any ideas?  I can't see why this wouldn't work.

A: If I remember correctly, JSplitPanes always respect the minimum size of their components. Try explicitly setting the minimum size of the ChatView to (0,0) and see if that helps. If so, you can then look at each of the components inside it to see which is causing the problem.

A: In any place do you set minimum size for the ChatView? If so, isn't this minimum equals to the frame size ( 500 x 500 ) ?
It is kind of hard to troubleshot with the information provided, but the following advice have ALWAYS worked for me ( and for the people who use it )

*

*Create the simplest frame that could possible work and add a SplitPane with two buttons.

*Resize in there.

*In everything goes ok, process replacing one of your components.

*Then the other.

*Detect which one is causing the strange behavior.

*On that one, start doing the same, replace it for the minimum component you can think of ( replace it with a JPanel for instance )

BTW, probably it would be better to replace java.awt.Container with javax.swing.JComponent
The idea is to start from the simplest thing that could possible work and evolve from there.  Most of the times the problem is in some silly property we set and by cleaning up everything it came up.
It should take less than 1 hr. for this.

A: If both components have sensible preferred and minimum sizes, and you're still seeing strange behavior, you may need to call setResizeWeight() on the JSplitPane.
Note, BTW, that programatically setting the divider location (setDividerLocation()) pretty much never works.

A: I'm not sure what is exactly causing your problem, but from vague memory I can tell you that JSplitPane goes bonkers if you don't set preferred sizes and minimum sizes for each of your panes.
I would suggest doing that just to see if it works better.
Here is some stuff from the Java tutorial on dividers.

A: It may be related with minimunSize of the right component. In the following example you can just move the separator to the left.
public static void main(String[] args) {
    JLabel barLabel = new JLabel("bar");
    JLabel fooLabel = new JLabel("foo");
    barLabel.setMinimumSize(new Dimension(150,150));
    fooLabel.setPreferredSize(new Dimension(50,50));

    JSplitPane treeViewChatSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, fooLabel, barLabel);
    treeViewChatSplitPane.setSize(500, 500);
    treeViewChatSplitPane.setBorder(null);
    treeViewChatSplitPane.setDividerSize(3);

    JFrame frame = new JFrame();
    frame.add(treeViewChatSplitPane, BorderLayout.CENTER);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200,200);
    frame.setVisible(true);

}


text:
Q: Why are there differences in USB flash drive throughput between different computers? I have a USB(2.0) Flash Drive. I was recently moving data off my desktop to my laptop.
I noticed that off my desktop I only get about 4-6MB/s. (It fluctuates quite a bit)
But on my laptop I get a solid 20MB/s.
What could be the issue with my desktop? Is it a driver issue or something?
Thanks

A: Assuming you are writing from the desktop to the flash drive, and reading from the flash drive to the laptop, these seem like reasonable numbers.  I have more than one flash drive that reads between 18-22MBps and writes at no more than 5MBps.
Also depends on whether you're seeing it when it's copying one large file, or many small files.  Usually copying many small files is substantially slower.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to parse emails and transfer to DB I have seen some web apps that allow me to email stuff to a special ID and it magically turns up in my account. How exactly do they do this?

A: Without you giving an example of the specific service you're thinking of, it's hard to know exactly, but one way could be:

*

*you give your email address to one of these sites, e.e. magic-mail.com

*they insert this into their db, and take the db id value for this entry (12345)

*they give you an address using this id (12345@magic-mail.com)

*when mail is received by magic-mail.com, they look up the part before the @, pull out the associated email address for that ID, and relay the message on to the address you gave initially (toby@example.com)
There are many other ways of doing this, likely more simple than the above, but again, without examples it's hard to tell you exactly how the site you're thinking of is operating.

Edit
On reading the question, I assumed "my account" meant your mail account. If you meant an account you have on this company's system, then the process would be the same as the above, but changing the last step to:

*

*when mail is received by magic-mail.com, they look up the part before the @, pull out the associated email address for that ID, and copy the contents of the message to the account associated with that id.

A: You can write a simple script on python/php or any language your know. Make it recieve a pop mail for account 'myName@mySite.com' and put the content to db.
It is quite easy.

A: You would need a way to monitor the mail account for new messages, read the message format, parse out the parts that are important to you and then perform the insert.
Monitoring the mail account would require having a script running on the server in a specified interval, otherwise the only other way would be to access a certain URL manually which would access the mail account and do all the necessary processing.
Depending on your hosting provider and the amount of freedom they give you, this may or may not be possible.

A: Short way:
You need to write a script that will connect to mail server, fetch mails, parse them and then put to database.
Run this in a cron job and you're set.


text:
Q: How to open video file with custom title I want to open video file and set the previewed title in video player with a different title than the file name (which is used by default).
            String videoFile = "Video file url / path";
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse(videoFile), "video/mp4");
            // Is there an extra to set the previewed video title?
            mMainActivity.startActivity(intent);

A: There is no documented extra for ACTION_VIEW that would offer this, and third-party video players would not have to honor it anyway. You are welcome to implement your own video player in your own app if you wish to control the title.


text:
Q: Multivariate Linear Regression in Python - analog of mvregress in MATLAB? I want to use the same function or method in Python as mvregress in MATLAB.
As an example, we have x1, x2, x3, x4, x5, x6 inputs and y1, y2, y3 outputs. After using this function we should get some estimate regression coefficients.
Does Python have this ability?

A: sklearn.linear_model.LinearRegression works fine for multivariate linear regression (where the output is a vector, not a scalar)
>>> from sklearn import linear_model
>>> X = [[1, 2, 3, 4, 5, 6]]
>>> Y = [[1, 2, 3]]
>>> lr = linear_model.LinearRegression()
>>> model = lr.fit(X, Y)
>>> model.predict([[1,2,3,4,5,6]])
array([[ 1.,  2.,  3.]])


text:
Q: Chaining results with Bluebird Is there any convenience method in Bluebird for a resolution chain where the input for each element is the resolved value from the previous element (unless it is not a function)?
I'm trying to chain the following logic into a single method:
function getClient() {
    // resolves with the client
}

function getClientProduct(client) {
    // resolves with the product
}

var response = {}; // global response object;

function prepareResponse(product) {
    // prepares global response object, resolves with `undefined`
}

promise.someMethod(getClient, getClientProduct, prepareResponse, response)
    .then(data=> {
        // data = the response object;
    });

I'd like to avoid having to write the following (if possible):
getClient()
    .then(client=>getClientProduct(client))
    .then(product=>prepareResponse(product))
    .then(()=>response);

A: Those arrow functions are meaningless. You can do simply
getClient().then(getClientProduct).then(prepareResponse).…

There is no convenience method to shorten that further - I guess you don't want to consider
[getClient, getClientProduct, prepareResponse].reduce((p,fn)=>p.then(fn), Promise.resolve())

For the last one, you can use the .return(response) utility method.

A: You don't really need a convenience method. You can just write it like this:
function getClient() {
    // resolves with the client
}

function getClientProduct(client) {
    // resolves with the product
}

var response = {}; // global response object;

function prepareResponse(product) {
    // prepares global response object, resolves with `undefined`
}

getClient()
    .then(getClientProduct)
    .then(prepareResponse)
    .return(response);


text:
Q: Rake task for pushing local file to GitHub I have a yml file in my local project, stored in config/locales/en.yml.
I want to create rake task to push this file to GitHub, overwriting the existing file.
How can I accomplish this?

A: Perhaps you want something like this?
# in lib/tasks/github.rake

namespace :github do
    desc "Push locale stored in `config/locales/en.yml` to github"
    task :push_locale do |t|
        sh "git add config/locales/en.yml"
        sh "git commit -m 'Update locale.'"
        sh "git push"
    end
end

and then invoke the task with rake github:push_locale


text:
Q: Entity Framework performance issue while looping with more record I have employee details of more than 4000 employees. While retrieving those rows, I am faced with performance issues due to the looping. So what can I do to improve performance?
This is the looping I mentioned:
List<EmployeesEntityObject> lstEmployee = new List<EmployeesEntityObject>();

foreach (var item in lst)
{
           EmployeesEntityObject obj = new EmployeesEntityObject();
           obj.EmployeeID = item.EmployeeID;
           obj.EmployeeName = item.EmployeeName;
           lstEmployee.Add(obj);
}

A: You could try and see what happens when you completely "linqify" your code:
var lstEmployee = lst.Select(emp => new EmployeesEntityObject
                                   {
                                       EmployeeID = item.EmployeeID,
                                       EmployeeName = item.EmployeeName
                                   }).ToList();

But as marc_s says, there is no apparent cause for any performance issues in your code. Unless, as said, the constructor and/or the setters of the properties conceal time-consuming code. Both of which, by the way, would not be recommendable.


text:
Q: "current directory" notation not working I was taught that it's good practice to specify the directory of a file you're linking to, even when the file is in the current directory. So, for example, use "./constants.inc.php" as opposed to "constants.inc.php". This has generally worked fine for me, except in one particular spot in my code I get the following PHP error when I use the ./ notation:

Warning: require(./constants.inc.php) [function.require]: failed to open stream: No such file or directory in C:\xampp\htdocs\widget_corp\includes\functions.inc.php on line 4
Fatal error: require() [function.require]: Failed opening required './constants.inc.php' (include_path='.;C:\xampp\php\PEAR;C:\xampp\htdocs\websites\mathverse\includes') in C:\xampp\htdocs\widget_corp\includes\functions.inc.php on line 4

Writing "./constants.inc.php" gives this error, but "constants.inc.php" doesn't (PHP seems to find the file just fine). Can someone tell me why the ./ notation doesn't work in this particular case? Perhaps it's something very simple I'm missing?
To give a bit more context (if necessary), the error is in the function below (line 2), which is in my PHP functions file (called functions.inc.php) which is inside an includes directory. The constant.inc.php file is also inside the includes directory.
Thank you.
function connect_to_db() {
  require("./constants.inc.php");
  $connection_id = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
  if (!$connection_id) {
    die("Database connection failed: " . mysql_error());
  }
  $db_selection_was_successful = mysql_select_db(DB_NAME, $connection_id);
  if (!$db_selection_was_successful) {
    die("Database selection failed: " . mysql_error());
  }
}

A:
Writing "./constants.inc.php" gives this error, but "constants.inc.php" doesn't (PHP seems to find the file just fine). Can someone tell me why the ./ notation doesn't work in this particular case? Perhaps it's something very simple I'm missing?

The only explanation I have is that PHP seems to be finding the constants.inc.php file in one of the directories in the include path - most likely C:\xampp\htdocs\websites\mathverse\includes.

A: even with or without ./ PHP will be searching for same file (in case of ./, it won't search in include_path) , and this means that constats.inc.php DOES NOT exist.
Try this one
require(dirname(__FILE__)."/../constants.inc.php");

A: Create the following heirachy:
index.php // echo 'I am in the top directory';
folder1/
    index.php // echo 'I am in folder 1';
    folder2/
        index.php // 'echo I am in foler' 2

on your top level index.php require folder1/index.php. From that require 'folder2/index.php';
This works no problem. However add a ./ before the folder2/index.php and you will get an error. It seems as once you specify which folder you want by using the ., it has to be relative to the current working directory. But if left open, the path will be checked in the calling scripts own directory too.
From the manual:

Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing. The include construct will emit a warning if it cannot find a file; this is different behavior from require, which will emit a fatal error.


text:
Q: Installing boost on macos I am trying to create a simple example using the boost library. I can successfully use CMake for the initial setup and it finds boost.

using the following code in CMakeLists.txt:
cmake_minimum_required(VERSION 3.18)
project(edge_detector)

find_package(Boost REQUIRED)
include_directories(${Boost_INCLUDE_DIRS})

add_executable(edge_detector main.cpp)
target_include_directories(edge_detector PUBLIC ${Boost_INCLUDE_DIRS})
target_link_libraries(edge_detector ${Boost_LIBRARIES})

However when I try to build the project using make or CMake --build . boost is not found and I am met with this error:

I am not sure what I am missing, I would be grateful for any help

A: Your include directive must include a file not a directory.
Replace
#include <boost/algorithm/string>

with
#include <boost/algorithm/string.hpp>


text:
Q: Process substitution with input redirection I am trying to understand input redirection in combination with process substituation. I am using bash 3
An example with tr is the following
$ tr "o" "a" <(echo "Foo")
tr: extra operand `/dev/fd/63'
Try `tr --help' for more information.

I think I understand why this does not work. The process substitution <( ) creates a file descriptor, where tr only reads from standard input.
How can I make it work with proper redirection?
I know that I could simply use pipes:
$ echo "Foo" | tr "o" "a"
Faa

However, I am trying to get a better understanding. I tried some thing with the help of man bash, by using <&, but I don't really know what I am doing.
How can I use process substitution properly using tr?

A: I found the Bash One-Liners Explained series very useful in understanding more about all this stuff.
Specifically the article linked above is all about input redirection.
To solve the specific example above:
> tr "o" "a" <<< $(echo "Foo")
Faa

A: You were really close:
tr "o" "a" < <(echo "Foo")

The substitution <() makes a file descriptor and just pastes the path to the shell. For comprehension just execute:
<(echo blubb)

You will see the error:
-bash: /dev/fd/63: Permission denied

That's why it just pastes /dev/fd/63 into the shell and /dev/fd/63 is not excutable, because it's a simple pipe. In the tr-example above, it's echo "Foo" that writes to the pipe and via input redirection < it's the tr command that reads from the file descriptor.


text:
Q: Where is the documentation for ATG Dynamo? Can anyone explain find a link to a pdf of any documentation at all that's online?
I have tried every search I can think of and have poured though many pages on Oracle's site. I asked more senior engineers at work for docs and links and have come up with nothing.

A: Found this after googling. Hope this helps:
https://docs.oracle.com/cd/E26180_01/Platform.94/ATGProgGuide/html/s0901coredynamoservices01.html
Also need to write more than 30 chars to able to post this.


text:
Q: How to execute code "under the hood" in my no-code platform As a learning project I started looking into how to mimic some basic features of a no-code platform. I usually code in Java/Python, have good knowledge over Javascript/HTML, but wanted to use this to pick up React or Vue frameworks. I am more of a backend dev than front end.
I understand the mechanics of the drag and drop of components, and the relationship graph flow representation in JSON for instance. What I am lacking knowledge about is how the JSON object is then loaded into an executable script, and how the execution is managed, especially when you have multiple users or even multiple flow running in parallel from the same user.
Any suggestions on how to accomplish this?
A very basic crude example:

*

*Each block is a drag and drop visual component within the web app ui.

*Which then is turned into its equivalent code script (say in Python)
 def sum(a,b):
   return a+b

 x=2
 y=3

 print(sum(x,y))

*The script is executed $ python diagramm.py > run1.log

*run1.log content shown within the web app

A: In the scenario you describe JSON is being used as a DSL. DSLs interpret "tokens" to create machine readable action. However, unlike real languages they require a custom parsing engine and typically have no IDE for that DSL.  This creates issue down the line in areas such as refactoring because the only tool available is Find/Replace editors.
DSL->Tokenizer->Code Generator->Runtime Inerpreter/Compiler->Executed code.
The term no-code is a misnomer ultimately, but refers to the fact the User doesn't have to code. In the end code is generated because computers do nothing without code.


text:
Q: I can't get the Nvidia driver to work, anyone any ideas? How can I install my Nvidia GT735m drivers. My laptop has optimus technology with a HD4000 as powersaving gpu besides the nvidia card. But I can´t get my gt735m to work. Everytime I try to install it I get a black screen after a reboot (which is unfixable, and if I manage to get the desktop interface back I can only run a 640x800 res.)
So... does anyone has a idea how to install this nvidia driver?
(ps. is it possible to disable my HD4000 and only run the nvidia card for everything including the desktop?)

A: can you give more information about what you have tried (to fix the black screen in particular) did you already try the suggestions in this question?
I don't have a optimus video card but I believe bumblebee is a project that is working on optimus support.
in general how you install drivers that are not standard included in ubuntu is this: go to system settings, go to 'software & Updates' open the 'Additional Drivers' tab let it search for proprietary drivers and have a look whether you can activate a driver.


text:
Q: Generics and IList related i have this code below -- a generic method which takes List as one of the input parameters. within the method, is an IF/ELSEIF statement, which runs into a common LINQ call.
Please help me out, so that the LINQ, call could be common to all the IF/ELSEIF's.
private Boolean filterList<T>(List<T> anyOutdoorSports, int numberOfPartcipants)
{
    if (anyOutdoorSports == null){ return false ;}
    Boolean _returnValue = false;

    if (anyOutdoorSports.GetType() == typeof(List<Swimming>))
    {
        List<Swimming> Swimming = anyOutdoorSports.Cast<Swimming>().ToList();

        if (Swimming.Count > 0)
        {
            int listCount = (from rca in Swimming
                             where (rca.RecordFields[numberOfPartcipants].ToString()).StartsWith("stamina")
                             select rca).Count();
            _returnValue = listCount > 0 ? true : false;
        }
    }
    else if (anyOutdoorSports.GetType() == typeof(List<Tennis>))
    {
        List<Tennis> Tennis = anyOutdoorSports.Cast<Tennis>().ToList();

        if (Tennis.Count > 0)
        {
            int listCount = (from rca in Tennis
                             where (rca.RecordFields[numberOfPartcipants].ToString()).StartsWith("stamina")
                             select rca).Count();
            _returnValue = listCount > 0 ? true : false;
        }
    }
    else if (anyOutdoorSports.GetType() == typeof(List<Soccer>))
    {
        List<Soccer> Soccer = anyOutdoorSports.Cast<Soccer>().ToList();

        if (Soccer.Count > 0)
        {
            int listCount = (from rca in Soccer
                             where (rca.RecordFields[numberOfPartcipants].ToString()).StartsWith("stamina")
                             select rca).Count();
            _returnValue = listCount > 0 ? true : false;
        }
    }

    return _returnValue;
}

THANKS TO ALL WHO VIEWED AND HELPED.

A: This is straightforward if there is a common base class for Tennis, Soccer and Swimming with a RecordFields property:
private boolean FilterList<T>(IEnumerable<T> anyOutdoorSports, int numberOfParticipants) where T : OutdoorSport
{
    if(anyOutdoorSports == null) return false;
    return anyOutdoorSports.Any(s => s.RecordFields[numberOfParticipants].ToString().StartsWith("stamina"));
}

A: Since all of your types seem to have an RecordFields property you could add an Interface and use that instead of the Generic.
Other than that you'd have to resort to Func<> expressions.

A: Assuming that all the classes inherit from the same base class, which contains RecordFields, you can create a generic constraint on the method and remove the ifs entirely.
private Boolean filterList<T>(List<T> anyOutdoorSports, int numberOfPartcipants)
  where T : OutdoorSport
{
    if (anyOutdoorSports == null){ return false ;}
    Boolean _returnValue = false;

    if (anyOutdoorSports.Count > 0)
    {
        int listCount = (from rca in anyOutdoorSports
                         where (rca.RecordFields[numberOfPartcipants].ToString()).StartsWith("stamina")
                         select rca).Count();
        _returnValue = listCount > 0;
    }

    return _returnValue;
}


text:
Q: Unclear formula for LED resistor calculation On this page:
LED Series Resistor Calculator and Formula
Vs, Vf and If can be filled in and the resistor is calculated.
The formula is even added: R = ((Vs - Vf) / If)
However, when e.g. filling in 5 Vs, 2 Vf, 0.02 If, Resistor is 125
While if I calculate it manually
R = ((5 - 2) / 0.02) = 150

To make it more unclear, when Vs == Vf, it is advised still to use a resistor and it gives a value (which it does), while the formula should give 0 ohm. So I have the idea the resistor value is calculated 'better', but the formula notation is wrong. But what is correct?


text:
Q: asp.net MVC cascading dropdownlist returns undefined using ajax Im trying to make a cascading dropdown list for Classes and Subjects, when I select a Class from the dropdown list the subject Dropdown shows subjects that are in the responding Class.
But the subject value that is returned in the controller is (Undefined)
Here is my view

        @Html.LabelFor(model => model.PDFClass, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownListFor(model => model.PDFClass, ViewBag.ClassName as SelectList, "Please Select", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.PDFClass, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.PDFSubject, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownListFor(model => model.PDFSubject, new SelectList(" "), "Please Select", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.PDFSubject, "", new { @class = "text-danger" })

here is the Ajax

Here is the method that gets a list of Classes&Subjects relation Table to the Ajax
        public JsonResult GetStateList(string Class)
        {

            var List1 = context.ClassesWithSubjects_.ToList().Where(i => i.ClassName == Class);
            return Json(List1, JsonRequestBehavior.AllowGet);
        }


text:
Q: OpenGL gl::GetUniformLocation fails to locate uniform only in certain cases I'm kinda stuck. I have a program abstraction to locate uniforms for me. I have a fragment shader with a float uniform elapsed, and a vertex shader with a mat4 uniform projection.
The helper function is defined as followed:
pub fn find_uniform(&mut self, name: &str) -> Result<(), UniformError> {
    if let Some(_) = self.uniforms.get(name) {
        return Ok(());
    }

    let target_location = unsafe {
        let location = gl::GetUniformLocation(self.program_id, name.as_bytes().as_ptr() as *const i8);
        let error = gl::GetError();
        if error != gl::NO_ERROR {
            return Err(UniformError::new(true, error));
        }

        location
    };

    if target_location < 0 {
        return Err(UniformError::new(false, UNIFORM_NOT_FOUND));
    }

    self.uniforms.insert(name.to_string(), target_location);

    return Ok(());
}

If I use the helper function to look for only elapsed or if i look for both with native gl calls it works:
// No error
if let Err(e) = program.find_uniform("elapsed") {
    eprint!("Failed to find elapsed, probably loading wrong shader. err: {}", e);
    return;
};

// OR
unsafe {
    let location1 = gl::GetUniformLocation(program.program_id, b"elapsed".as_ptr() as *const i8);
    println!("{}", location1); // 0
    let location2 = gl::GetUniformLocation(program.program_id, b"projection".as_ptr() as *const i8);
    println!("{}", location2); // 1
}

But if I use my helper function for both it fails to find whatever i look for first:
if let Err(e) = program.find_uniform("elapsed") {
    // Enters error branch here
    eprint!("Failed to find elapsed, probably loading wrong shader. err: {}", e);
    return;
};

if let Err(e) = program.find_uniform("projection") {
    eprint!("Failed to find projection, probably loading wrong shader. err: {}", e);
    return;
};

Does anyone have an idea of what I'm doing wrong?

A: Looking at your code, the conversion to name.as_bytes().as_ptr() as *const i8 is unsafe and depends on memory layout. Rust strings are not C-strings and are not null terminated by default. Use std::ffi::CString::new(); to ensure the string null-terminated. So your current program depends purely if you get lucky in having a null byte after your byte strings.
The following code should work:
let target_location = unsafe {
    use std::ffi::CString;
    let c_name = CString::new(name).expect("Convert to c-string");
    let location = gl::GetUniformLocation(self.program_id, c_name.as_ptr());
    let error = gl::GetError();
    if error != gl::NO_ERROR {
        return Err(UniformError::new(true, error));
    }
    location
};

See also:
How to pass data to openGL functions correctly in Rust


text:
Q: Bugged simultaneous edit In the following post: https://stackoverflow.com/posts/19760375/revisions
A user made a minor edit to my post (edit 3) by correcting a mistake at the same time that I made a larger but non-conflicting edit to the post (edit 2).
A few unexpected things happened as a result:

*

*The post showed the state after my edit, without his edit applied, although it said he made the last edit (under the post).

*When I attempted to edit the post, the markup and preview showed a combination of both of our edits (my edit with his edit applied), but this differed from the actual visible post (my edit only).

*The diff in the revision history showed that his edit undid mine, which differed both from the displayed text and the markup/preview in subsequent edits.

To merge both of our edits I had to edit the post, make a temporary change, submit it, re-edit the post, undo the temporary change, and submit it. After that it seemed to be OK.
While I understand there are some current issues with simultaneous edits, there is a lot going on here. Essentially this edit left three different and conflicting versions of the post at various points on SO:

*

*Revision history showed latest version (if you work through the diffs) as his edit only (edit 3 undid edit 2).

*Visible post showed my edit only (edit 2).

*Markup/preview in editor showed merged version (edit 3 and edit 2 merged).

That's a big potential mess for posts with more complex formatting.


text:
Q: Connecting two computers residing on different networks using python I am developing a voice + audio chat app. I have successfully created the web app which runs on the computers residing on the same network. Now I want to make upgradation in my project and want to connect the computers of different networks. I ave developed the web app in python. Please tell me how to connect the two computers over the different network using python only?

A: Port forwarding - this one explains how to port forward on specific routers. Basically what you want to do is port forward any ports used by the server of your web app (this is usually only the port 80 for web apps) on your local router. Then find out your global IP somewhere like What is my ip?. After that you can connect to the server from anywhere outside your local network using your global IP.


text:
Q: How to remove given item from comma separated list? $list = 'Mon,Tue,Wed,Thrs,Fri,Sat,Sun';

Is there a regex or a function that will work as follows?
1)"Tue"       return string ->"Mon,Wed,Thrs,Fri,Sat,Sun"
2)"Thrs, Mon"     return string ->"Tue,Wed,Fri,Sat,Sun"
3)"Sun,Wed,Fri"       return string ->"Mon,Tue,Thrs,Sat"
4)"Fri"     return string ->"Mon,Tue,Wed,Thrs,Sat,Sun"

Below works fine for removing just one item from the string. What if I want to remove more than one item like above?
$input = 'Wed';
$list = 'Mon,Tue,Wed,Thrs,Fri,Sat,Sun';
    $array1 = Array($input);
    $array2 = explode(',', $list);
    $array3 = array_diff($array2, $array1);

    $output = implode(',', $array3);

    echo $output;

A: Use explode on the $input variable as well:
$input = 'Wed';
$list = 'Mon,Tue,Wed,Thrs,Fri,Sat,Sun';
$array1 = explode(',', $input);
$array2 = explode(',', $list);
$array3 = array_diff($array2, $array1);

$output = implode(',', $array3);

echo $output;

A: you can store your list in array or just can explode it if you dnt want
 function weekdays($day){
    $list= array('Mon','Tue','Wed','Thrs','Fri','Sat','Sun');
    if (($key = array_search($day, $list )) !== false) {
        unset($list[$key]);
        return $list;
       }
    }


text:
Q: Norm of Inverse of sums of positive definite matrices. Consider a symmetric positive definite matrix $R > 0 $ and a symmetric  positive semi-definite matrix $P \ge 0$. Does this hold?
$$\|(R + P)^{-1} \| \le \| R^{-1} \|? $$
and does this hold too?
$$\|(R + P)^{-1} \| \le \| R^{-1} \| \le \frac{1}{\| R \|}?  $$

A: Yes, it holds. It is a non-trivial fact that if $A,B$ are real and symmetric (more generally, selfadjoint) and $A\leq B$ (i.e. $B-A$ is positive semi-definite) then $\lambda_j(A)\leq\lambda_j(B)$, where $\lambda_1(A)\geq\lambda_2(A)\geq\cdots\geq\lambda_n(A)$ are the eigenavalues (counting multiplicities).
From the above, then $\lambda_n(R+P)\geq\lambda_n(R)$, so (with the operator norm)
$$
\|R^{-1}\|=\frac1{\lambda_n(R)}\geq\frac1{\lambda_n(R+P)}=\|(R+P)^{-1}\|.
$$
More generally, for any Ky-Fan norm,
$$
\|A\|_{(k)}=\sum_{j=1}^k\lambda_j(A)^\downarrow,
$$
since we are dealing with positive matrices the eigenvalues are the singular values. So
$$
\|(R+P)^{-1}\|_{(k)}=\sum_{j=n-k+1}^n\frac1{\lambda_j(R+P)}\leq
\sum_{j=n-k+1}^n\frac1{\lambda_j(R)}=\|R^{-1}\|_{(k)}.
$$
As the inequality holds for all Ky-Fan norms, it holds for all unitarily invariant norms.

The inequality $$\tag{*}\|R^{-1}\|\leq\frac1{\|R\|}$$ can only hold for the spectral norm if $\|R\|\,\|R^{-1}\|=1$ (because you always have $\|R\|\,\|R^{-1}\|\geq1$). This equality is $\lambda_1(R)/\lambda_n(R)=1$, i.e. $\lambda_1(R)=\lambda_n(R)$. So the inequality $(*)$ holds only for scalar multiplies of the identity (and, in such case, it is an equality).


text:
Q: Issues with Python 3 absolute import from script within package I feel that this is a rather basic issue, so I'm only more upset that I wasn't able to fix it for quite some time. Say I have the following folder structure:
foo
|- first_module.py
|- __init__.py
|- bar
   |- second_module.py
   |- __init__.py

foo and bar being directories. In first_module.py I have an absolute import statement referring to second_module.py:
import foo.bar.second_module

Now, if run first_module.py as a script (foo being the working directory), I get this error
ModuleNotFoundError: No module named 'foo':

Please, can anyone explain to me why this is the case? I've checked that foo is in sys.path. I've read the docs and a bunch of other stackoverflow posts. I think it might have to do with the interpreter not knowing that first_module.py is part of the package foo. But how can I fix this?

A: The problem is that trying import foo.bar.second_module would require that your directory structure have a foo directory as a child of your current working directory, i.e.:
foo
|- first_module.py
|- __init__.py
|- foo
   |- bar
      |- second_module.py  <-- at foo.bar.second_module
      |- __init__.py

To keep your original directory structure and import successfully, simply change your first_module to use import bar.second_module instead.

why this is the case?

When importing, you should think of the dots . as analogous to path separators. Thus, using the following sample layout:
foo
|- first.py
|- bar
   |- second.py
   |- third.py

If you want to import module second.py from first.py, you must write import bar.second. If you want to import third from second, you can write import third because they're both in the same directory.
Note that you'd still need to write import bar.third if trying to import from first.


text:
Q: Action button invoke service web I am beginner in angular and i want to add to add button an action that invokes a web service that sends itself to a node server to add a user. i work on a template (nebular-ngx) .
enter link description here
this the code of my add button with angular4
 add: {
  addButtonContent: '',
  createButtonContent: '',
  cancelButtonContent: '',
},

i wonna add an action who invoke a service web and send it to a node server
this is my hole code
import { Component } from '@angular/core';
import { LocalDataSource } from 'ng2-smart-table';

import { SmartTableData } from '../../../@core/data/smart-table';

@Component({
selector: 'ngx-smart-table',
templateUrl: './smart-table.component.html',
styles: [`
nb-card {
  transform: translate3d(0, 0, 0);
  }
 `],
 })
  export class SmartTableComponent {

settings = {
 add: {
   addButtonContent: '',
    createButtonContent: '',
   cancelButtonContent: '',
   },
  edit: {
  editButtonContent: '',
  saveButtonContent: '',
  cancelButtonContent: '',
  },
  delete: {
  deleteButtonContent: '',
  confirmDelete: true,
  },
  columns: {
  id: {
    title: 'ID',
    type: 'number',
    },
    firstName: {
    title: ' Name',
    type: 'string',
    },
    email: {
     title: 'E-mail',
    type: 'string',
    },
    password: {
    title: 'password',
    type: 'password',
  },
   },
  };

source: LocalDataSource = new LocalDataSource();

constructor(private service: SmartTableData) {
const data = this.service.getData();
this.source.load(data);
}

onDeleteConfirm(event): void {
if (window.confirm('Are you sure you want to delete?')) {
  event.confirm.resolve();
} else {
  event.confirm.reject();
 }
 }
 }

A: You can use your button click event to make the service call from component:
<button class="btn btn-primary" (click)="makeServiceCall($event)">Add</button>

In component:
makeServiceCall(e) {
       this.myAngularService.makeHttpRequest().subscribe((response: Response) => {
            // my response here
        }, (error: any) => {
            console.log(error);
        });

}

Inside myAngularService, make use of angular's HttpClient to make the service call:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class myAngularService{
  constructor(private http: HttpClient) { }

  makeHttpRequest() {
      return this.http.get<any>('my_service_url);
  }
}


text:
Q: How to add a vertex vertically in this template (or with tkz-graph ) Please help me draw a graph like this(see hand-drawing pic) in Latex ? I have found a template which has clean Latex in it. I am trying to add some vertices vertically without any success, Here is what I have so far.  This is what I am trying to achieve. It is not necessary to this template.

A: Welcome to TeX.SE! The directions \WE, \SO etc. stand for west, south etc. This allows you to do vertical and horizontal connections as you like.
\documentclass[border=10pt]{standalone}
%%%<
\usepackage{verbatim}
%%%>
\begin{comment}
:Title: Drawing a graph
:Tags: Graphs;Computer Science
:Author: Stefan Kottwitz
:Slug: graph

In graph theory, models and drawings often consists mostly
of vertices, edges, and labels. So, it may be possible,
to use a simpler language for generating a diagram of a graph.

The tkz-graph package offers a convenient interface.

The code is fully explained in the LaTeX Cookbook, Chapter 11,
Science and Technology, Application in graph theory.
\end{comment}
\usepackage{tkz-graph}
\GraphInit[vstyle = Shade]
\tikzset{
  LabelStyle/.style = { rectangle, rounded corners, draw,
                        minimum width = 2em, fill = yellow!50,
                        text = red, font = \bfseries },
  VertexStyle/.append style = { inner sep=5pt,
                                font = \Large\bfseries},
%  EdgeStyle/.append style = { bend left}
  }
\thispagestyle{empty}
\begin{document}
\begin{tikzpicture}
  \SetGraphUnit{3.5}
  \Vertex{A}
  \EA(A){B}
  \EA(B){C}
  \EA(C){D}
  \EA(D){E}
  \SO(A){F}
  \SO(B){G}
  \SO(D){H}
  \SO(E){I}

  \Edge[label = 1](A)(B)
  \Edge[label = 2](B)(C)
  \Edge[label = 3](C)(D)
  \Edge[label = 4](D)(E)

  \Edge[label = 5](A)(F)
  \Edge[label = 6](B)(G)
  \Edge[label = 7](D)(H)
  \Edge[label = 8](E)(I)

  \Edge[label = 9](F)(G)
  \Edge[label = 10](H)(I)

\end{tikzpicture}
\end{document}


text:
Q: For each container not failing when it is returning 0 rows I have a for each container in my SSIS package.Inside that i have a script task in it.For each loop is iterating an object variable containing result from an Execute SQL task.
Everything is fine but the problem is for-each loop is not failing even when no rows are returned by previous sql task.
I want the package should fail when zero rows are returned.What should id do?

A: I generally don't like to have packages fail just because the conditions for running aren't met. "Fail" can mean a phone call in the middle of the night. If this is something that needs to be addressed immediately, that's fine, but if it's not, I'd suggest a graceful exit instead.
A first thought would be to add another Execute SQL task in front of the one you have. In that task, execute the query you're using, but just return a row count, then pass that count to a variable. Then have two precedent constraints coming away from the new Execute SQL task.
Connect your first constraint to your existing Execute SQL task, but add a condition that your row count variable has to be >0.
Create another constraint with the condition that row count ==0. Connect that to, for instance, a Send Mail task that will generate an email saying there were no rows to process, and let the package execution end there.

A: To have your package fail when there are no rows in the object variable, add an OnPostExecute Event Handler to the Execute SQL Task before the Foreach Loop.  In this Event Handler, create a Script Task that checks for existing rows in the object variable, then raises an error if none are found.  A DataTable object can be used as outlined below for this, and of course you can include whatever information in the error message that you need.  On the Script Task, the FailPackageOnFailure property will need to be set to true.
 Although raising the error will already fail the package this prevents subsequent tasks from being executed.  The following outlines this further and a reference to the System.Data.OleDb namespace is necessary for this example.
        OleDbDataAdapter od = new OleDbDataAdapter();
        System.Data.DataTable dt = new System.Data.DataTable();
        od.Fill(dt, Dts.Variables["User::YourObjectVariable"].Value);

            if (dt.Rows.Count > 0)
                {
           //If no processing is necessary, nothing needs to be done here.
                }
            else
               {
           Dts.Events.FireError(0, "Error", "No rows were available.", String.Empty, 0);
               }


text:
Q: Safari giving "kCFErrorDomainCFNetwork error 303" when visiting a site I am currently having problems visiting archive.org
example link
Safari 12 (and 13 b4) on Mojave shows the following error:
kCFErrorDomainCFNetwork error 303

Things I've tried:

*

*disable all extensions

*Develop > Empty Caches

*trashing Safari.plist

*booting into Safe Mode

*recovery mode + Disk Utility First Aid

*different DNS servers

All have had no effect.
Strangely, the problem does not appear in Safari Technology Preview, Chrome, Opera or Tor.

A: OK, this solution is the strangest thing. I found the solution on a Russian site, but now that the search terms for the solution are known you can find at some other sites.
The problem is a result of Safari holding too much local data for the site in question and failing to deal with that correctly. I use archive.org a lot so I had lots of LocalStorage and Cookie data for that site. The fact that this data is only in Safari, and none of my other browsers explains why they could browse the site just fine.
So, the solution:

*

*Go into Safari > Preferences > Privacy

*Search for "archive.org"

*Click Remove

*The problem goes away

Here's a video showing the problem before and after: https://imgur.com/gallery/d1P1FCi

I've reported this to Apple with full logs as radar #14814758.


text:
Q: How to write setHttpResponseCode() in magento 2 Observer In Magento 1.x I m writing below code in Observer -
Mage::app()->getResponse()->setHttpResponseCode(403);
Mage::app()->getResponse()->clearBody();
Mage::app()->getResponse()->sendHeaders();

Now I want to write same functionality in Magento-2 Observer. Please let know what Injunctions need to implement and how to write above code.

A: First you need to inject the following class in your observer constructor: \Magento\Framework\App\ResponseInterface for example:
protected $_response;

public function __construct(
    ...
    \Magento\Framework\App\ResponseInterface $response
) {
    ...
    $this->_response = $response;
}

Then in your code you can do:
$this->_response->setHttpResponseCode(403);
$this->_response->clearBody();
$this->_response->sendHeaders();


text:
Q: Sendgrid Inbound Parse Webhook Emails are not received on Sendgrid I am using the SendGrid for receiving the emails from my domain (example.com). I have configured all the steps from the mentioned link Sendgrid Inbound Parse Webhook.
I have added all the name records(MX records and CNAMES) in the GoDaddy DNS records against my domain.
The issue is when I send an email to hello@example.com. When an email is sent to this email-id there is no mail delivery failure report. There is no any statistics for the SendGird console about the webhook got triggered.
I am not able to figure out what went wrong in this process. As emails in the sendgrid webhook are not received.
I think they are lost in between.

A: I found the documentation to be insufficient in this area. You need to send to the subdomain, listed in your MX record, which redirects mail to sendgrid.
For example, if you add a MX record for email.example.com, you need to send the email to user@email.example.com.

A: One of the best ways to test if a 3rd party Web API post is being triggered or not is by using a tool that receives posts and provides visibility to the data sent along with the post (e.g. Headers, parameters, and the related data in json, text, etc).
One of the tools that I have used to test if a post is being triggered or not is offered by:  https://requestbin.fullcontact.com/.  Take these steps to set-up your testing environment:
(note: I am not associated with the requestbin.fullcontact.com resource - I am just an enthusiastic fan of this very useful service).

*

*Go to requestbin and "Create a RequestBin".  This will create your own unique requestbin URL. (e.g. https://requestbin.fullcontact.com/xxxxx)

*Copy this URL, and paste it into your SendGrid Inbound Parse "Destination URL".

*Keep your testing environment simple initially by NOT checking the "Additional Options" (Check incoming emails for spam & Post the raw...).

*Be sure you do not enter a 'Subdomain' in the SendGrid Inbound Parse "Receiving Domain" unless you are expecting users to use the subdomain as part of your email address.

*Re: #3, same applies to your DNS at GoDaddy.  Your email should also not reflect a 'subdomain' as part of your MX record (e.g. you should not use mail.example.com).

*Click "Add".

*Now, send an email to your domain (e.g. info@example.com).

*Check your requestbin to see if a post was made by using your unique requestbin URL, appended with "?inspect"  (e.g. https://requestbin.fullcontact.com/xxxxx?inspect).
Result:  You should see post information when viewing your 'inspect' URL.
Using this first step of a diagnostic process to test your usage of SendGrid's Inbound Parse should help expose potential problems in your configuration (e.g. DNS set up would be the next area to look at if no post data is being received in the requestbin inspect URL).  Good luck.


text:
Q: Binding checkbox to model and check/unchecking it in Angular I have a the following HTML:

        <input type="checkbox" id="cbxAcceptTest" ng-checked="{{test.IsAccepted}}"  ng-click="testSelection($event,{{test}})" />

and the testSelection method as :
$scope.testSelection = function ($event, test) {
    if (test.IsAccepted) {
        alert('accept');
    }
    else {
        alert('reject');
    }

};

I am not able to trigger this method on ngClick, It works on ngChecked, but then I have to use ngModel, which Ive read does not go with ngChecked in the following link.

A: In my case I have something like this:

        <input type="checkbox" ng-model="item.auto" ng-click="onAutoClick(item)" />

In my controller:
$scope.onAutoClick = function(item) {
  if(item.auto){
     // checked (true condition)
  } else  {
     // unchecked ( false condition)
  }

};

A: Just remove the curly braces around test when you pass it as a parameter.

A: Please check this Plnkr.
In HTML you need remove your curly braces

        <input type="checkbox" id="cbxAcceptTest" ng-checked="{{test.IsAccepted}}"  ng-click="testSelection(test)" />


text:
Q: Extracting the n-th elements from a list of named tuples in pandas Python? I am trying to extract the n-th element from a list of named tuples stored in a df looking like this:
df['text'] = [Tag(word='Come', pos='adj', lemma='Come'), Tag(word='on', pos='nounpl', lemma='on'), Tag(word='Feyenoord', pos='adj', lemma='Feyenoord')]

I am trying to extract only elements that contain the pos information from each tuple. This is the outcome that I would like to achieve:
df['text'] = ['adj', 'nounpl', 'adj']

This is what I have tried this far:
d =[]
count = 0
while count < df['text'].size:
    d.append([item[1] for item in df['text'][count]])
    count += 1
dfpos = pd.DataFrame({'text':d})
df['text']= pd.DataFrame({'text':d})

df['text']=df['text'].apply(lambda x: ', '.join(x))

And this is the error: IndexError: tuple index out of range
What am I missing?
Solution: It seems that the easiest solution is to turn the tuples into a list. I am not sure if this is the best solution, but it works.
d =[]
count = 0
while count < df['text'].size:
    temp=([list(item[1:-1]) for item in df['text'][count]])
    d.append(sum(temp, []))
    count += 1

df['text']= pd.DataFrame({'text':d})

df['text2']=df['text'].apply(lambda x: ', '.join(x))

A: Try indexing using apply if Tag is your named tuple i.e
Data Preparation :
from collections import namedtuple
Tag = namedtuple('Tag', 'word pos lemma')
li = [Tag(word='Come', pos='adj', lemma='Come'), Tag(word='on', pos='nounpl', lemma='on'), Tag(word='Feyenoord', pos='adj', lemma='Feyenoord')]
df = pd.DataFrame({'text':li})

For attribute based selection use . in apply since its a named tuple i.e
df['new'] = df['text'].apply(lambda x : x.pos)

If you need an index based selection then use
df['new'] = df['text'].apply(lambda x : x[1] if len(x)>1 else np.nan)

Output df['new']

0       adj
1    nounpl
2       adj
Name: text, dtype: object

Another solution is use str[1] for select value in namedtuple:
df['text1'] = df['text'].str[1]
print (df)
                          text   text1
0            (Come, adj, Come)     adj
1             (on, nounpl, on)  nounpl
2  (Feyenoord, adj, Feyenoord)     adj


text:
Q: Order of execution in constructor initialization list Is order of execution in constructor initialization list determinable? I know that members order in a class is the order in which those members will be initialized but if I have scenario like this:
class X()
{
X_Implementation* impl_;
};

and then providing that allocator is available:

X::X():impl_(Allocate(sizeof(X_Implementation)))//HERE I'M ALLOCATING <--1
,impl_(Construct<X_Implementation>(impl_))//AND HERE I'M CONSTRUCTING <--2
{
}

but in order for this to be dependable this order MUST be from left to right. Is it guarantied by GREAT BOOK OF std:: or not? If not I can always move the second line into the body.

A: According to ISO/IEC 14882:2003(E) section 12.6.2:

Initialization shall proceed in the following order:

*

*First, and only for the constructor of the most derived class as described below, virtual base classes shall
be initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph
of base classes, where "left-to-right" is the order of appearance of the base class names in the derived
class base-specifier-list.

*Then, direct base classes shall be initialized in declaration order as they appear in the base-specifier-list
(regardless of the order of the mem-initializers).

*Then, nonstatic data members shall be initialized in the order they were declared in the class definition
(again regardless of the order of the mem-initializers).

*Finally, the body of the constructor is executed.

So, follow that order, and you'll have your order. Also according to the standard, the order is prescribed as such so that objects can be uninitialized in the precisely reverse order.

A: Your specific scenario is based on the idea of initializing the same member more than once. This is plain illegal in C++. Your code will not compile. So, the question you are asking doesn't really exist.
The order of member initialization is the order of their declaration in class definition. In no-inheritance contexts that covers everything related to the order of initialization in the constructions initializer list.

A: The C++ standard does guarantee an order for initialization lists (ISO C++ Standard 12.6.2/5):

...nonstatic data members shall be initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

(See Wyatt Anderson's answer for more information.)
Example:
class Foo
{
public:
    Foo();
private:
    A a;
    B b;
    C c;
};

Foo::Foo() : b(), a(), c() {
    // a is initialized first, then b, then c - NOT b, a, then c!
}

However, you can't initialize a variable twice - what you have won't compile.
class X //() what's with the pair of parentheses you have in your code snippet?
{
public:
    X();
private:
    X_Implementation* impl_;
};

X::X():
    impl_(Allocate(sizeof(X_Implementation))),
        // It is not allowed to initialize a data member twice!
    impl_(Construct<X_Implementation>(impl_)) {
}

Instead, just put the extra work into the constructor:
X::X() : impl_(Allocate(sizeof(X_Implementation))) {
    impl_ = Construct<X_Implementation>(impl_);
}

There may be exception safety issues with the above code, but without knowing what Allocate() or Construct() actually does I'm not able to tell. I can tell you that it's best to separate allocation and construction into their own classes if you do that, using the Resource Acquisition Is Initialization (RAII) idiom:
class XBase
{
protected:
    XBase() : impl_(Allocate(sizeof(X_Implementation))) { }

    ~XBase() {
        if( !impl_) { Deallocate(impl_); } // Or something like this
    }

    X_Implementation* impl_;
};

class X : private XBase // XBase is an implementation detail
{
public:
    X() {
        impl_ = Construct<X_Implementation>(impl_);
    }

    ~X() {
        Destruct<X_Implementation>(impl_); // Or something like this
    }
};

This way, if Construct() throws an exception, you won't leak memory since the base class destructor will be called which will deallocate the memory pointed by impl_. This is important because if the exception is not caught and leaves the constructor, its matching destructor will not be called. See Bjarne Stroustrup's paper on exception safety.


text:
Q: How can I add arguments to run() method in java? How can I add input arguments to run method in java threading?
@Override
public void run(int a, String b){
    // do something
}
// The method run(int) of type particle_explode must override or implement a supertype methodJava(67109498)

If I add argument, it said The method run(int) of type particle_explode must override or implement a supertype methodJava(67109498)
So how can I add argument to it?

A: Put the values to the Runnable and have the Thread run that.
Runnable r = new MyRunnable(a, b);

new Thread(r).run();

If you need a convenient way to run a variety stuff in the background, submit() runnable things to an Executor.


text:
Q: ESXi 5 - Custom build iscsi or openfiler? This is for a development environment, NOT a production environment. We have 2 ESXi 5 hosts that is currently using their own local disks for storage. We have a very large Supermicro server that has 16TB of diskspace. We're thinking of either installing Openfiler or installing RH 5 and configuring iSCSI ourselves. What are some of the drawbacks to going the RH route?
I thought I read somewhere that Openfiler doesn't work too well w/ VMware. I'm not sure if this is the case w/ Openfiler 2.99.
Thanks

A: It could be the hardware I used, but periodically the openfiler would freeze up and required a reboot, about a year ago. However, judging by your needs it is probably adequate. However, the new version could have improved.
RH is simpler to set up for me as I am more familiar with it and can have full control easily. Openfiler has another problem that I did not quite figure out in file permissions and ownership, if you go the nfs route. If you use iscsci however, it is just a block device so it is easier.
So I would say RH if you are a linux guy, and openfiler if you are not, because the latter provides a web gui to configure things very quickly and easily, for those who has no prior linux/bsd experience.


text:
Q: Recovering/Removing the BIOS password of a Toshiba Satellite M35-S320 I have this Toshiba Satellite M35-S320, with a BIOS password. The problem is, I was a bonehead and had no idea what I was doing when I set a (random) password.
I forgot the password immediately.
Is there any way to reset or recover the BIOS password?
Remember, I CANNOT BOOT INTO THE OS, BOOT MENU, BIOS SETUP, ANYTHING. I am locked out of this thing.
A thing I would like to know:
Some people on the internet talk about BIOS password hashes. This "hash"
does not appear when I fail. It just says, "Too many attempts! The system will
be powered off!"
Note: I have already tried removing the battery, trying "Toshiba", and holding down the Left Shift key.
I really hope I can get this thing working. :(

A: I haven't used a Satellite in years, but doing some research, I find several possible options:

*

*Try 'Toshiba' as a password.

*Hold left-shift key down during boot.

*Open the PC and remove the battery for at least an hour.


text:
Q: Can we get more than one value from the proximity sensor per second? I need to detect the change in proximity sensor values per second and further use it in calculations. I tried the Android SDK method. But I found out that only one change or lesser, ( near->far or far->near ) can be detected per second. Is it a performance issue? I used SENSOR_DELAY_FASTEST. I also tried it on two different phones ending up with the same result.
Will I get a higher frequency if the NDK is used?
If yes, how to get real time change per second values using the NDK? (NDK programming is too complex and beyond my scope).
I did try programming this in the NDK but all is got was constant values like 4.85016E-14.
Help appreciated!


text:
Q: AWS Fargate connection to RDS in a different VPC I have following setup:

*

*ECS (Fargate) cluster in VPC-1

*RDS in VPC-2

My application running in ECS uses DNS name to connect to RDS however instead of private IP DNS resolves public IP address.
In RDS I want to configure strict security rules to prevent connections from the outside world - I would like to limit it to only accept connections from VPC-1.
I tried following things:

*

*peering both VPC-1 and VPC-2 - doesn't help, app running in ECS still resolves public IP

*routing all outbound traffic (0.0.0.0/0) from ECS cluster to a NAT gateway (instead internet gateway) and configuring security group in RDS to accept connections from elastic IP configured for NAT gateway - in this case my app doesn't even want to start, I suspect this is due to the fact that provisioning process fails due to the fact that outbound traffic is routed via NAT

*all VPCs have "DNS resolution" and "DNS hostnames" set to "yes"

I'm running out of ideas how to configure it correctly. As soon as I allow all inbound traffic (0.0.0.0/0) for my RDS everything starts to work fine but I don't want that.
What am I missing here? Maybe I should use entirely different approach to secure access to my RDS?

A: I managed to solve the problem by using approach with NAT gateway - I'm not sure why it did not work earlier, I changed approach to first create VPC and then create ECS cluster and associate it with previously created VPC.

*

*Created Elastic IP, NAT gateway, VPC with private and public subnets as described in this article: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-public-private-vpc.html

*NAT gateway is associated with private subnet

*Created ECS cluster in private subnet

*Created load balancer and associated it with public network

*Modified security group for RDS to allow traffic from Elastic IP configured on previously created NAT gateway.
With this setup any traffic from application to RDS goes via NAT so I can setup security group rules to allow for this traffic. On another hand, load balancer in public subnet is able to communicate with cluster that sits in private network.


text:
Q: Fanpage tab redirect to app canvas We are creating a canvas app and would like to add directly to my fanpage.
There are 2 ways that I'm not sure about how to take the user to the app's fanpage.
First would be to create a tab and add it in the fanpage.
On this tab would have some text and a call-to-action to redirect to app canvas.
Would create a second tab and add it in the fanpage only with a redirect to take the user directly to the fanpage of the app.
Is there any documentation specific to this practice or some restriction to redirect the tab?

A: To see if your app was loaded inside a page tab, parse the signed_request server-side and look if there is a page-id set.
If so, answer that request with a minimal HTML document containing not much more than a piece of JavaScript code to redirect inside the top window instance, like this:
top.location.href = "https://apps.facebook.com/yourappsnamespace";

There should be no restrictions on that – Facebook is only worried about automatically redirecting users away from Facebook (to outside domains), but since you are redirecting to a canvas app, they stay on their site.

A: The docs clearly state:

We do not accept Canvas pages that redirect to Page Tabs, or vice
  versa.


text:
Q: como obtener ultimo resultado de un group by Duda existencial :D
Tengo este query que me trae un un valor acumulado; pero solo necesito el ultimo valor de cada grupo pero el group by siempre toma el primer valor :( . Alguna sugerencia?
//// QUERY
SELECT t.id,YEAR(fecha),MONTH(fecha),
@running_total:=@running_total + total_efectivo+ total_facturado AS acumulado
FROM
( SELECT id_hist as id, date(fecha) as fecha, sum(tipo_pago) as total_facturado ,sum(total) as total_efectivo
FROM `historico`
GROUP BY fecha)t JOIN (SELECT @running_total:=0) r

id
año
mes
acumulado

1
2019
5
1110

12
2019
5
1830

21
2019
5
3020

32
2019
5
3580

38
2019
5
4385

48
2019
5
5345

60
2019
5
6650

72
2019
5
7440

81
2019
6
7830

84
2019
6
7970

Al agrupar el resultado es: agrego el GROUP BY MONTH(fecha)

id
año
mes
acumulado

1
2019
5
1110

81
2019
6
7830

Lo esperado o deseado es:

id
año
mes
acumulado

72
2019
5
7440

84
2019
6
7970

De antemano muchas gracias a quien me pueda explicar qué puedo hacer, aportaría enormemente a mi aprendizaje.

A: Estás teniendo el típico problema del GROUP BY en MYSQL. Y digo en MySQL porque hay otros sistemas gestores que te impiden proyectar un campo por el que no agrupas sin totalizar. Supongo que tarde o temprano terminará por imponerse esta restricción para evitar estos descuidos.
No es que te enseñe el primer registro, sino que podría enseñarte cualquiera. Lo que no puedes hacer es pedir que te muestre un campo de los que cambian en ese grupo. Puedes pedirle el MAX(), el MIN(), e incluso el GROUP_CONCAT() para que te los muestre todos, pero no uno sin más, porque el sistema gestor no sabe cuál darte y te da cualquiera, habitualmente el primero que se encuentra.
En tu caso, como necesitas el último id de cada grupo, entiendo que un MAX(id_hist) id resolvería tu problema, porque supongo que irás registrando y asignando los autonuméricos en orden.
Espero haber respondido a tu pregunta. Si necesitas más detalles, déjame cualquier duda en los comentarios.

A: Esto se resuelve muy facil a partir de MySql 8.0 con windows function, pero entiendo por tu query que están trabajando con alguna versión anterior.
Una solución que se me ocurre es utilizar una variable @aniomes que contiene la concatenación del año y el mes. Ordenando por id DESC utilizas una sentencia CASE, si el valor de la variable @aniomes != CONCAT(anio, mes), seteamos la variable con el año y el mes, y aparecerá en el resultado como la columna ultimo; sino, si coinciden ambos entonces la columna quedará con valor null.
Conclusión: el último registro de cada grupo (año y mes) contendrá el año y el mes concatenado en la columna ultimo, las demás filas contendrán null.
Luego filtras solo las filas en las cuales la columna ultimo no es nula.
Hice la query sobre el resultado de tu query (la tabla que sale en la pregunta, yo le llamé t), tu la tendrás que adapatar, ya que no cuento con la estructura y datos de prueba de las tablas reales.
SET @aniomes:=0;

SELECT id, anio, mes, acumulado
FROM (SELECT *,
             CASE WHEN @aniomes != CONCAT(anio, mes) THEN @aniomes:=concat(anio,mes) END AS ultimo
      FROM t
      ORDER BY anio, mes, id DESC) AS sq
WHERE ultimo IS NOT NULL
ORDER BY anio, mes;


text:
Q: React Modal confirm doesn't work properly I'm new to ReactJS. In my component AllHeroes.js I expect when I click Delete, a Modal shows Yes/No option.
This is the reference: https://react-bootstrap.github.io/components/modal/
However the Modal doesn't show as a popup, it appears right below the form without any style.
Here is my code of AllHeroes.js
import React, { Component } from 'react';
import { Link, BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import AddHero from './AddHero';
import EditHero from './EditHero';
import { Button, ButtonToolbar, Modal } from 'react-bootstrap';

class AllHeroes extends Component {
  constructor(props) {
    super(props);

    this.state = {
      show: false
    }

    this.OnEditHandle = this.OnEditHandle.bind(this);
    this.OnDeleteHandle = this.OnDeleteHandle.bind(this);
    this.handleShow = this.handleShow.bind(this);
    this.handleClose = this.handleClose.bind(this);
  }

  OnEditHandle(id) {
    //const id = arguments[0];
    window.location = '/Edit/' + id;
  }

  OnDeleteHandle(id) {
    debugger
    this.setState({
      show: true
    })
  }

  handleClose() {
    this.setState({ show: false });
  }

  handleShow() {
    this.setState({ show: true });
  }

  render() {

    let closeModal = () => this.setState({ show: false })

    return (

All Heroes

              Id
              Name
              Dob
              Stocked
              Price

            {
              this.props.GetAllHeroes().map(item => (

                  {item.Id}
                  {item.Name}
                  {item.Dob.toLocaleString()}
                  {item.Stocked.toString()}
                  {item.Price}
                  <button onClick={() => this.OnEditHandle(item.Id)}>Edit</button>
                  <button onClick={() => this.OnDeleteHandle(item.Id)}>Delete</button>

              ))
            }

        <Modal show={this.state.show} onHide={this.handleClose} animation={true}>
          <Modal.Header closeButton>
            <Modal.Title>Delete</Modal.Title>
          </Modal.Header>
          <Modal.Body>Are you sure to delete this Hero?</Modal.Body>
          <Modal.Footer>
            <Button variant="secondary" onClick={() => this.handleClose}>
              No
            </Button>
            <Button variant="primary" onClick={() => this.handleClose}>
              Yes
            </Button>
          </Modal.Footer>
        </Modal>

    );
  }
}

export default AllHeroes;

Please help to display the Modal properly as this reference.

A: You forgot to import the Bootstrap stylesheets. You can clearly see it with the "Button" and "Modal" component.
As stated in the react-bootstrap documentation :

Because React-Bootstrap doesn't depend on a very precise version of Bootstrap, we don't ship with any included css. However, some stylesheet is required to use these components.

You should then also install bootstrap in your project
npm install --save bootstrap
yarn add bootstrap

And import the .css file in your src/index.js
import 'bootstrap/dist/css/bootstrap.css';

A: here you go add:
import 'bootstrap/dist/css/bootstrap.css'


text:
Q: scala: FOO cannot be cast to FOO In Scala, I am incredibly confused by this fairly tautological error message:
java.lang.ClassCastException: FOO cannot be cast to FOO

I would expect that someone can always be cast to its own type.

Context
I am trying to run the following wrapper around the scala compiler, located at http://code.google.com/p/rooscaloo/source/browse/trunk/rooscaloo/src/org/darevay/rooscaloo/Interpreter.scala Unfortunately, Scala is saying ResultHolder cannot be cast to ResultHolder when I do the following:
import org.darevay.rooscaloo._
println(new Interpreter().eval("2"))

I thought println was supposed to accept Any. What should be going on is that Interpreter.eval returns a ResultHolder type, such that ResultHolder.value would be equal to 2.
Additionally, trying to print .value doesn't work with the error:
(fragment of Test.scala):3: error: value value is not a member of Any
println(new Interpreter().eval("2").value)

More details
java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        ...
Caused by: java.lang.ClassCastException: org.darevay.rooscaloo.ResultHolder cannot be cast to org.darevay.rooscaloo.ResultHolder
        at binder0$.set(<script>:1)
        at binder0.set(<script>)
        ... 24 more (unsure how to print them)

Though I am a Scala newbie, perhaps the internal mechanism binder of the scala.tools.nsc.interpreter package is trying to do something weird.
I'm invoking the script as scala Test.scala.

Question
My question is: What is the cause of this error message, what is the real issue, and how does one get working sample code for scala.tools.nsc.[interpreter]? Thanks.

A: I've run into similar issue, and I've converted my code to use IMain#mostRecentVar introduced in Scala 2.9. Here's from CompilerMatcher I wrote:
  val main = new IMain(s)
  main.compileSources(files.map(toSourceFile(_)): _*)
  code map { c => main.interpret(c) match {
    case IR.Error => error("Error interpreting %s" format (c))
    case _ =>
  }}
  val recent = main.mostRecentVar
  val holder = main.valueOfTerm(recent)
  if (holder != Some(expected))
    println("actual: " + holder.map(_.toString).getOrElse{"None"})


text:
Q: Is there a command to insert symbols from the nomenclature into the main document similar to /gls for glossary entries? I'm using the nomencl package for the first time after initially building my list of symbols using the glossaries package before realizing this was not appropriate.
However, from the documentation it does not seem like the nomencl package allows you to insert an already-defined symbol using a keyword as you can in glossaries using the \gls{} command.
Example from my document:
\usepackage{glossaries}
\makeglossaries

% Define glossary entry
\newglossaryentry{SAG}{name={SAG},description={semi-autogenous grinding mill}}

\usepackage[nocfg]{nomencl}
\makenomenclature

\begin{document}

\printglossary
\printnomenclature

% Use already-defined glossary entry
The most common type of tumbling mill is the semi-autogenous grinding mill (\gls{SAG}).

\begin{equation}
    p(k) = \frac{B(q^{-1})}{A(q^{-1})} w_p(k),
\end{equation}
where $p(k)$ is the generated disturbance signal.
% Add symbol to nomenclature
\nomenclature{\ensuremath{p(k)}}{disturbance signal at time $k$}%

% Re-use glossary entry
The \gls{SAG} is ...

I would like to replace all instances of p(k) in the document with something like \gls{pk} (but for nomenclature entries).
The main reason I would like to do this is in case I need to change the notation of a symbol throughout the document.


text:
Q: Three phase commit protocol I'm trying to understand the three phase commit protocol by reading the wiki page (http://en.wikipedia.org/wiki/Three-phase_commit_protocol#Motivation). In the description for the diagram I posted below, it says the following: "If the coordinator succeeds in the prepared state, it will move to the commit state. However if the coordinator times out while waiting for an acknowledgement from a cohort, it will abort the transaction. In the case where all acknowledgements are received, the coordinator moves to the commit state as well."
Is that a typo where it says "coordinator moves to the commit state as well?" Isn't it already in the commit state? Does it mean "the cohort moves to the commit state as well?" Seems like it kind of says the same thing twice.


text:
Q: how to prevent dataframe columns being classed as character instead of numeric Good morning.
I am cycling through some data, building a dataframe as I go.   Every time I add or replace a row in the dataframe, numeric values get classed as character, and I have to re-class them.  I assume I am doing something wrong when adding the data to the dataframe ?
test.df<-data.frame(SIDE=rep("",5),n=rep(NA, 5),c1=rep(NA,5),stringsAsFactors=FALSE)
test.df[1,]<-cbind("A",1,256)
test.df[2,]<-cbind("A",2,258)
test.df[3,]<-cbind("A",3,350)
test.df[4,]<-cbind("A",4,400)
test.df[5,]<-cbind("A",5,360)
summary(test.df)
 SIDE                n                  c1
  Length:5           Length:5           Length:5
  Class :character   Class :character   Class :character
  Mode  :character   Mode  :character   Mode  :character

Convert the numeric columns to numeric:
test.df[, c(2:3)] <- sapply(test.df[, c(2:3)], as.numeric)
summary(test.df)
 SIDE                 n           c1
 Length:5           Min.   :1   Min.   :256.0
 Class :character   1st Qu.:2   1st Qu.:258.0
 Mode  :character   Median :3   Median :350.0
                    Mean   :3   Mean   :324.8
                    3rd Qu.:4   3rd Qu.:360.0
                    Max.   :5   Max.   :400.0

So the dataframe is now as I expect it - 1 column of character data and 2 of numeric. However if I change one of the rows again:
test.df[5,]<-cbind("A",5,360)
summary(test.df)
 SIDE                n                  c1
 Length:5           Length:5           Length:5
 Class :character   Class :character   Class :character
 Mode  :character   Mode  :character   Mode  :character

it has gone back to all character!
Is there any way to ensure that when I append/change data in the dataframe that it keeps the appropriate classes ?
Thanks, Pete

A: cbind("A",5,360) is a matrix, which can hold only one type, i.e. character in your case.
Use the data.frame method:
cbind.data.frame("A",5,360)

However, "cycling through some data" is probably the least efficient way to do this in R.

A: When you form a matrix, it is all of the same mode, so this cbind("A",1,256) is all character mode. (There is a cbind.data.frame function but none of the arguments to cbind were data.frames, so it was not called. You could have done this:
test.df<-data.frame(SIDE="A",n=1,c1=256,stringsAsFactors=FALSE)
test.df<- rbind( test.df,
                  list("A",2,258),
                  list("A",3,350),
                  list("A",4,400),
                  list("A",5,360) )
 test.df
#---------------
  SIDE n  c1
1    A 1 256
2    A 2 258
3    A 3 350
4    A 4 400
5    A 5 360

A: Just had a similar problem, and the quickest way (I think) is to set options(stringsAsFactors=FALSE)


text:
Q: Simple way to convert expression to a list? I know that I can convert an expression to list by
List @@ expr

But this does not work if expr is atomic, e.g.,
List @@ 1

will give you 1 instead of {1}. Of course I can check the length of expr first. But I wonder if there is simpler way to do this.

A: Like J.M. wrote, the question is if the expression is atomic, because Apply doesn't work on atomic expressions.
If we disambiguate the two cases we should be fine:
Listify = If[AtomQ[#], {#}, List @@ #]&

Listify[42]
(* {42} *)

Listify[foo[1, 2, 3]]
(* {1, 2, 3} *)

A: ClearAll[toList]
toList = # /. { _[a__] :> {a}, a_?AtomQ :> {a}} &;

Examples:
list = {2, a, foo[a, b], s + t + u, Rational[1, 3],
   Complex[5, 6], <|a -> x, b -> y, c -> z|>, DateObject[]};

Grid[Prepend[Transpose[{list, toList /@ list}],
  Item[#, Background -> LightBlue] & /@ {"expr", "toList@expr"}],
 Dividers -> All]


text:
Q: How can i fix the code so the progressBar1 will show the percentages from 0% to 100%? In jumps of 1 steps 1%...2%...3%...4%...5%
What happen now is few things. First the code is working fine the backgroundworker is start calling the Convert method and it's getting to the backgroundworker completed event. Not sure if the completed event is needed at all.
You can see in button1 click event i set this labels first time with the number of frames. and progressBar1 maximum.
The problems are:

*

*On label12 i see 290 as maximum of progressBar1 but in fact there are only 280 frames, On label14 it's showing that there are 280 frames count.

*In the end of the process i see on label12 the value 281 but there are 280 frames why it's counting to 281 ?

*The percentages on label11 not moving at all it's staying on 0% all the time.
On form1 load event:
private void Form1_Load(object sender, EventArgs e)
        {
            RichTextBox1.Visible = false;
            ProgressBar1.Value = 0;
            Button5.Enabled = false;
            KB = 1024;
            MB = KB * 1024;
            GB = MB * 1024;
            psiProcInfo = new ProcessStartInfo();
            prcFFMPEG = new Process();
        }

On button1 click event
private void Button1_Click(object sender, EventArgs e)
        {
            OFD = new OpenFileDialog();
            if (OFD.ShowDialog() == DialogResult.OK)
            {
                mFile = new MediaFile(OFD.FileName);
                InputFile = OFD.FileName;
                pathResult = Path.GetFileNameWithoutExtension(OFD.FileName);
                Label3.Text = "Name: " + pathResult;
                if (mFile.FileSize > 1070000000)
                {
                    Label4.Text = "FileSize: " + String.Format("{0:0.00}", mFile.FileSize / KB / MB) + " GB.";
                }
                else
                {
                    Label4.Text = "FileSize: " + String.Format("{0:0.00}", mFile.FileSize / MB) + " MB.";
                }
                Label5.Text = "Duration: " + mFile.Video[0].DurationString;
                Label6.Text = "Format: " + mFile.Video[0].Format;
                Label7.Text = "Codec: " + mFile.Video[0].CodecID;
                Label8.Text = "Resolution: " + mFile.Video[0].FrameSize;
                Label9.Text = "Framerate: " + mFile.Video[0].FrameRate;
                Label14.Text = "NumberOfFrames: " + mFile.Video[0].SourceFile.FrameCount.ToString();
                Label15.Text = "VideoStreams: " + mFile.Video[0].StreamType + " " + mFile.Video[0].StreamIndex;
                FCount = int.Parse(mFile.Video[0].SourceFile.FrameCount.ToString());

                ProgressBar1.Maximum = FCount + 10;
                Label12.Text = ProgressBar1.Maximum.ToString();
            }
        }

The Convert method that in there i'm doing the calculations of the reporting the progress to the progressBar1 and labels.
private void Convert()
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            if (ComboBox1.SelectedIndex == 3)
            {
                strFFCMD = " -i \"" + InputFile + "\" \"" + OutputFile + "\"";
            }

            if (ComboBox1.SelectedIndex == 2)
            {
                strFFCMD = " -i " + (char)34 + InputFile + (char)34 +
                " -c:v libx264 -s 1280x720 -pix_fmt yuv420p -qp 20 -profile high444-c:a libvo_aacenc -b:a 128k -ar 44100 -ac 2 " + OutputFile;
            }
            psiProcInfo.FileName = exepath;
            psiProcInfo.Arguments = strFFCMD;
            psiProcInfo.UseShellExecute = false;
            psiProcInfo.WindowStyle = ProcessWindowStyle.Hidden;
            psiProcInfo.RedirectStandardError = true;
            psiProcInfo.RedirectStandardOutput = true;
            psiProcInfo.CreateNoWindow = true;
            prcFFMPEG.StartInfo = psiProcInfo;
            prcFFMPEG.Start();
            ffReader = prcFFMPEG.StandardError;

            do
            {
                if (Bgw1.CancellationPending)
                {
                    return;
                }
                Button5.Enabled = true;
                Button3.Enabled = false;
                strFFOUT = ffReader.ReadLine();
                //Show each read line in the richtextbox
                RichTextBox1.Text = strFFOUT;
                if (strFFOUT != null)
                {
                    if (strFFOUT.Contains("frame="))
                    {
                        currentFramestr = strFFOUT.Substring(7, 6).Trim();
                        Regex rx = new Regex(@"^\d+");
                        Match m = rx.Match(currentFramestr);
                        if (m.Success)
                        {
                            currentFrameInt = System.Convert.ToInt32(m.Value);
                        }
                    }
                }

                string percentage = System.Convert.ToInt32((ProgressBar1.Value / ProgressBar1.Maximum * 100)).ToString() + "%";
                ProgressBar1.Maximum = FCount + 1000;
                ProgressBar1.Value = (currentFrameInt);
                Label12.Text = "Current Encoded Frame: " + currentFrameInt;
                Label11.Text = percentage;
            } while (!(prcFFMPEG.HasExited || string.IsNullOrEmpty(strFFOUT)));
        }

Then the backgroundworker dowork event:
private void Bgw1_DoWork(object sender, DoWorkEventArgs e)
        {
            Convert();
        }

I'm not using the backgroundworker progresschanged event and completed event.
Just used a break point on the completed event and saw it's getting there in the end.
Now some values i get using a break point inside the Convert method. I added a breakpoint on the line:
if (m.Success)
                        {
                            currentFrameInt = System.Convert.ToInt32(m.Value);
                        }

First time the value in m.Value is "9"
Then "17"
And it finish stop getting to the completed event on "17"
Now i'm not using a break point at all.
The first value is "9" in the end it's 281 i could see that near the end it jumped from 269 to 281.
This is a screenshot of the form1 when the process completed using a break point:

Current Encoded Frame : 17 thats Label12
NumberOfFrames: 280 thats Label14
The 0% on the right of the progressBar1 that never change and stay on 0% all the time is Label11
And this is a screenshot of form1 without using any break point:

In top of form1:
private Process prcFFMPEG;
private ProcessStartInfo psiProcInfo;
private string strFFCMD;
private StreamReader ffReader;
private string strFFOUT;
private string currentFramestr;
private int currentFrameInt;

A: *

*As @Stephen Ross mentioned you are setting label12 = ProgressBar1.Maximum = FCount + 10 = Framecount + 10 = 280 + 10 = 290

*You are getting the value of label12 from ffReader = prcFFMPEG.StandardError;. It is hard to say anything without knowing this process prcFFMPEG. But I guess it is returning the error value frame=281 at the end. But there could also be something wrong with your Trim or your RegEx.

*To solve Issue 3, you should cast your ProgressBar1 values to double:
label11 = percentage = ... = ((double)ProgressBar1.Value / (double)ProgressBar1.Maximum * 100.0)


text:
Q: Is it possible to control the orientation of another app started through implicit intent? In my app, I have to show a video in Youtube. When the user press a button, I start this video through the following implicit intent, passing the url of the video in Youtube.
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.video_url))));

This starts another app, like the Youtube app.
My doubut is:
Is it possible to make the youtube app play a video only in landscape or portrait orientation?

A: yes add permission on android manifeast


text:
Q: OpenSUSE "fstab" "mount" "An error occurred while accessing" "the system responded: mount: only root can mount" Gentlemen,
I trying to mount a network share at OpenSUSE's boot, when I try to access the folder where the share is mounted (using Dolphin) the system returns me the following error (edited):
"An error occurred while accessing ..." "... The system responded: mount: only root can mount ..."
How to solve?

A: To resolve this issue use the parameters "x-systemd.automount" and "cache=none" in the share to be mounted using fstab.
Example:
//192.168.56.1/Data/DEV/ /home/brlight/DEV/ cifs auto,x-systemd.automount,cache=none,users,username=eduardo,password=questor 0 0

I'm not sure about that, but it seems that this problem occurs for two reasons: 1 - The network is unavailable when the system tries to mount the share; 2 - When you using the parameter "x-systemd.automount", the UI (KDE) try to mount the share when needed or inherits some kind of permission to mount the share!
I appreciate comments and possible corrections!
Thanks to kaipee!
Source: https://bbs.archlinux.org/viewtopic.php?pid=1168782


text:
Q: Revoke access of microsoft/outlook account using outlook or graph rest API I'm using Microsoft Graph API for integration of microsoft/outlook calendar in my app.
API reference is here
I want to revoke user's access of their calendars from my app but didn't find any way to do so. I tried with following api but no luck:
DELETE https://graph.microsoft.com/v1.0/users/{user_id}

A: Well, that command would delete the user entirely. So while that would certainly remove them from the calendar, I'm guessing this isn't the outcome you're looking for. :-)
If you're looking to remove the permission for your app, there are a couple of ways to trigger this:

*

*Simply stop requesting that user's calendars from your app. This won't revoke permission to the calendar however so this likely isn't sufficient.

*Drop Calendars.Read and Calendars.ReadWrie from your list of requested scopes.

*

*In order to ensure this change is reflected in the user's account, you'll need to re-authenticate the user with the query param prompt=consent auth URI.

*Have the user revoke permission for your application entirely. This is done by visiting https://myapps.microsoft.com.

*

*There are certain apps that a user cannot directly revoke. These are apps who were granted access at the organization level. To revoke these, an Administrator will need to do this in the Azure Portal.


text:
Q: between and overlaps to be used interchangeably What is the difference between "BETWEEN" AND "OVERLAPS" in postgresql?
can you provide an example? is it possible to have a NULL value in the overlaps syntax
(NULL, x) OVERLAPS (?, ?).

A: With a, b, c integers, a between b and c means just what it means in plain english:
b <= a and a <= c

With a, b, c, d integers, [a,b] overlaps [c,d] means they've elements in common:
not(b <= c) and not(d <= a)

(Mind bounds when dealing with overlaps.)
The null value means infinity when dealing with range types.

Examples:
denis=# select int4range(-1, 0), int4range(0, 1);
 int4range | int4range
-----------+-----------
 [-1,0)    | [0,1)
(1 row)

denis=# select int4range(null, 0), int4range(0, null);
 int4range | int4range
-----------+-----------
 (,0)      | [0,)
(1 row)

denis=# select int4range(null, 0) && int4range(0, null) as test;
 test
------
 f
(1 row)

denis=# select int4range(null, 1) && int4range(0, null) as test;
 test
------
 t
(1 row)


text:
Q: inssert  for the 1st comma & replace all the dot with  How can I insert
 for the first comma, and for every dot (period)?

Hi,Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto, optio, dolorum provident rerum aut hic quasi placeat iure tempora laudantium ipsa ad debitis unde? Iste voluptatibus minus veritatis qui ut.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iusto, optio, dolorum provident rerum aut hic quasi placeat iure tempora laudantium ipsa ad debitis unde? Iste voluptatibus minus veritatis qui ut.

A: you can call replace again:
var result = test.replace(/\./g,'.
').replace(',', '
');

A: If you need to replace first comma, you can use something like this:
var test = $('.test').text();
first_comma=test.indexOf(','); //return first comma position
test=test.replace(test.charAt(first_comma),',
') //replace it
var result = test.replace(/\./g,'.
');
$('.test').html(result);

Demo: https://jsfiddle.net/4jgyj98c/

A: You need to call the jquery part after loading jquery, and also to use
$(document).ready(function(){
  var test = $('.test').text();
  var result = test.replace(/\./g,'.
');
  // var result = test.split('.').join('.
');
  $('.test').html(result);
})

will be a good prectice. so put all your code into this function.
I also mention another way to do it. you can try that as well. both will do the same.


text:
Q: How to Disconnect a python DBus connection? I made some kind of answering machine for pidgin client that uses Linuxes DBus to make connection with pidgin. the code is this:
class DBus_Answer():
    def __init__(self, text = "No text"):
        self.answer = text
        bus_loop = DBusQtMainLoop(set_as_default=True)
        self.bus = dbus.SessionBus()
        self.bus.add_signal_receiver(self.pidgin_control_func,
                                     dbus_interface="im.pidgin.purple.PurpleInterface",
                                     signal_name="ReceivedImMsg")

    def pidgin_control_func(self, account, sender, message, conversation, flags):
        obj = self.bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject")
        purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface")
        purple.PurpleConvImSend(purple.PurpleConvIm(conversation), self.answer)

now I want to use it as a module in another program. I called it like this:
answering_machine.DBus_Answer(message)

the problem is, when I stop the second program (the program that has this one as a module) and then start it again, I'll get a segmentation fault because it want to make another connection to the DBus and it seams it's not regular!
Other wise I want to give the chance of disabling this module to user. I tried to use an if statement. It will work for the first time. but if user run the module for once, he can't disable it any more.

A: segmentation faults occur because in a python module (written in C) a pointer is NULL, or because it points to random memory (probably never initialized to anything), or because it points to memory that has been freed/deallocated/"deleted".so your problem is probably with your memory.try trace the segfault using methods described here


text:
Q: Remove hidden controls At run time, I have to decide whether to display a bunch of controls or not.
I'm working on this form:
My form
In some cases, i would like to hide all controls but "Row font size" label, its Combobox and "Close" button. When doing so, i want to move the remaining components up and resize the main form so it looks nice.
As suggested in the comments, i tried to use FlowLayoutPanel with panels.
One panel for CheckedBoxList, One panel for each pair (label, Combobox) as i want to keep Labels and ComboBoxes in the same line.
With this solution, i have two issues:

*

*More components to manage: I have to hide the panel now instead of other initial components

*Auto-resize is not working any more: If I resize the main form, inner components doesn't change size any more.

Also, I looked at the TableLayoutPanel, and it doesn't look an option for me as i have different number of columns in each row. First row, I have only a CheckedBoxList and in the second row a have a label and a combobox...
Any suggestion to address this issue and keep the Auto-resize feature for all controls?

A: In Winforms, it uses a grid kind of layout in the background. So you have to take control of the layout yourself. The easiest way to do this is to create a method called RefreshLayout() and call this method anytime you hide or show the button. So your condition will look like this:
if (condition)
{
    buttonDown.Hide();
    RefreshLayout();
}

In the RefreshLayout() method, you need to determine if the button is hidden or visible and then move all the controls below the button up or down by the button size. Also, you may want to change the height of the form itself. So it will look something like this:
public void RefreshLayout()
{
    int offset;

    if (buttonDown.Visible)
    {
        // The button is visible
        offset = buttonDown.Height;
    }
    else
    {
        // The button is hidden
        offset = buttonDown.Height * -1;
    }

    // For each control under the button...

    control1.Location.Y = control1.Location.Y + offset;
    control2.Location.Y = control2.Location.Y + offset;
    // and so forth, for each control
}


text:
Q: Disable streaming of a shared video I work in a corporate office, I am in charge of distributing the training videos.  I have all 100+ training videos shared over the network.  The plant managers open the videos in WMP so it's essentially streaming off the computer where the videos are stored.  The issue is that the videos are on my personal PC. So the streaming bogs down my internet connection.  Is there any way to disable the streaming?
I want them to have to download the video to their workstations and then watch it.

A: The only way you could get users to download the video first (without streaming) is to instruct them to do so. There's no magic way to instruct their computers to download it first. And even if you did instruct them to do this, you would still experience lag in your connection. There is no difference between "streaming" (playing while downloading) and downloading (playing the file after downloading) They're still downloading it from you and using bandwidth. (Read @ScottChamberlain's comment)
You said you do not want to move the files off of your computer or move them to a cloud service, so you've essentially locked yourself out of all viable solutions.

However, an alternative solution to fix your slow network speed problem would be to put your computer behind a router and use QoS to limit file sharing services outbound. This would be taking place on TCP port 445. Their computers would simply take longer to buffer (while streaming) or download. The downside to doing this is all outbound file sharing traffic from your computer on this port would become throttled.


text:
Q: Wifi Router That Allows me to assign devices a frequency Current Setup
Wifi: 1 Google Wifi router running version 12371.52.22
Living: Big city high rise with crowded 2.4 spectrum.  Our apartment is ~840 sqft.
Troubleshooting: 97% of our devices work fine & are not impacted by the collisions on the 2.4 frequency. But, I wish Google Wifi was better at the automatic channel changing. As I write this, an analyzer shows 20+ networks, with ~5 of them are on my same 2.4 channel. Google Wifi currently doesn't support manual channel changing, but I digress. Because this frequency is very commonly crowded, 2 of our work devices do not work on that frequency, we believe due to the speed combined with our work VPNs. Currently we are stuck disconnecting & reconnecting wifi until it switches back to the 5 ghz frequency, where we never have any issues.
Possible Solutions: We are looking at a different routers, but want one that still combines the two frequencies (2.4 & 5) into one SSID. There is a lot of benefit for this as we have a few legacy devices that require 2.4 & dont want to have to keep switching back and forth networks to use certain devices. But since 2.4 seems to be the issue for our work laptops, we are looking for a system that we can assign a device to ALWAYS connect using a certain frequency. We have looked at "client side" solutions; but both work laptops are pretty locked down, which makes configuration changes nearly impossible. Our last option would be to run a cat5 cable, but this isn't ideal for a few reasons...
Given the context does anyone have any suggestions on how we can solve for our issue(s)?
Is there a router out there that does what we are in need of?
Is there a better setup that would be achieves our goal?
...
Thank you!