text:
Q: Find line in text file, check for text in between? Question about Batch/Windows/CMD:
I would like that my batch file can search for a line (which I already achieved, but what comes next not), it looks like this:
<name>MyName</name>

It needs to find the text in between <name> and </name>. After that it needs to set that as a variable (%name%).
Does anyone have any idea?
EDIT: if someone wants to give an answer, please list the code. Perl is OK, but this should be open-source and not everyone has Perl.

A: It can be done this way (assuming your input is in file "test1.html"):
findstr "<name>" test1.html > temp1.lis
FOR /F "tokens=2 delims=>" %%i in (temp1.lis) do @echo %%i > temp2.lis
FOR /F "tokens=1 delims=<" %%i in (temp2.lis) do @echo %%i > temp3.lis

The first line is a guard that only HTML/XML tag
"name" will match in the two FOR lines  (you may
already have done this). The result is saved in a temporary
file, "temp1.lis".
The second line capture what is to the right of the first
">" - in effect what is after "<name>". At this stage
"MyName</name" is left in temporary file "temp2.lis" (as
the closing tag also contains ">"). Note the double "%"s
(%%i) as this is in a BAT file (if you want to test directly
from the command line then it should only be one "%").
The third line capture what is to the left of the first "<"
- this is the desired result: "MyName" (is left of "<" in
"MyName</name"). The result is in variable %%i and you
can call a function with %%i as a parameter and access the
result in that function (in the FOR line above the function
was the built-in "echo" and the result thus ended up in
temporary file "temp3.lis" by the redirection of standard
output)

Note that the above only works if
<name>MyName</name>

is the first HTML/XML tag in a line.
If that is not the case or you want a more robust solution
you can instead call a function in the first FOR line (that
receives %%i as the first parameter). That function can then
replace "<name>" with a single character that you are
sure is not in the input, e.g.:
set RLINE=%MYLINE:<name>=£%

Explanation: if the input line is in variable %MYLINE% then
"<name>" will be replaced with "£" and the result will be
assigned to variable %RLINE%.
The reason for the replace is that the delimiters for the
FOR loop are single character only.
You can then use "£" as a delimiter in the FOR loop (to extract what is
to the right of "<name>" - as before):
echo %RLINE%>temp5.lis
FOR /F "tokens=2 delims=£" %%i in (temp5.lis) do @echo %%i > temp6.lis

You have to repeat this technique for "</name>"
(but only if <name>MyName</name> is not
the first HTML/XML tag in a line).
So as you see it is possible, but is quite painful.

A: Learn Perl, it's made for exactly that kind of thing.


text:
Q: There are [community-standards] here? The community-standards (30 questions, no tag wiki) tag here on Meta Stack Exchange seems unclear. It seems to imply some sort of social standard or community consensus is happening or being requested, but that's not really clear or helpful. We have several more specific tags related to rules of conduct and behavior that more specifically identify the problematic or potentially problematic conduct issue and that should be used instead.

*

*Questions about how to interpret, enforce, or adjudicate the Code of Conduct should be tagged code-of-conduct.

*Questions about the now-obsolete Be Nice Policy should be tagged be-nice-policy.

*Questions about the acceptability or unacceptability of certain social behaviors, unconnected with any specific policy, should be tagged behavior.

*Questions about the boundaries of specific kinds of unacceptable or potentially problematic behavior should be tagged with the applicable behavior, such as spam, abuse, serial-edits, and serial-voting.

*Questions about what sort of questions are on-topic or off-topic should be tagged off-topic.

*Questions about when it is acceptable or desirable to upvote or downvote a post should be tagged voting, up-votes, and/or down-votes.

Could we burninate these nonexistent community standards?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Struts2: Autopopulating fields based on a dropdown value without JavaScript I tried searching the site but could not find an answer to my question.
i am developing a java Struts2 web application.
There are 3 form fields on a jsp page as follows:
(Struts2 tags are being used)
<s:form action="action1">

other fields
......
<s:select name="test1" list="{'A','B','C'}"></s:select>
<s:textfield name="test2"></s:textfield>
<s:textfield name="test3"></s:textfield>
.....
other fields
<s:submit value="submit1"><s/submit>
</s:form>

when a value is selected in test1 field, test2 and test3
would needed to be populated from the database based on the
value selected in test1.
as per the process i need to implement, i need to do some calculations based on the input from jsp1(presented above), and present the result on jsp2 which has to have entirely different content from jsp1. My issue is limited to the data entry in jsp1.
what would be the best way of doing this without javascript?
assume that javascript is disabled in the browsers accessing
the application.
thanks,

A: EDIT
It seems that there's a bit of confusion here, let's try to make it clear:
There are basically three ways of triggering a communication with the server from the browser:

*

*submit HTML

*submit JS

*AJAX submit

You may or may not care about giving support to users browsing with JavaScript disabled;

*

*if you DO NOT care, then you can proceed as you wish;

*if you DO care, then you have two ways in front of you:

*

*make an unique version of the pages, that works both with and without JS (by using ONLY option "1", "submit HTML");

*make the pages working in two possible ways, mutually exclusive: while processing the page, you detect if the user has javascript enabled: if yes, you go with JS (submit  or AJAX), if not, you fallback to the non JS solution ( "submit HTML" ).

Both this two solutions works with and without JS, but the latter is generally preferred because you can set up a nice, good-looking, user's experience-oriented WebApp for the 99% of the users, by using JavaScript and eventually AJAX, and create a fallback solution for the 1% of the users that, even if the site won't be nice as in the JS version, and even if it won't have ALL the features of the JS version, it would still be usable, and the core functionalities will be available.
As I said in the comment above, there is no need for the fallback version of the WebApp to be as nice, as fast, as good in user experience as the JS version: it should simply... work.
For example, this JSP will work in both cases: it will do a JavaScript Submit after selecting an element from the Select if JS is enabled, and it will do a submit after pressing the Submit button if JS is disabled.
With JS disabled, onchange will be ignored and  processed.

With JS enabled, onchange will be processed and  ignored.
<s:form action="myAction">
    <s:select    onchange="javascript:document.forms[0].submit();"
                 name="test1" value="test1" list="{'A','B','C'}"  />
    <s:textfield name="test2" value="test2" />

            Since you have JS disabled,
            you need to manually press to the GO button,
            but you still can make it work ;)

        <s:submit    value="go" />

</s:form>

in your Action
public class MyAction extends ActionSupport{

    private String test1="";
    private String test2;
    /* Getters and Setters */

    public String execute(){
        if (test1.length()>0)
            assignValues();
        return SUCCESS;
    }

    private void assignValues(){
        if (test1.equals("A")){
            test2 = "A was chosen, do something";
        } else if (test1.equals("B")){
            test2 = "B was chosen, do something else";
        } else if (test1.equals("C")){
            test2 = "C was chosen, what's next?";
        }
    }
}

The other doubts you are expressing in comments suggest that you may want to step back for a moment and read some Struts2 tutorial, to be sure of gaining the maximum from the framework.
If you have other fields in the same Form that you don't want to be affected, just declare a variable in the Action (with the Getter and the Setter), for each one of them: they will be preserved in the reloaded page, because they will be sent (because they're in form) with the submit, they will be injected through the Setter, they will be read back through the Getter and injected in the new page by the matching with their name and the Action variable.
Otherwise you could use AJAX, but I'd start from this.
And no, you can't nest forms.

A: Thanks to Andrea Ligios, i have the below solution to my issue.
jsp1 was changed as below
<s:form action="action2">

other fields
......
<s:select name="test1" list="{'Select','A','B','C'}"
    onchange="javascript:document.forms[0].submit();"></s:select>
<s:submit value="populate test2 and test3"></s:submit>
<s:textfield name="test2"></s:textfield>
<s:textfield name="test3"></s:textfield>
.....
other fields
<s:submit value="submit1" action="action1"><s/submit>
</s:form>

struts.xml has following mappings
.....
<action name="action2" class="MyAction" method="populate">
    <result name="success">/jsp1.jsp</result>
</action>
<action name="action1" class="MyAction">
    <result name="success">/jsp2.jsp</result>
</action>
.....

MyAction has following code
public class MyAction extends ActionSupport{

    //all field declarations

    //Getters and Setters

    public String execute(){

    //do processing for jsp2 based on values from jsp1

    return SUCCESS;
    }

    public String populate(){

    //populate test2 and test3 from database based on value of test1

    return SUCCESS;
    }
}


text:
Q: Static files not being served on using :slug When I got to http://localhost:8090/ or http://localhost:8090/about my static files work.
But if I visit any of the posts for example http://localhost:8090/posts/lorem-ipsum I get GET error in browser console. ( tried to server file from path http://localhost:8090/posts/css/style.css )
Server.js
`
app.use(express.static(path.join(__dirname, "ShowAnime")))
app.use('/', require(__dirname + "/ShowAnime/route.js"))

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
    console.log(__dirname, path)
})

`
routes
`
router.get(['/', '/home'], (req, res) => {
    res.sendFile(path.join(__dirname, "index.html"))
})

router.get(['/watch', '/watch/:slug'],
(req, res) => {
    res.sendFile(path.join(__dirname, "Video.html"))
})

module.exports = router

`
the path of the static files seem to change on using slugs


text:
Q: Any workable way to use Python scripts with scipy and numpy libraries and Unity? I want to use Unity to create some kind of GUI for some my data analysis scripts made with Python language.
I tried to use IronPython by using this guide Use Python with Unity3D Guide, but had a problem with numpy library. I found a non-ideal solution here - it's about tinynumpy.
However the using of scipy isn't possible by this way.
Is the any solution to use Python libraries and Unity with no limits?

A: Why do you want to use python with unity? It doesnt make sense for me but it might just be me. I would actually reonmend you using another game engine if you are going to be using pyrhon, such as the godot game egine. It's main laguage is the same as python.


text:
Q: mview refresh: atomic_refresh on Oracle 11g I have an Oracle database 11g with several Materialized Views that I want te refresh nightly. I did create a procedure that is scheduled within Oracle.
In that procedure I use the following syntax to refresh the MV:
BEGIN
 DBMS_MVIEW.REFRESH(' MV_1','C', atomic_refresh=>false);
END;

MV_1 looks like follows:
SELECT
    /*+ NO_PARALLEL(adres@db2) */
    a.n a_nr ,
    c.c_nr ,
    a.i id ,
    b.name ,
  FROM TABLE(pck_1.fnc_1) a
  JOIN b b
  ON a.i = b.id
  JOIN adres@db2 c
  ON a.n = c.nr;

Please note the databaselink for the table ADRES and the TABLEtype I recieve from the function FNC_1
The query run's fine, and takes about 5 minutes.
Running SELECT TABLE(pck_1.fnc_1) FROM DUAL also takes about 5 minutes and returns a table with two columns (I and N).
But when I execute the procedure to refresh the MV I'm getting an ora-12840 Error:
Error starting at line 1 in command:
BEGIN
 DBMS_MVIEW.REFRESH(' MV_1','C', atomic_refresh=>false);
END;
Error report:
ORA-12008: Fout in pad voor vernieuwen van snapshot.
ORA-12840: Kan externe tabel niet benaderen na een parallelle transactie of een transactie voor direct invoegen.
ORA-06512: in "SYS.DBMS_SNAPSHOT", regel 2566
ORA-06512: in "SYS.DBMS_SNAPSHOT", regel 2779
ORA-06512: in "SYS.DBMS_SNAPSHOT", regel 2748
ORA-06512: in regel 2
12008. 00000 -  "error in materialized view refresh path"
*Cause:    Table SNAP$_<mview_name> reads rows from the view
           MVIEW$_<mview_name>, which is a view on the master table
           (the master may be at a remote site).  Any
           error in this path will cause this error at refresh time.
           For fast refreshes, the table <master_owner>.MLOG$_<master>
           is also referenced.
*Action:   Examine the other messages on the stack to find the problem.
           See if the objects SNAP$_<mview_name>, MVIEW$_<mview_name>,
           <mowner>.<master>@<dblink>, <mowner>.MLOG$_<master>@<dblink>
           still exist.

When I change the value of the atomic_refresh procedure to true, the procedure completes succesfully.
So here is my question:
I do give the atomic_refresh parameter the value of FALSE to force a truncate of the MV so the refresh of the MV is faster. As a side affect it creates multiple sessions (parallel) which causes my SQL error. Adding the parameter PARALLILISM=>0 didn't gave any results.
Is it possible to refresh a materialized view completely as fast as possible, where I do not worry about undo data in one session.
This is what Oracle says about atomic_refresh: http://docs.oracle.com/cd/E11882_01/appdev.112/e40758/d_mview.htm#ARPLS67204


text:
Q: Text based JavaScript Ajax quiz I'm trying to create a text based quiz that moves on to the next slide when the correct answer is guessed. I have the code running(which is not showing questions in my pc but it is showing the questions perfectly here) but the input space is not displaying on my output screen. Can someone please help me identify the error?
Base code is from https://codepen.io/SitePoint/pen/GmPjjL

(function(){
    // Functions
    function buildQuiz(){
      // variable to store the HTML output
      const output = [];

      // for each question...
      myQuestions.forEach(
        (currentQuestion, questionNumber) => {

          // variable to store the list of answers
          const answers = [];

          for(questionNumber in currentQuestion.answers){

            answers.push(
              `
                <input type="text" name="question${questionNumber}" placeholder="Company" size="20">
              `

            );
          }

          // add this question to the output
          output.push(
            `

 ${currentQuestion.question}

`
          );
        }
      );

      // finally combine our output list into one string of HTML and put it on the page
      quizContainer.innerHTML = output.join('');
    }

    function showResults(){

      // gather answer containers from our quiz
      const answerContainers = quizContainer.querySelectorAll('.answers');

      // keep track of user's answers
      let numCorrect = 0;

      // for each question...
      myQuestions.forEach( (currentQuestion, questionNumber) => {

        // find selected answer
        const answerContainer = answerContainers[questionNumber];
        const userAnswer = (answerContainer.querySelector('input').value);

        //if answer is blank
    if (userAnswer.length === 0 ) {
        alert("You must enter an answer to continue...");
        return false;
    }

        // if answer is correct
        if(userAnswer.toLowerCase() === currentQuestion.correctAnswer.toLowerCase()){
          // add to the number of correct answers
          numCorrect++;

          // alert
         alert("CONGRATULATIONS! Your answer is correct! You have advanced to the next level.");
        }
        // if answer is wrong
        else{
          // alert
          alert("Wrong answer, please, keep trying...");
        }
      });

      // show number of correct answers out of total
      resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.length}`;
    }

    function showSlide(n) {
      slides[currentSlide].classList.remove('active-slide');
      slides[n].classList.add('active-slide');
      currentSlide = n;
      if(currentSlide === 0){
        previousButton.style.display = 'none';
      }
      else{
        previousButton.style.display = 'inline-block';
      }
      if(currentSlide === slides.length-1){
        nextButton.style.display = 'none';
        submitButton.style.display = 'inline-block';
      }
      else{
        nextButton.style.display = 'inline-block';
        submitButton.style.display = 'none';
      }
    }

    function showNextSlide() {
      showSlide(currentSlide + 1);
    }

    function showPreviousSlide() {
      showSlide(currentSlide - 1);
    }

    // Variables
    const quizContainer = document.getElementById('quiz');
    const resultsContainer = document.getElementById('results');
    const submitButton = document.getElementById('submit');

    const myQuestions = [
    {
      question: "Who invented JavaScript?",
      image: "https://i.postimg.cc/rmRj3SYt/nikecw.png",
      answers: "Write your answer here",
      correctAnswer: "Nike",
    },
    {
      question: "Which one of these is a JavaScript package manager?",
      image: "https://i.postimg.cc/rmRj3SYt/nikecw.png",
      correctAnswer: "Nike",

    },
    {
      question: "Which tool can you use to ensure code quality?",
      image: "https://i.postimg.cc/rmRj3SYt/nikecw.png",
      correctAnswer: "Nike",
    }
];
    // Kick things off
    buildQuiz();

    // Pagination
    const previousButton = document.getElementById("previous");
    const nextButton = document.getElementById("next");
    const slides = document.querySelectorAll(".slide");
    let currentSlide = 0;

    // Show the first slide
    showSlide(currentSlide);

    // Event listeners
    submitButton.addEventListener('click', showResults);
    previousButton.addEventListener("click", showPreviousSlide);
    nextButton.addEventListener("click", showNextSlide);
  })();

@import url(https://fonts.googleapis.com/css?family=Work+Sans:300,600);

body{
    font-size: 20px;
    font-family: 'Work Sans', sans-serif;
    color: #333;
  font-weight: 300;
  text-align: center;
  background-color: #f8f6f0;
}
h1{
  font-weight: 300;
  margin: 0px;
  padding: 10px;
  font-size: 20px;
  background-color: #444;
  color: #fff;
}
.question{
  font-size: 30px;
  margin-bottom: 10px;
}
.answers {
  margin-bottom: 20px;
  text-align: left;
  display: inline-block;
}
.answers label{
  display: block;
  margin-bottom: 10px;
}
button{
  font-family: 'Work Sans', sans-serif;
    font-size: 22px;
    background-color: #279;
    color: #fff;
    border: 0px;
    border-radius: 3px;
    padding: 20px;
    cursor: pointer;
    margin-bottom: 20px;
}
button:hover{
    background-color: #38a;
}

.slide{
  position: absolute;
  left: 0px;
  top: 0px;
  width: 100%;
  z-index: 1;
  opacity: 0;
  transition: opacity 0.5s;
}
.active-slide{
  opacity: 1;
  z-index: 2;
}
.quiz-container{
  position: relative;
  height: 200px;
  margin-top: 40px;
}
    <!DOCTYPE html>

<title>trial</title>
  <link rel="stylesheet" href="trialcs.css">

If I give you color wheel of 5 most dominant colors from 5 iconic logos, how many can you guess?

<button id="previous">Previous Question</button>
<button id="next">Next Question</button>
<button id="submit">Submit Quiz</button>

A: In your output.push I've added a input box, you need to pass your input box in this particular place. Input box I've added is just to show you the place you can add Input tag.

(function () {
    // Functions
    function buildQuiz() {
        // variable to store the HTML output
        const output = [];

        // for each question...
        myQuestions.forEach((currentQuestion, questionNumber) => {
            // variable to store the list of answers
            const answers = [];

            for (questionNumber in currentQuestion.answers) {
                answers.push(
                    `
                <input type="text" name="question${questionNumber}" placeholder="Company" size="20">
              `
                );
            }

            // add this question to the output
            output.push(
                `

 ${currentQuestion.question}

                <input type="text" name="question${questionNumber}" placeholder="Write answer here" size="20">

`
            );
        });

        // finally combine our output list into one string of HTML and put it on the page
        quizContainer.innerHTML = output.join("");
    }

    function showResults() {
        // gather answer containers from our quiz
        const answerContainers = quizContainer.querySelectorAll(".answers");

        // keep track of user's answers
        let numCorrect = 0;

        // for each question...
        myQuestions.forEach((currentQuestion, questionNumber) => {
            // find selected answer
            const answerContainer = answerContainers[questionNumber];
            const userAnswer = answerContainer.querySelector("input").value;

            //if answer is blank
            if (userAnswer.length === 0) {
                alert("You must enter an answer to continue...");
                return false;
            }

            // if answer is correct
            if (
                userAnswer.toLowerCase() === currentQuestion.correctAnswer.toLowerCase()
            ) {
                // add to the number of correct answers
                numCorrect++;

                // alert
                alert(
                    "CONGRATULATIONS! Your answer is correct! You have advanced to the next level."
                );
            }
            // if answer is wrong
            else {
                // alert
                alert("Wrong answer, please, keep trying...");
            }
        });

        // show number of correct answers out of total
        resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.length}`;
    }

    function showSlide(n) {
        slides[currentSlide].classList.remove("active-slide");
        slides[n].classList.add("active-slide");
        currentSlide = n;
        if (currentSlide === 0) {
            previousButton.style.display = "none";
        } else {
            previousButton.style.display = "inline-block";
        }
        if (currentSlide === slides.length - 1) {
            nextButton.style.display = "none";
            submitButton.style.display = "inline-block";
        } else {
            nextButton.style.display = "inline-block";
            submitButton.style.display = "none";
        }
    }

    function showNextSlide() {
        showSlide(currentSlide + 1);
    }

    function showPreviousSlide() {
        showSlide(currentSlide - 1);
    }

    // Variables
    const quizContainer = document.getElementById("quiz");
    const resultsContainer = document.getElementById("results");
    const submitButton = document.getElementById("submit");

    const myQuestions = [
        {
            question: "Who invented JavaScript?",
            image: "https://i.postimg.cc/rmRj3SYt/nikecw.png",
            answers: "Write your answer here",
            correctAnswer: "Nike"
        },
        {
            question: "Which one of these is a JavaScript package manager?",
            image: "https://i.postimg.cc/rmRj3SYt/nikecw.png",
            answers: "Write your answer here",
            correctAnswer: "Nike"
        },
        {
            question: "Which tool can you use to ensure code quality?",
            image: "https://i.postimg.cc/rmRj3SYt/nikecw.png",
            answers: "Write your answer here",
            correctAnswer: "Nike"
        }
    ];
    // Kick things off
    buildQuiz();

    // Pagination
    const previousButton = document.getElementById("previous");
    const nextButton = document.getElementById("next");
    const slides = document.querySelectorAll(".slide");
    let currentSlide = 0;

    // Show the first slide
    showSlide(currentSlide);

    // Event listeners
    submitButton.addEventListener("click", showResults);
    previousButton.addEventListener("click", showPreviousSlide);
    nextButton.addEventListener("click", showNextSlide);
})();
@import url(https://fonts.googleapis.com/css?family=Work+Sans:300,600);

body {
    font-size: 20px;
    font-family: "Work Sans", sans-serif;
    color: #333;
    font-weight: 300;
    text-align: center;
    background-color: #f8f6f0;
}
h1 {
    font-weight: 300;
    margin: 0px;
    padding: 10px;
    font-size: 20px;
    background-color: #444;
    color: #fff;
}
.question {
    font-size: 30px;
    margin-bottom: 10px;
}
.answers {
    margin-bottom: 20px;
    text-align: left;
    display: inline-block;
}
.answers label {
    display: block;
    margin-bottom: 10px;
}
button {
    font-family: "Work Sans", sans-serif;
    font-size: 22px;
    background-color: #279;
    color: #fff;
    border: 0px;
    border-radius: 3px;
    padding: 20px;
    cursor: pointer;
    margin-bottom: 20px;
}
button:hover {
    background-color: #38a;
}

.slide {
    position: absolute;
    left: 0px;
    top: 0px;
    width: 100%;
    z-index: 1;
    opacity: 0;
    transition: opacity 0.5s;
}
.active-slide {
    opacity: 1;
    z-index: 2;
}
.quiz-container {
    position: relative;
    height: 200px;
    margin-top: 40px;
}
If I give you color wheel of 5 most dominant colors from 5 iconic logos, how many can you guess?

<button id="previous">Previous Question</button>
<button id="next">Next Question</button>
<button id="submit">Submit Quiz</button>


text:
Q: Can jQuery listen to a click event on a youtube / vimeo movie? I have a jQuery slider filled with movies and I would like jQuery to stop the slider on a click event for either the embed / object. I have tried to no avail to get this to work. I have tried this:
$("embed").click(function() {
alert('Handler for .click() called.');
})

$("object").click(function() {
alert('Handler for .click() called.');
})

Neither works for the HTML tags embed or object. Any suggestions?

A: Enable the youtube player like so:
http://www.youtube.com/v/VIDEO_ID?enablejsapi=1&version=3
Then you can use these operations and listen to and react to events such as "onStateChange"

A: Have you tried adding a function name into the onclick attribute of the object tag?  If that does not work then I'm guessing the object itself is consuming the event and there is no way to get to the click.

A: Because both youtube and vimeo videos are rendered using flash, it's unlikely that you'll be able to listen for the click events registered by those elements because Flash has its own internal event model with its own handlers. I imagine it's possible to rebroadcast click events to javascript using ExternalInterface, but I've never seen it done.

A: Could it be that the jQuery bindings do not work because your embed/object elements are generated after you do that bindings? For example if you are using swfobject (flash gets embedded by javascript) this could be an issue.
What happens if you use live() instead?
jQuery("object,embed").live("click", function() {
    alert('Handler for .click() called.');
});

You could also try wrapping a div around these videos and bind the handler to the div.


text:
Q: WP action hook prefix in php class Hi I'm currently writing my first Wordpress Plugin in OOP way. I have question about naming class methods that will be used in add_action or add_filter. Does calling it array($this, 'my-action-method) will suffice to avoid naming collisions or I have to add some prefix?

A: Since you are using $this, it points to the instantiated object. The method name is just be the object (class) method name. There wouldn't be name collision issues (other than within the object/class itself for which PHP should throw an error).


text:
Q: How to convert binary string to string. json_encode binary string returns false I have read, that b in front of something means binary.
I am receiving a text field from MS DB, column type is CLOB.
I am using Laravel and when I die dump (dd()) I see:
b"""
My big text
"""

If I create simple string and dd() it I see:
"My big text"

The problem is that json_encode() returns false on this b-String, but everything fine with simple string.
Could you please tell me how can I make it a simple string?
P.S. I have tried unpack() -> unsuccess
EDIT: actually json_encode() not related to this binary string. It was failing cause of non utf8 symbol. I see  ...(22:45 – 0:15 CEST)..., but when I do utf8_decode($text), I see ...(22:45 ? 0:15 CEST)... and if I try to json_encode() now, it's works perfect.

A: PHP does not have "binary" and "non-binary" strings. It just has strings, and they're always "binary", as they're just acting like byte arrays. The b prefix is added by the Symfony VarDumper component as a sign that the string is not valid UTF-8. Arguably UTF-8 should be the one and only sensible encoding in use today, and apparently Symfony goes so far as to declare anything else as "binary", i.e. atypical text.
That is also the reason why your json_encode failed.
FWIW, b was a proposed forward compatibility prefix to prepare PHP code for PHP 6, which was supposed to have very Python-like binary strings and Unicode strings. Only PHP 6 never happened and the b prefix still does nothing. Symfony seems to have gone all out and adopted the b and """ conventions from Python nonetheless.


text:
Q: How to send app requests using gigya I am planning to use GIGYA for my application. How would I send requests (like a post on the wall or notification)for my application to the user. So that I can actively engage user.

A: you can't just post on one of your users wall with Gigya products
but you can make your site more social and give your users the ability to share things on your site with their friends with actions like posting on there wall
its very easy to do and implement just use the share plugin:
http://developers.gigya.com/010_Developer_Guide/18_Plugins/032_Share
or the share bar plugin:
http://developers.gigya.com/010_Developer_Guide/18_Plugins/015_Share_Bar


text:
Q: Let $f(x)$ be a continuous function defined for $1≤x≤3$. If $f(x)$ takes rational values for all $x$ and $f(2)=5$, what is the value of $f(1.5)$?
Let $f(x)$ be a continuous function defined for $1≤x≤3$. If $f(x)$ takes rational values for all $x$ and $f(2)=5$, what is the value of $f(1.5)$?

How do I approach questions like these?

A: The image of a continuous real function under a closed interval (like $1\leq x\leq3$) is also a closed interval.  (This is a combination of the intermediate value theorem and the extreme value theorem.) The only closed intervals that don't contain any irrational numbers are singleton sets where the only value is rational.  Therefore, since $5$ is in the range, the function must be $f(x)=5$ for all $1\le x \le 3$ and thus $f(1.5)=5$.


text:
Q: Is there a direct way to combine setters for multiple record fields to a single setter? import Control.Lens
import Control.Lens.TH

data Foo = Foo {
    _bar, _baz :: Int
   }
makeLenses ''Foo

Now if I want to modify both int fields, I can do
barbaz :: Setter' Foo Int
barbaz = sets $ \foo f -> foo & bar %~ f
                              & baz %~ f

but this seems like a pretty ugly manual way to do it.
Can the same be achieved directly with lens/arrow combinators?

A: lens doesn't a ready-made combinator for that, presumably beacuase you can get illegal setters (or lenses) if the focuses of the components overlap.
data Trio a = Trio a a a
    deriving (Show)

oneTwo :: Setter' (Trio a) (a, a)
oneTwo = sets $ \f (Trio x y z) -> let (x', y') = f (x, y) in Trio x' y' z

twoThree :: Setter' (Trio a) (a, a)
twoThree = sets $ \f (Trio x y z) -> let (y', z') = f (y, z) in Trio x y' z'

cheating :: Setter' (Trio a) (a, a)
cheating = sets $ \f x -> x & oneTwo %~ f & twoThree %~ f

GHCi> Trio 1 1 1 & cheating %~ bimap (2*) (2*) & cheating %~ bimap (3+) (3+)
Trio 5 10 5
GHCi> Trio 1 1 1 & cheating %~ (bimap (2*) (2*) <&> bimap (3+) (3+))
Trio 5 13 5

In your case, the nicest alternative to building the setter/traversal by hand (as you and Cristoph Hegemann are doing) seems to be liftA2 (>=>) :: ASetter' s a -> ASetter' s a -> ASetter' s a, as suggested elsewhere by bennofs (thanks Shersh for the link). If you happen to have a lens to a homogeneous pair (or some other Bitraversable) lying around, you can get the traversal out of it with both:
data Foo = Foo
   { _bar, _baz :: Int
   } deriving (Show)
makeLenses ''Foo

barBaz :: Iso' Foo (Int, Int)
barBaz = iso ((,) <$> view bar <*> view baz) (Foo <$> fst <*> snd)

GHCi> Foo 1 2 & barBaz . both %~ (2*)
Foo {_bar = 2, _baz = 4}

Yet another possibility is exploiting Data.Data.Lens to get a traversal of all fields of a certain type:
{-# LANGUAGE DeriveDataTypeable #-}

import Control.Lens
import Data.Data.Lens
import Data.Data

data Foo = Foo
   { _bar, _baz :: Int
   } deriving (Show, Data, Typeable)
makeLenses ''Foo

barBaz :: Traversal' Foo Int
barBaz = template

GHCi> Foo 1 2 & barBaz %~ (2*)
Foo {_bar = 2, _baz = 4}

A: I've had this problem before and have a solution that works for two lenses by combining them into a Traversal:
fields2 :: Lens' s a -> Lens' s a -> Traversal' s a
fields2 f1 f2 f s = (\v1 v2 -> s & f1 .~ v1 & f2 .~ v2) <$> f (s ^. f1) <*> f (s ^. f2)

barbaz = fields2 bar baz

This can than be used like:
foo & barbaz %~ f

It's a little dirty and doesn't scale but it works for me :D If someone posts a nicer answer I'll be very happy!


text:
Q: Singletons factory using generics and reflection OrderDBManager, UserDBManager, ProductDBManager extend DBManager.
I'm trying to create a singletons DBManager Factory
to get instances of different DBManager type classes.
But I have a problem using generics to return an instance of exact DBManager type class user wants. Right now it only works for DBManager itself.
I would appreciate your help!
public class DBManagerFactory {

     private static final Map<String, DBManager> instances = new HashMap<>();

     private static final String DB_MANAGER_PACKAGE_NAME = "ua.Test.db.";

     public static DBManager getInstance(Class<? extends DBManager> dbManagerClass) {
            String dbManagerClassName = dbManagerClass.getSimpleName();
            DBManager dbManager = instances.get(dbManagerClassName);

            if(dbManager == null){
                Class clazz = Class.forName(DB_MANAGER_PACKAGE_NAME + dbManagerClassName);
                dbManager = (DBManager)clazz.newInstance();
                instances.put(dbManagerClassName, dbManager);
            }
            return dbManager;
     }}

A:
But I have a problem using generics to return an instance of exact
  DBManager type class user wants.

To return a specific class in the method, you should specify a scoped method parameterized type that allows the client of the class to specify which type the method should return.
You could declare the method in this way :
public static <T extends DBManager> T getInstance(Class<T> dbManagerClass)  {

To avoid unsafe casts, you could cast the DBManager instance retrieved from the Map<String, DBManager> to a T extends DBManager type by using the Class#cast(Object ) method that performs for you the type check before casting the DBManager instance :
T dbManager = dbManagerClass.cast(instances.get(dbManagerClassName));

At last, the way to retrieve the class :
Class clazz = Class.forName(DB_MANAGER_PACKAGE_NAME + dbManagerClassName);

is not required as you have already the class as parameter of the method.
Just directly use it.
Here is sample code that implements this solution :
public class DBManagerFactory {

    private static final Map<String, DBManager> instances = new HashMap<>();

    public static <T extends DBManager> T getInstance(Class<T> dbManagerClass)  {

      final String dbManagerClassName = dbManagerClass.getSimpleName();

      T dbManager = dbManagerClass.cast(instances.get(dbManagerClassName));

      if (dbManager == null) {
        try {
          dbManager =  dbManagerClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
          e.printStackTrace(); // or better log it
          throw new RuntimeException("faillure during reflection instantiation for class " + dbManagerClass.getName(), e);
        }
        instances.put(dbManagerClassName, dbManager);
      }

      return dbManager;
    }

}

With these modifications, the client classes could invoke the method in this way :
DBManager instance = DBManagerFactory.getInstance(DBManager.class);
DBManagerChild child = DBManagerFactory.getInstance(DBManagerChild.class);

A: If you need to get explicit return type, then you could use generic factory method, as follows:
class Base {}

class A extends Base {}

class B extends Base {}

class InitializationFailedException extends RuntimeException {
    public InitializationFailedException(Throwable cause) {
        super(cause);
    }
}

class Factory {

    private static Logger log = LoggerFactory.getLogger(Factory.class);

    private static final ConcurrentHashMap<Class<? extends Base>, Base> instances = new ConcurrentHashMap<>();

    public static  <T extends Base> T getInstance(Class<T> tClass) {
        if (tClass == null) {
            throw new NullPointerException();
        }
        return (T) instances.computeIfAbsent(tClass, (tClass1) -> {
            try {
                return tClass1.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                log.error("Unable to create singleton value for " + tClass1.getCanonicalName(), e);
                throw new InitializationFailedException(e);
            }
        });
    }

}

With this approach you can get you sub type references created:
A aInstance = Factory.getInstance(A.class);
B bInstance = Factory.getInstance(B.class);

for your problem method signature can look like:
public static <T extends DBManager> T getInstance(Class<T> dbManagerClass);

instances Map should look like:
private static final Map<Class<? extends DBManager>, DBManager> instances = new HashMap<>();


text:
Q: Distance from point to cone "Consider the cone
$$ C := \{ (x,y,z) \in \mathbf{R}^{3} : x^{2}+y^{2} = z^{2}\}$$
and the point $ P:=(1,2,3) $. Find the least diatance between $P$ and any point $Q\in C$ and the coordinates of this point."
Here's what I did. Project everything (the cone and the point $P$) onto the $xy$-plane. $P$ lies on the $y = 2x$ line so if a $Q\in C$ is going to have minimal distance to $P$ it'll lie here as well (right?). I then intersected the cone with the plane $y = 2x$ and locally considered the cone as the line $y = x$, and then found the least distance btw. any point therein to the point $P$ which "locally" had coordinates $(\sqrt{5},3)$.
I found then the least distance to be $\frac{3-\sqrt{5}}{\sqrt{2}}$ and the coordinates of $Q=(x_Q,y_Q,z_Q)$ to be
$$ x_Q = \sqrt{\frac{7+3\sqrt{5}}{10}} $$
$$ y_Q = 2x_Q $$
$$ z_Q = \sqrt{5}x_Q $$
And I come here to ask if this is correct. It might be silly but that square root inside a square root kinda made me think I may have gotten something wrong. Possibly my very first assumption, viz. that $Q$ must lie along the $ y = 2x$ plane was unfounded... I'm going to proofcheck my resolution... The vector between $Q$ and $P$ should be a scalar multiple of the gradient vector of the function of which $C$ is a level surface at $Q$, correct?

A: The set of normals to the surface of a cone is given by $\nabla f$ where f  is the cone. $$f=z-\sqrt{x^2+y^2}$$
$$\nabla f = n = \left ( \frac {-x}{\sqrt{(x^2 + y^2)}}, \frac {-y}{\sqrt{(x^2 + y^2)}},1 \right )$$
Of course we don't know what x & y are, but we can continue anyway and write the line equation from P (1,2,3) to Q (x,y,z) and it would be
$$\left [ \begin{array}{c}x\\y\\z\end{array}\right ] = \left [ \begin{array}{c}1\\2\\3\end{array}\right ] + \lambda \cdot n$$
Now we can split the line equation into three equations, one for each row and then add the cone equation to get 4 equations in 4 unknowns.
The unknowns are x, y, z, and $\lambda$.  The equations are $$x = 1 + \lambda n_1$$  $$y=2+\lambda n_2$$  $$z=3+\lambda n_3$$  $$z=\sqrt{x^2+y^2}$$
Their simultaneous solution yields (positives only)  $x=(3\sqrt{5}+5)/10\qquad y=(3\sqrt{5}+5)/5$      $z=(\sqrt{5}+3)/2 \qquad  \lambda=(\sqrt{5}-3)/2$  These values for x, y, and z are the $Q_x, Q_y, and Q_z$  values and they do match what you found by projecting onto the xy axis.  Of course, the "short distance" is just $|P-Q|$.


text:
Q: Magento: "configForm is not defined" error when saving admin settings I get this error when I try to save an some settings on the admin. At least so far, I've noticed it happens in the system/advanced section and on a plugin (color picker) I want to deactivate.
Uncaught ReferenceError: configForm is not defined
onclick

Any idea?
Thanks

A: The problem in the /magento/js/prototype/validation.js corrupted.
Just replace it with the original version from backup files or from fresh magento and it will works.


text:
Q: Adding line of identity to correlation plots using pairs() command in R Similar to a prevous post, I'd like to modify the following code (from example in the R documentation for pairs() command):
## put (absolute) correlations on the upper panels,
## with size proportional to the correlations.
panel.cor <- function(x, y, digits = 2, prefix = "", cex.cor, ...)
{
    usr <- par("usr"); on.exit(par(usr))
    par(usr = c(0, 1, 0, 1))
    r <- abs(cor(x, y))
    txt <- format(c(r, 0.123456789), digits = digits)[1]
    txt <- paste0(prefix, txt)
    if(missing(cex.cor)) cex.cor <- 0.8/strwidth(txt)
    text(0.5, 0.5, txt, cex = cex.cor * r)
}
pairs(USJudgeRatings, lower.panel = panel.smooth, upper.panel = panel.cor)

Instead of a loess line, I want a line of identity for each plot. The secret lies in the $"panel.smooth" function, but I don't know how to modify it.

A: I think you just mean something like this:
my_line <- function(x,y,...){
    points(x,y,...)
    abline(a = 0,b = 1,...)
}
pairs(USJudgeRatings, lower.panel = my_line, upper.panel = panel.cor)

A: Or, if you want to plot a fitted, linear line, then you could modify joran's answer:
my_line <- function(x,y,...){
    points(x,y,...)
    abline(a = lm(y ~ x)$coefficients[1] , b = lm(y ~ x)$coefficients[2] , ...)
}

If you are indeed using pairs, however, it seems like loess would be more appropriate since you are likely exploring a dataset and would warrant the fitting of a linear line as extraneous at that point.


text:
Q: Eclipse galieo does not show classes directory inside build Due to this problem, a servlet does not execute on it.  What can be the reason?

A: Try Navigator view (Window -> Show View -> Navigator). Some F5 (refresh) hits may help too.

A: It can be that that a filter hides those files. Go to your package explorer window, then use the pull-down menu icon, most right one, then check 'Filters...'.


text:
Q: When will Python garbage collect when passing an encoded str to ctypes library? I have a function in a library that expects a char *, to which I want to send an encoded str. I would ideally like to call encode inline to the function call:
my_lib = cdll.LoadLibrary('my_lib.so')
my_string = 'hello'
my_lib.my_func(my_string.encode('utf-8'))

but I'm concerned that the bytes instance that's the return value of my_string.encode('utf-8') will get deleted (by garbage collecting or reference counting) by Python before the library function uses it. Is this possible, and so should I actually do the below?
my_lib = cdll.LoadLibrary('my_lib.so')
my_string = 'hello'
my_string_encoded = my_string.encode('utf-8')
my_lib.my_func(my_string_encoded)

A: Both of your code snippets are safe, because at the beginning of each fuction call, reference counters of arguments are incremented, and at return time they are decremented. Thus the temporary bytes object remains alive during the call, and its data pointer remains valid.


text:
Q: Windows Azure and WCF Data Services V3 My question is:
why does WCF Data Services 5.2.0 work under Azure Emulator and not under Azure Staging/Production environment?
I get this error on server:

Could not load file or assembly Microsoft.Data.Services, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

instead on emulator it works perfectly..
My project reference assemblies are:

*

*Microsoft.Data.Services 5.2.0.0

*Microsoft.Data.Services.Client 5.2.0.0

*Microsoft.Data.OData 5.2.0.0

*Microsoft.Data.Edm 5.2.0.0

*System.Spatial 5.2.0.0

*Microsoft.WindowsAzure.Storage 2.0.0.0

V3 is very useful to show data in JSON without other libraries.

A: The problem can be related to the fact that in the .svc file there is an hardcoded reference to the GACed version: 5.0.0.0
<%@ ServiceHost Language="C#" Factory="System.Data.Services.DataServiceHostFactory, Microsoft.Data.Services, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Service="Forward.TestService " %>

If your dlls have Copy Local attribute set to true, you should be able to remove version and solve the problem
<%@ ServiceHost Language="C#" Factory="System.Data.Services.DataServiceHostFactory, Microsoft.Data.Services, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Service="Forward.TestService " %>


text:
Q: Reorganize the widgets - Flutter So I am trying to add a description under the (task.title) but with the current code I wrote I am not sure how I can refactor it or even improve it to be able to do that. I would also like to have some sort of widget that can do some space between each task tile so that it's not too crowded. Any Help is appreciated. Thank you.

task_tile.dart

class TaskTile extends StatelessWidget {
  const TaskTile({
    Key? key,
    required this.task,
  }) : super(key: key);

  final Task task;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Expanded(
          child: Row(
            children: [
              Expanded(
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const SizedBox(width: 10),
                    Text(
                      task.title,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        color: const Color(0xFF89ABE3),
                        fontFamily: 'Source Sans Pro',
                        fontSize: 19,
                        decoration:
                            task.isDone! ? TextDecoration.lineThrough : null,
                      ),
                    ),
                    const SizedBox(width: 10),
                  ],
                ),
              ),
            ],
          ),
        ),
        Row(
          children: [
            PopupMenu(
              favouriteCallback: () => context.read<TasksBloc>().add(
                    MakeFavouriteTask(task: task),
                  ),
              task: task,
            ),
            Transform.scale(
              scale: 1.2,
              child: Checkbox(
                shape: const CircleBorder(
                  side: BorderSide(
                    width: 20,
                  ),
                ),
                side: const BorderSide(
                  color: Color(0xFF89ABE3),
                ),
                activeColor: Colors.greenAccent,
                value: task.isDone,
                onChanged: task.isDeleted == false
                    ? (value) {
                        context.read<TasksBloc>().add(UpdateTask(task: task));
                      }
                    : null,
              ),
            ),
          ],
        ),
      ],
    );
  }
}

task_list.dart

class TasksList extends StatelessWidget {
  const TasksList({
    Key? key,
    required this.tasksList,
  }) : super(key: key);

  final List tasksList;

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      padding: const EdgeInsets.only(top: 10),
      itemCount: tasksList.length,
      itemBuilder: (context, index) {
        var task = tasksList[index];
        return TaskTile(task: task);
      },
    );
  }
}

A: I understand now, I've edited your previous code to incorporate the changes that you needed, try this :
class TaskTile extends StatelessWidget {
  const TaskTile({
    Key? key,
    required this.task,
  }) : super(key: key);

  final Task task;

  @override
  Widget build(BuildContext context) {
    return Column(// wrap the whole widget in a Column
      children: [
        const SizedBox(width: 4), //add a sizedbox for spacing
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: Row(
                children: [
                  Expanded(
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const SizedBox(width: 10),
                        Column( //one column is needed here
                          children: [
                            Text(
                              task.title,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                color: const Color(0xFF89ABE3),
                                fontFamily: 'Source Sans Pro',
                                fontSize: 19,
                                decoration: task.isDone!
                                    ? TextDecoration.lineThrough
                                    : null,
                              ),
                            ), // you can also add a SizedBox here to keep spacing if they're too close
                            Text( // and this is your desciption part
                              task.description,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                color: const Color(0xFF89ABE3),
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(width: 10),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Row(
              children: [
                PopupMenu(
                  favouriteCallback: () => context.read<TasksBloc>().add(
                        MakeFavouriteTask(task: task),
                      ),
                  task: task,
                ),
                Transform.scale(
                  scale: 1.2,
                  child: Checkbox(
                    shape: const CircleBorder(
                      side: BorderSide(
                        width: 20,
                      ),
                    ),
                    side: const BorderSide(
                      color: Color(0xFF89ABE3),
                    ),
                    activeColor: Colors.greenAccent,
                    value: task.isDone,
                    onChanged: task.isDeleted == false
                        ? (value) {
                            context.read<TasksBloc>().add(UpdateTask(task: task));
                          }
                        : null,
                  ),
                ),
              ],
            ),
          ],
        ),
        const SizedBox(width: 4),//add a sizedbox for spacing
        Divider(thickness: 2,),// the divider you want to keep the tiles apart
      ],
    );
  }
}

Hope this answers all your questions...


text:
Q: Common Emitter resistors interactions Background: I did an "A" level in electronics 25 years ago; now been a professional programmer for nearly 20 years. I want to build some very basic circuits to interact with an Arduino but I've forgotten a lot, apparently :)
Question: I am playing around with the below circuit, and it is confusing me. The values below are taken from a website, and they work fine and as expected. However, they clip the bottom half of the waveform.
Reading that the gain is only set by RL and RE, naively, I though that biasing the transistor to half the supply would move the waveform up so that it would be amplified the same in both directions, so I altered R1 to 11k.
However, this seems to completely stop the circuit amplifying at all; in fact the gain is now ~-0.5. Now, I'm willing to accept that my change didn't do what I wanted, but if the load is only set by RL and RE, why did this have such a dramatic effect?
NOTE: I have read all the many Common Emitter questions on the site and I'm afraid the answers are a bit over my head, so if you could aim your responses at my beginner 17yo self, that'd be good :)
NOTE TWO: RE should be 470R, not 5R. Screenshot is wrong.
(Also I cannot get it to run in Circuit Lab for some reason, so here it is in PartSim - http://www.partsim.com/simulator#76064)

A: It's not so much that they affect the gain, but the fact that this change to R1 takes the transistor outside its linear operating region.
With a pair of 11K resistors for R1 and R2 you're trying to bias the base at 2.5V.
With a typical VBE of about 0.6V that means you're looking for 1.9V across RE, which in turn means an emitter current of about 4mA.
However, to get that 4mA flowing through RL to get to RE you would need to have a voltage drop of 18V across RL which you can't get anywhere near with a 5V supply.
The result is that the transistor becomes fully saturated trying to achieve that emitter current and in that state an increase in base current has very little effect on the collector current and hence very little effect on the voltage at the collector. The result is that the circuit no longer gives you the gain you want.

A: As user Finbarr said, it's all about defining the working region, not the amplification ratio. With wrong R1, R2 setting you go in saturation or non-conducting region.
Source : http://www.electronics-tutorials.ws/transistor/tran_2.html

Calculated example:


text:
Q: Find the closest key in a dictonary with string? I am trying to find a way to find the closest key to a string within a dictonary. Example:
data = {'1a': 'This is 1a', '1d': 'This is 1d', '1f': 'This is 1f', '1e': 'This is 1e'}
find_nearest(data, '1b')
#This would return key '1a'

I have found other examples, but most deal with numbers. Example:
data[num] if num in data else data[min(data.keys(), key=lambda k: abs(k-num))]

I was able to find one code that looked promising:
from sortedcontainers import SortedDict
sd = SortedDict((key, value) for key, value in data)

# Bisect for the index of the desired key.
index = sd.bisect(200)

# With that index, lookup the key.
key = sd.iloc[index]

# You can also look ahead or behind to find the nearest key.
behind = sd.iloc[index - 1]
ahead = sd.iloc[index + 1]

So I tried this, here is my code:
from sortedcontainers import SortedDict
data = {'1a': 'This is 1a', '1d': 'This is 1d', '1f': 'This is 1f', '1e': 'This is 1e'}
sd = SortedDict((key,value) for key,value in data.items())

index = sd.bisect('1b')

key = sd.iloc[index]
print(key)

But when I run this code it returns:
1d #Instead of '1a'

I have tried every which way to get the code to work, but i can't seem to get it right. Does anyone know of a fast and efficient way of achieving this?

A: When you bisect, the algorithm has 2 choices if it doesn't find an exact index match.  It can return the index of the object on the left, or the index of the object on the right.  It looks like bisect is an alias of bisect_right.  You could use bisect_left instead...
Of course, this isn't necessarily closer (you haven't really defined what you mean by closer).  Indeed, even something like difflib.SequenceMatcher.ratio() probably won't help with the example as it only looks to see what the ratio of matching to non-matching elements are.
You could try something like:
def find_closest(sd, expected):
    index = sd.bisect(expected)
    closest_lower = sd.iloc[index]
    try:
        closest_upper = sd.iloc[index]
    except IndexError:
        return closest_lower

    # assumption -- Your keys are hex values.
    # this assumption could be completely wrong, but demonstrates
    # how to think of defining a measure of "closeness"
    var expected_as_int = int(expected, 16)
    def distance(val):
        return int(val, 16) - expected_as_int

    return min([closest_lower, closest_upper], key=distance)

A: The way I would implement this is by iterating through the keys in order, and finding the key with the smallest "difference".  Because the keys are sorted, you know you've found it as soon as the difference stops decreasing.
def closestKey(data, val):
    lastKey = None
    lastDif = None
    for key in sorted(data.keys()):
        dif = difference(key, val) #need to figure out difference()
        if lastDif is not None and dif > lastDif:
            return lastKey
        lastDif = dif
        lastKey = key

This doesn't handle the case in which two keys are equidistant, if that's important.

A: Thanks to @mgilson, that gave me the idea that helped me, I was able to do what I wanted to achieve. Here is my code for anyone interested:
from sortedcontainers import SortedDict
data = {'1a': 'This is 1a', '1d': 'This is 1d', '1g': 'This is 1g', '1h': 'This is 1h'}
def find_closest(sd, expected):
    index = sd.bisect(expected)
    try:
        indexAhead = sd.iloc[index]
    except IndexError:
        indexAhead = sd.iloc[len(sd.keys()) - 1]
    if indexAhead == expected:
        return expected
    else:

        try:
            indexBehindNum = 0
            indexBehind = sd.iloc[index -1]
            for char in indexBehind:
                indexBehindNum += ord(char)
        except IndexError:
            pass
        if not indexBehindNum:
            return indexAhead
        else:
            expectedTotalNum = 0
            indexAheadNum = 0
            for char in expected:
                expectedTotalNum += ord(char)
            for char in indexAhead:
                indexAheadNum += ord(char)
            diffrenceAhead = indexAheadNum - expectedTotalNum
            diffrenceBehind = indexBehindNum - expectedTotalNum
            Closest = min([diffrenceAhead, diffrenceBehind], key=abs)
            if Closest == diffrenceAhead:
                return indexAhead
            else:
                return indexBehind

sd = SortedDict((key,value) for key,value in data.items())

print(find_closest(sd, '1b'))#This will return '1a'!

I am not sure if this is the fastest and most efficient, but I will try to continue to try to find other ways.


text:
Q: Difference between a list & a stack in python? What is the difference between a list & a stack in python?
I have read its explanation in the python documentation but there both the things seems to be same?
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

A: A stack is a data structure concept. The documentation uses a Python list object to implement one. That's why that section of the tutorial is named Using Lists as Stacks.
Stacks are just things you add stuff to, and when you take stuff away from a stack again, you do so in reverse order, first in, last out style. Like a stack of books or hats or... beer crates:

See the Wikipedia explanation.
Lists on the other hand are far more versatile, you can add and remove elements anywhere in the list. You wouldn't try that with a stack of beer crates with someone on top!
You could implement a stack with a custom class:
from collections import namedtuple

class _Entry(namedtuple('_Entry', 'value next')):
    def _repr_assist(self, postfix):
        r = repr(self.value) + postfix
        if self.next is not None:
            return self.next._repr_assist(', ' + r)
        return r

class Stack(object):
    def __init__(self):
        self.top = None
    def push(self, value):
        self.top = _Entry(value, self.top)
    def pop(self):
        if self.top is None:
            raise ValueError("Can't pop from an empty stack")
        res, self.top = self.top.value, self.top.next
        return res
    def __repr__(self):
        if self.top is None: return '[]'
        return '[' + self.top._repr_assist(']')

Hardly a list in sight (somewhat artificially), but it is definitely a stack:
>>> stack = Stack()
>>> stack.push(3)
>>> stack.push(4)
>>> stack.push(5)
>>> stack
[3, 4, 5]
>>> stack.pop()
5
>>> stack.push(6)
>>> stack
[3, 4, 6]
>>> stack.pop()
6
>>> stack.pop()
4
>>> stack.pop()
3
>>> stack
[]

The Python standard library doesn't come with a specific stack datatype; a list object does just fine. Just limit any use to list.append() and list.pop() (the latter with no arguments) to treat a list as a stack.
You could also use the collections.deque() type; it is usually slightly faster than a list for the typical patterns seen when using either as a stack. However, like lists, a deque can be used for other purposes too.

A: A "stack" is a specific application of list, with operations limited to appending (pushing) to and popping (pulling) from the end.

A: In python lists can also be used as stacks. Think of a list like a combination between your normal lists and a stack.
This is also described here

The list methods make it very easy to use a list as a stack, where the
  last element added is the first element retrieved ("last-in,
  first-out"). To add an item to the top of the stack, use append(). To
  retrieve an item from the top of the stack, use pop() without an
  explicit index

In fact you are using their exact example. Are you confused by the fact that it's a "combined data structure" ?
EDIT: as another user mentioned, it is a concept that is implemented using lists.

A: Stack works in the concept of Last in First out.
We can perform push and pop operations in the stack
But compare to stack list is easy to do all operations like add,insert,delete,concat etc...
Stack is the application of stack and it's like data structures we use it more.


text:
Q: Why iis host application do not let log in? I have hosted my applciation to the IIS -7 and it browses proper but it doest let me log in now, desipte i have checked it has a correct connection string, it throws error at my log page
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 96:         SqlParameter[] arrParams = new SqlParameter[0];
Line 97:         _userDetails = Data.GetSQLQueryResults(sqlQuery, 0, arrParams);
Line 98:         if (_userDetails.Rows.Count != 0)
Line 99:         {
Line 100:            _userAccountID = _userDetails.Rows[0]["UserAccountID"].ToString();

Source File: d:\Projects\June 20\CorrDefensev2\App_Code\UserInfo.cs    Line: 98

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
   UserInfo.setUserData(MembershipUser membershipUser) in d:\Projects\June 20\CorrDefensev2\App_Code\UserInfo.cs:98
   UserInfo..ctor(String username) in d:\Projects\June 20\CorrDefensev2\App_Code\UserInfo.cs:76
   Account_Login.Login1_LoggingIn(Object sender, LoginCancelEventArgs e) in d:\Projects\June 20\CorrDefensev2\MyPublic\Login.aspx.cs:76
   System.Web.UI.WebControls.Login.OnLoggingIn(LoginCancelEventArgs e) +115
   System.Web.UI.WebControls.Login.AttemptLogin() +85
   System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e) +101
   System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
   System.Web.UI.WebControls.ImageButton.OnCommand(CommandEventArgs e) +125
   System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +177
   System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563

the solution: all i had to use sql server authentication that is a connection string in web.config with the username, password, and it works fantastic...

A:  SqlParameter[] arrParams = new SqlParameter[0];
 _userDetails = Data.GetSQLQueryResults(sqlQuery, 0, arrParams);

You are passing arrParams with zero elements in it, Your query might expect some parameter to return the result. There is a chance that you have null for _userDetails as you are getting now. You can prevent the exception by putting check for null on _userDetails
if (_userDetails != null && _userDetails.Rows.Count != 0)
{

}

To find out exact cause
if (_userDetails != null)
{
   //No data table returned
   if( _userDetails.Rows.Count != 0)
   {
        //No record found
   }
}


text:
Q: Number of monic polynomials of degree $2$ I know that there are $p^2$ monic polynomials of degree $2$ over the field $\mathbb{Z}_{p}
 $ but I want to prove it precisely. Help me a hint to prove that. Thanks a lot.

A: A degree 2 polynomial has the form $ax^2 + bx +c$.  It is monic when $a=1$.  How many choices of $b$ are there?  How many choices of $c$ are there?


text:
Q: signature_pad canvas does not render inside asp.net form Using szimek's signature-pad libraries, I'm trying to embed the canvas into an asp.net form.  When I test, the canvas does not render and viewing the elements shows that the canvas consistently has a height of zero.  If I remove the form tags, it's fine.  Anyone have a suggestion?

    <form id="form1" runat="server">

                <canvas></canvas>

Sign above

                        <button type="button" class="button clear" data-action="clear">Clear</button>
                        <button type="button" class="button" data-action="change-color">Change color</button>
                        <button type="button" class="button" data-action="undo">Undo</button>
                        <asp:button text="Save" runat="server" cssclass="button save" data-action="save" onclick="Save" />

                        <button type="button" class="button save" data-action="save-png">Save as PNG</button>
                        <button type="button" class="button save" data-action="save-jpg">Save as JPG</button>
                        <button type="button" class="button save" data-action="save-svg">Save as SVG</button>

        <input type="hidden" id="hfSign" runat="server" />
    </form>

A: I have used Signature Pad before, Click here to check demo
Step 1 : You need to apply height and width to <canvas>
<canvas id="mySketch" width="500" height="200">
</canvas>

Step 2 : You have already a hidden field
<input type="hidden" id="hfSign" runat="server" />

Step 3 : Fill canvas resutl to hfSign and convert its value to image using Convert.FromBase64String()

A: Used an older version of the signature-pad.css and placement is now correct in all browsers.


text:
Q: n|solid console: [WARNING] NSolid Agent shutting down, listening on port has encountered an error: EADDR │INUSE (address already in use) I successfully had n|solid + console + profiling running locally a day ago but when I restarted today, although I can get etcd and the nsolid-proxy up no problem, when I npm start in nsolid-console I am getting:
[WARNING] NSolid Agent shutting down, listening on port has encountered an error: EADDRINUSE (address already in use)
  on ../nsolid-ext/deps/agent/src/threads.cc:786

> nsolid-console@1.4.4 start /home/ns/nsolid-console
> NODE_ENV=production node bin/nsolid-console --interval=1000

[WARNING] NSolid Agent shutting down, listening on port has encountered an error: EADDRINUSE (address already in use)
  on ../nsolid-ext/deps/agent/src/threads.cc:786
Server running on http://0.0.0.0:3000

...and when I do start my app with nsolid index.js and load the console at http://127.0.0.1:3000 and select my app, there are three processes running, instead of one, and they are: npm, nsolid-proxy and nsolid - as if the console is profiling nsolid itself and not my app.
Also, when I run nsolid-cli ls I have multiple entries...seems like I should only have one?
> nsolid-cli ls
{"pid":13143,"hostname":"rainworld","app":"example","address":"10.99.46.63:39682","id":"ec04fa6e98e08961bdba4f757d1cd2297563e4a6"}
{"pid":13908,"hostname":"rainworld","app":"example","address":"10.99.46.63:46188","id":"1fc5132d6b4f779a073b0ca8952862e165eb546a"}
{"pid":13095,"hostname":"rainworld","app":"example","address":"10.99.46.63:1111","id":"c2bddf9a505a490bab333e8b93627171586dbf6a"}
{"pid":13130,"hostname":"rainworld","app":"example","address":"10.99.46.63:42300","id":"b6b2a5a5c0da40ececc9ef0a0eed5fd4cd0927eb"}

I have all of the various env variables in my fish shell config file, e.g.
set -x NSOLID_APPNAME example
set -x NSOLID_HUB localhost:4001
set -x NSOLID_SOCKET 0
set -x NODE_ENV production

A: The NSOLID_* environment variables should be set per application to be monitored, since you have this variables globally you are telling to the N|Solid runtime to monitor both the nsolid-proxy and nsolid-console under the same application name (defined in NSOLID_APPNAME).
Keep this variables locally per application and it should work.


text:
Q: Generating PDF with get/set variables The variables value1 to value4 are needed to display in the PDF through the iText PDF generator. When I use the value, it shows "Cannot make a static reference to the non-static field value1". How could I fix that?
Here is the code:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class GenerateSummonPDF
{
private String value1;
private String value2;
private String value3;
private String value4;   //this variables with constant updated string data

public  String getValue1()
{
    return this.value1;

}

public void userdata(String p1, String p2, String p3, String p4)
{

    this.value1 = p1;
    this.value2 = p2;
    this.value3 = p3;
    this.value4 = p4;

}
  public static void main(String[] args)
  {

  Document document = new Document();
  try
  {
     PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\User\\workspace\\enforement system\\Summon PDF list\\Serial No.pdf"));
     document.open();
     document.add(new Paragraph(getValue1()); //i need to print all the data here from the userdata
     document.close();
     writer.close();
  } catch (DocumentException e)
  {
     e.printStackTrace();
  } catch (FileNotFoundException e)
  {
     e.printStackTrace();
  }
   }
}

A: You need an instance of GenerateSummonPDFto call non-static methods:
public static void main(String[] args)
{
    GenerateSummonPDF generateSummonPDF = new GenerateSummonPDF(); //create an instance
    generateSummonPDF.userdata("TestString1", "TestString2", "TestString3", "TestString4"); //some content

    Document document = new Document();
    try
    {
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\User\\workspace\\enforement system\\Summon PDF list\\Serial No.pdf"));
        document.open();
        document.add(new Paragraph(generateSummonPDF.getValue1()); //get value1
        document.close();
        writer.close();
    } catch (DocumentException e)
    {
        e.printStackTrace();
    } catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
}

A: You are calling the values from the static methods, so that you are getting this error, Just create a function and place your code there like this..
public static void main(String[] args)
  {
      createPdf();
  }
createPdf(){
  Document document = new Document();
  try
  {
     PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\User\\workspace\\enforement system\\Summon PDF list\\Serial No.pdf"));
     document.open();
     document.add(new Paragraph(getValue1()); //i need to print all the data here from the userdata
     document.close();
     writer.close();
  } catch (DocumentException e)
  {
     e.printStackTrace();
  } catch (FileNotFoundException e)
  {
     e.printStackTrace();
  }
}


text:
Q: How to let user type a number and then use the function to return that number is odd or even
def function(number):
    if number % 2 == 0:
        number = "even"
        return number
    else:
        number = "odd"
        return number

function(input("5"))

A: You would have to take the user-input, and then run the function with the number the user did type. example:
userinput = input("Type a number: ")
then...
print(function(userinput))


text:
Q: Can anyone modify this script, as I want to store the result in excel in the columns but it's split the result $servers= Get-Content "Location "
$PatchingTracker="D:\tracker.csv"
foreach($server in $servers)
{
    if(Test-Connection -ComputerName $server)
    {
        $update= Get-HotFix -ComputerName $server -Description *  | out-file $PatchingTracker -Append
        $uptime= Get-WmiObject win32_operatingsystem -ComputerName $server |     select csname, @{LABEL='LastBootUpTime' ;EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}} | out-file $PatchingTracker -Append
    }
}

A: here's one way to do what i think you want. [grin]
what it does ...

*

*sets the constants

*creates a list of systems
when ready to do this with real data, replace the entire #region/#endregion block with a call to grab your computer name list.

*loops thru the list of computer names

*tests to see if the system responds

*IF yes = grabs the wanted info from the target system

*IF no = sets the values to the $NoResponse string

*builds a PSCO that has the desired properties
you will likely want to change this to better fit your situation.

*sends that PSCO out to the $Results collection

*displays the result on screen

*saves the result to a CSV for later use [likely to import into excel]

please note that using Invoke-Command instead of a foreach loop would be faster since it would run part of the code on the target systems. i was too lazy to write that up, tho. [grin]
the code ...
$PatchReportFile = 'PatchReport_-_{0}.csv' -f (get-date -Format 'yyyy-MM-dd')
$PRDir = $env:TEMP
$FullPRFile = Join-Path -Path $PRDir -ChildPath $PatchReportFile

$NoResponse = '__n/a__'

#region >>> create server name list
# when ready to do this for real ...
#    - remove or comment out the entire "#region/#endregion" block
#    - add a "Get-Content" or other command to grab your computer list
$ServerList = @"
BetterNotBeThere
LocalHost
10.0.0.1
127.0.0.1
$env:COMPUTERNAME
"@ -split [System.Environment]::NewLine
#endregion >>> create server name list

$Results = foreach ($SL_Item in $ServerList)
    {
    if (Test-Connection -ComputerName $SL_Item -Count 2 -Quiet)
        {
        $CIM_OS = Get-CimInstance -ComputerName $SL_Item -ClassName CIM_OperatingSystem
        $LastBootUpTime = $CIM_OS.LastBootUpTime
        $UpTime_Days = [math]::Round(([datetime]::Now - $LastBootUpTime).TotalDays, 2)

        $HotFixId_List = (Get-HotFix -ComputerName $SL_Item).HotFixId -join ', '
        }
        else
        {
        $LastBootUpTime = $NoResponse
        $UpTime_Days = $NoResponse
        $HotFixId_List = $NoResponse
        }

    [PSCustomObject]@{
        ComputerName = $SL_Item
        LastBootUpTime = $LastBootUpTime
        UpTime_Days = $UpTime_Days
        HotFixId_List = $HotFixId_List
        }
    }

# display on screen
$Results

# send to CSV
#    the delimiter is set to ';' so that excel will [hopefully] import it smoothly
$Results |
    Export-Csv -LiteralPath $FullPRFile -NoTypeInformation -Delimiter ';'

the output on screen ...
ComputerName     LastBootUpTime         UpTime_Days HotFixId_List
------------     --------------         ----------- -------------
BetterNotBeThere __n/a__                __n/a__     __n/a__
LocalHost        2021-05-12 10:15:45 PM 1.38        KB4601554, KB4561600, KB4570334, KB4577266, KB4577586, KB4580325, KB4586864, KB4589212, KB4593175, KB4598481, KB500...
10.0.0.1         __n/a__                __n/a__     __n/a__
127.0.0.1        2021-05-12 10:15:45 PM 1.38        KB4601554, KB4561600, KB4570334, KB4577266, KB4577586, KB4580325, KB4586864, KB4589212, KB4593175, KB4598481, KB500...
[MySysName]      2021-05-12 10:15:45 PM 1.38        KB4601554, KB4561600, KB4570334, KB4577266, KB4577586, KB4580325, KB4586864, KB4589212, KB4593175, KB4598481, KB500...

CSV file content ...
"ComputerName";"LastBootUpTime";"UpTime_Days";"HotFixId_List"
"BetterNotBeThere";"__n/a__";"__n/a__";"__n/a__"
"LocalHost";"2021-05-12 10:15:45 PM";"1.38";"KB4601554, KB4561600, KB4570334, KB4577266, KB4577586, KB4580325, KB4586864, KB4589212, KB4593175, KB4598481, KB5003173, KB5003242"
"10.0.0.1";"__n/a__";"__n/a__";"__n/a__"
"127.0.0.1";"2021-05-12 10:15:45 PM";"1.38";"KB4601554, KB4561600, KB4570334, KB4577266, KB4577586, KB4580325, KB4586864, KB4589212, KB4593175, KB4598481, KB5003173, KB5003242"
"[MySysName]";"2021-05-12 10:15:45 PM";"1.38";"KB4601554, KB4561600, KB4570334, KB4577266, KB4577586, KB4580325, KB4586864, KB4589212, KB4593175, KB4598481, KB5003173, KB5003242"

A: You can refer to the below script, as it worked as expected but I am only getting a single KB number in excel, else it provides all the details.
$servers= Get-Content "#file path of the server list"

foreach($server in $servers)
{
$windowsupdate= Get-WmiObject -ComputerName $servers -ClassName Win32_QuickFixEngineering -Property * | select HotFixID, InstalledBy, InstalledOn
$uptime= Get-WmiObject win32_operatingsystem -ComputerName $servers | select csname, @{LABEL='LastBootUpTime' ;EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}}

   foreach($update in $windowsupdate)
   {
$CustomObject = New-Object -TypeName psobject
$CustomObject | Add-Member  -MemberType NoteProperty -Name 'Server Name' -Value $servers
$CustomObject | Add-Member  -MemberType NoteProperty -Name 'HotFix ID' -Value $update.HotFixID
$CustomObject | Add-Member  -MemberType NoteProperty -Name 'Installed By' -Value $update.InstalledBy
$CustomObject | Add-Member  -MemberType NoteProperty -Name 'Installed On' -Value $update.InstalledOn
$CustomObject | Add-Member  -MemberType NoteProperty -Name ' Reboot Time' -Value  $uptime.LastBootUpTime -PassThru
$CustomObject | Format-Table
$infoColl=$CustomObject
  }
}
$infoColl | Export-Csv D:\Patch_Tracker_$((Get-Date).ToString('MM-dd-yyyy')).csv -NoTypeInformation #Export the results in csv file.

A: I tried with the same script once again and What I get is below.
Get-CimInstance : The client cannot connect to the destination specified in
the request. Verify that the service on the destination is running and is
accepting requests. Consult the logs and documentation for the WS-Management
service running on the destination, most commonly IIS or WinRM. If the
destination is the WinRM service, run the following command on the destination
to analyze and configure the WinRM service: "winrm quickconfig".
At C:\Users\shivam\OneDrive - Essex Lake Group\Script\PatchTracker1.2V.ps1:20
char:19
+ ...   $CIM_OS = Get-CimInstance -ComputerName $SL_Item -ClassName CIM_Ope ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ConnectionError: (root\cimv2:CIM_OperatingSystem
   :String) [Get-CimInstance], CimException
    + FullyQualifiedErrorId : HRESULT 0x80338012,Microsoft.Management.Infrastr
   ucture.CimCmdlets.GetCimInstanceCommand
    + PSComputerName        : localhost

Cannot find an overload for "op_Subtraction" and the argument count: "2".
At C:\Users\shivam\OneDrive - Essex Lake Group\Script\PatchTracker1.2V.ps1:22
char:9
+         $UpTime_Days = [math]::Round(([datetime]::Now - $LastBootUpTi ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

ComputerName LastBootUpTime UpTime_Days
------------ -------------- -----------
localhost                   @{csname=ELGILE0635; LastBootUpTime=5/25/2021 5:...

And the excel file doesn't count anything. Even I tried to check manually Cim_Instance command and it works.


text:
Q: Proof of characterization of measurable sets I am not sure if the following characterization works.
Suppose the $\mathcal{M}$ is a $\sigma$-algebra in $X$. Let $f$ be a map from $X$ to $[-\infty,\infty]$, that is,
$$f:(X,\mathcal{M}) \rightarrow [-\infty,\infty]$$
Then, $f$ is measurable if  $\forall \alpha \in \mathbb{R}$,we have $f^{-1}((\alpha,\infty)) \in \mathcal{M}$.
Proof:
Assume that $f$ is measurable and let $\alpha$ to be arbitrary. Note that since   $f$ is measurable, we have $f^{-1}((\alpha,\infty)) \in \mathcal{M}$. Since $\alpha$ was arbitrary, then $\forall \alpha \in \mathbb{R}$,we have $f^{-1}((\alpha,\infty)) \in \mathcal{M}$.  Now, assume that $\forall \alpha \in \mathbb{R}$, we have $f^{-1}((\alpha,\infty)) \in \mathcal{M}$. In particular, we have that for every $\alpha$, the subset $(\alpha,\infty) \subset [-\infty,\infty]$ is a borel set, so that the collection $f^{-1}((\alpha,\infty)) \in \mathcal{M}$ and thus $f$ is measurable.In particular the set:
$$\Omega = \bigcup_{\alpha \in \mathbb{R}} \Omega_{\alpha}, \text{ where } \Omega_{\alpha} = \{(\alpha,\infty) \subset [-\infty,\infty]| f^{-1}((\alpha,\infty)) \in \mathcal{M}\},$$
is a $\sigma-$algebra.
Is this proof correct?

A: In fact the given condition does not imply that $f$ is measurable. We're given that $f:X\to[-\infty,\infty]$, so $f$ is measurable if the inverse image of every Borel subset of $[-\infty,\infty]$ is measurable. This does not follow from the given condition; the suggested characterization is false.
Counterexample: Say $E$ is some non-measurable set, and let $F=X\setminus E$. Let $f=\infty\chi_E-\infty\chi_F$. Then $f^{-1}((a,\infty))=\emptyset$ for every $a\in\Bbb R$. But $\{\infty\}$ is a Borel subset of $[-\infty,\infty]$, and $f^{-1}(\{\infty\})=E$.

A: You must do this.  Let $\mathcal{S} = \{B\in \mathcal{B}(\mathbb{R})| f^{-1}(B)\in \mathcal{M}\}$.  Then it is easy to show $\mathcal{S}$ is a $\sigma$-algebra.  If $f^{1}(-\infty, a)\in \mathcal{M}$ for all $a\in \mathbb{R}$, it is easy to show that the inverse image of any open interval of under $f$ is in $\mathcal{M}$.  Hence, $\mathcal{S}$ is a $\sigma$-algebra containing all open intervals. You must have $\mathcal{B}(\mathbb{R})\subseteq \mathcal{S}$.


text:
Q: Processing - Overwrite audio Is it possible to make processing overwrite recorded files?
For example, code records ten audio files then when its reaches ten (rec9.wav) it overwrites the first recording (rec0.wav) with new audio and so on. Code below, any help is appreciated, thank you!
import ddf.minim.*;

Minim minim;
AudioInput in;
AudioRecorder recorder;
AudioPlayer player;

int prevTime;
int delay = 10000;
int recID = -1; //what to have a maximum of 10 ID's
int playID = 0;
boolean isRec = false;

void setup(){
  size(512, 200);
  minim = new Minim(this);
  in = minim.getLineIn(Minim.STEREO, 512);
  prevTime = millis();
}

void draw(){
  if (millis() - prevTime > delay){
    prevTime = millis();
    if(!isRec){
      if(recorder != null && recorder.isRecording()) recorder.endRecord();
        else{
        recID++;
        recorder = minim.createRecorder(in, "rec"+recID+".wav", true);
        recorder.beginRecord();
        }
          isRec = true;
          println("RECORDING");
    }else{
      if(recorder != null) {
        recorder.endRecord();
        recorder.save();
        println("Done saving " + recID);
        player = minim.loadFile("rec"+recID+".wav", 2048);
        player.play();
        }
          isRec = false;
          println("SAVING REC " + recID);
    }
  }
}

A: Can't you just do something like this?
recID++;
if(recID >= maxRecordings){
   recID = 0;
}


text:
Q: Meteor Up Deployment to Amazon EC (Ubuntu 14.04) not working I setup a standard Amazon Micro instance with Ubuntu 14.04, set a sudo user, and basically followed the instructions for Meteor Up. I get this error at the "Invoking deployment process" stage...
 -----------------------------------STDERR-----------------------------------
        Warning: Permanently added 'ec2-54-200-136-28.us-west-2.compute.amazonaws.com,54.200.136.28' (ECDSA) to the list of known hosts.
        npm http GET https://registry.npmjs.org/fibers
        npm http 304 https://registry.npmjs.org/fibers
          % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                         Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0curl: (7) Failed to connect to localhost port 80: Connection refused
        Latest deployment failed! Reverted back to the previous version.
        -----------------------------------STDOUT-----------------------------------

        > fibers@1.0.1 install /opt/meteor/tmp/bundle/programs/server/node_modules/fibers
        > node ./build.js

am I doing something wrong? I've got port 80 opened in the Amazon EC2 settings and my mup.json file looks like this:
{
  // Server authentication info
  "servers": [
    {
      "host": "[amazon_IP]",
      "username": "ubuntu",
      "password": "password"
      // or pem file (ssh based authentication)
      //"pem": "~/.ssh/id_rsa"
    }
  ],

  // Install MongoDB in the server, does not destroy local MongoDB on future setup
  "setupMongo": true,

  // WARNING: Node.js is required! Only skip if you already have Node.js installed on server.
  "setupNode": true,

  // WARNING: If nodeVersion omitted will setup 0.10.25 by default. Do not use v, only version number.
  "nodeVersion": "0.10.25",

  // Install PhantomJS in the server
  "setupPhantom": true,

  // Application name (No spaces)
  "appName": "meteor",

  // Location of app (local directory)
  "app": "/home/meteor_apps/thestory",

  // Configure environment
  "env": {
    "PORT": 80,
    "ROOT_URL": "http://54.200.136.28"
  },

  // Meteor Up checks if the app comes online just after the deployment
  // before mup checks that, it will wait for no. of seconds configured below
  "deployCheckWaitTime": 15
}

I just set my ROOT_URL to be the Amazon Public IP... not really sure where Meteor uses ROOT_URL env variable

A: With a micro instance it takes a bit longer for Meteor up to finish bundling your app. Increase deployCheckWaitTime to something like 300 (5 minutes).
Whats happening is Meteor up gives up waiting for it to finish, so you need to increase this timeout.
Also you might want to check the node version, depending on your Meteor version you may need to use  a later version such as 0.10.28 for 0.8.1.2/3. You could try installing it but if you run into trouble you would need to run mup setup again or install node manually.


text: Q: how to keep a distributed software up to date on Linux machines I have my own distributed software running on few RasPi (20+) in different geographical locations, but every time i change something in my app, i have to update the excuteble in all Pi's manually, what are your suggestions to automate this process?


text:
Q: React Context Api Im developing a products table with checkboxes on the side, the check box job is to send the Id of the choosen product once its clicked to it's grandfather so i can build an array of the choosen ones and send them via api.
Its built like this:
grandfather - Table page component.
father - The table itself.
child - The checkbox component.
basically I'm having trouble how to pass the information, i know i should use context api but the syntax is confusing me, here's the code:
Grandfather:
interface Istate {
  Select: boolean;
  SelectT: boolean;
  SelectI: boolean;
  Loader: boolean;
  numOfProds: number;
  listing: any;
  checkBoxId: any;
  prodName: string;
  quantity: number;
  price: number;
  TempProdName: string;
  TempQuantity: number;
  TempPrice: number;
}

interface Iprops {
  id: string;
  name: string;
}

class Products extends Component<Iprops, Istate> {
  state = {
    Select: false,
    SelectT: false,
    SelectI: false,
    Loader: false,
    numOfProds: 0,
    listing: Array,
    checkBoxId: '',
    prodName: '',
    quantity: 0,
    price: 0,
    TempProdName: '',
    TempQuantity: 0,
    TempPrice: 0,
  };

  async componentDidMount() {
    this.showLoader();
    const listing = await AllProductsService.AllProducts();
    this.setState({ listing });
    console.log(listing);
    this.setState({ numOfProds: listing.length });
    this.hideLoader();
  }

  toggleSelect = () => {
    const { Select } = this.state;
    this.setState({ Select: !Select });
  };

  toggleSelect2 = () => {
    const { SelectT } = this.state;
    this.setState({ SelectT: !SelectT });
  };

  toggleSelect3 = () => {
    const { SelectI } = this.state;
    this.setState({ SelectI: !SelectI });
  };

  showLoader = () => {
    this.setState({ Loader: true });
  };

  hideLoader = () => {
    this.setState({ Loader: false });
  };

  CancelValue = () => {
    const { prodName, quantity, price, TempPrice, TempProdName, TempQuantity } = this.state;
    this.setState({ TempProdName: prodName });
    this.setState({ TempQuantity: quantity });
    this.setState({ TempPrice: price });
  };

  changeValue = (checkBoxId: any, value: any) => {
    this.setState({
      [checkBoxId]: value,
    } as any);
  };

  render() {
    const {
      Select,
      SelectT,
      SelectI,
      listing,
      numOfProds,
      Loader,
      checkBoxId,
      prodName,
      quantity,
      price,
      TempProdName,
      TempQuantity,
      TempPrice,
    } = this.state;
    const { name, id } = this.props;
    return (
      <ProductTableProvider
        value={{
          prodName,
          quantity,
          price,
          checkBoxId,
          changeValue: this.changeValue,
        }}
      >
        <Breadcrumb path1="/overview" one="Dashboard" path2="/dashboard/products" two="All Products" />
        <InsideWrapper>
          <Platform>

Products

Manage your products

            <CardStat header="Total" numOf={numOfProds} page="Products" />
            <CardStat header="Ebay" numOf={numOfProds} page="Products" />

                <GreenButton onClick={this.toggleSelect3}>Export to Ebay</GreenButton>
                <SimpleModal isOpen={SelectI} close={this.toggleSelect3} whatToDo={`Export ${name} to Ebay?`}>
                  <YesNoButton name={name} id={id} />
                </SimpleModal>
                <RegularButton onClick={this.toggleSelect}>Save</RegularButton>
                <SimpleModal isOpen={Select} close={this.toggleSelect} whatToDo="Are you sure you want to save?">
                  <YesNoButton name={name} id={id} />
                </SimpleModal>
                <OrangeButton onClick={this.CancelValue}>Cancel</OrangeButton>
                <DeleteButton onClick={this.toggleSelect2}>Delete</DeleteButton>
                <SimpleModal isOpen={SelectT} close={this.toggleSelect2} whatToDo="Are you sure you want to delete?">
                  <YesNoButton name={name} id={id} />
                </SimpleModal>

              <Card>{Loader ? <Loading /> : <DatatablePage listing={listing} />}</Card>

          </Platform>
        </InsideWrapper>
      </ProductTableProvider>
    );
  }
}
export default Products;

Father:
const DatatablePage = (props: any) => {
  const { listing } = props;
  const rows = Array.isArray(listing)
    ? listing.map((val: any) => {
        return {
          select: <CheckBoxComp value={false} id={val._id} />,
          name: <TableText value={val.name} id={val._id} />,
          barcode: val._id,
          category: val.category,
          image: <ImageSec src={ImageProd} />,
          unitsInStock: <TableText value={val.unitsInStock} id={val._id} />,
          price: <TableText value={val.price} id={val._id} />,
          more: <ButtonsPopUp name={val.name} id={val._id} />,
        };
      })
    : [];
  const data = {
    columns: [
      {
        label: '',
        field: '',
        sort: 'disabled',
        width: 20,
      },
      {
        label: 'Name',
        field: 'name',
        sort: 'asc',
        width: 100,
      },
      {
        label: 'Barcode',
        field: 'barcode',
        sort: 'asc',
        width: 100,
      },
      {
        label: 'Category',
        field: 'category',
        sort: 'asc',
        width: 100,
      },
      {
        label: 'Images',
        field: 'images',
        sort: 'asc',
        width: 100,
      },
      {
        label: 'Quantity',
        field: 'unitsInStock',
        sort: 'asc',
        width: 150,
      },
      {
        label: 'Price',
        field: 'price',
        sort: 'asc',
        width: 150,
      },
      {
        label: '...',
        field: 'more',
        sort: 'disabled',
        width: 100,
      },
    ],
    rows,
  };
  return (
    <Rules>
      <MDBDataTable
        entriesLabel="Show Products"
        infoLabel={['Showing', 'to', 'of', 'Products']}
        fixed
        responsive
        btn
        sortable
        hover
        data={data}
        theadColor="white"
      />
    </Rules>
  );
};

export default DatatablePage;

Child:
interface Istate {
  checked: boolean;
  products?: any[];
}
interface Iprops {
  id: any;
  value: any;
  changeValue?: (checkBoxId: string, value: any) => void;
}
class CheckBoxComp extends Component<Iprops, Istate> {
  state = {
    checked: true,
    products: [] as any,
  };

  addOne = (id: any, checked: any) => {
    let { products } = this.state;
    const newObj = { id, checked };
    products = products.concat(newObj);
    this.setState({ products }, () => {
      console.log(products);
    });
  };

  isChecked = (id: any) => {
    const { checked, products } = this.state;
    const { changeValue } = this.props;
    console.log(id);
    this.setState({
      checked: !checked,
    });
    if (changeValue) {
      changeValue(id, checked);
    }
    this.addOne(id, checked);
  };

  render() {
    const { id, value } = this.props;
    const { checked } = this.state;
    return (
      <Fragment>
        <Checkbox>
          {' '}

            <Inputt type="checkbox" value={checked} onChange={this.isChecked.bind(this, id)} />

        </Checkbox>
      </Fragment>
    );
  }
}

export default CheckBoxComp;

any help wrapping the code correctly using context api?


text:
Q: Exchange 2010 Backup Strategy We just moved to Exchange 2010 from another mail system and have been using IDrive for years to back up our Documents & mail on a single windows server.
Previously we just stopped the services that access the mail database and then scheduled an incremental backup in Idrive resulting in small amounts of changed data being sent to idrive nightly.  This system has worked fine for us but now that we on exchange 2010 things seem a little bit more complicated.
We were not sure what exactly what needed to be backed in exchange so Windows Server Backup seemed to fit the bill but it seems windows backup creates a new directory for each backup which will in turn result in duplicate amounts of exchange data being uploaded to idrive.

*

*Is ok to stop the exchange services and back up at file level with IDrive?

*How could a mailbox be restored in this scenario

*Do I need to worry about transaction logs

*Can you suggest a better way?

The server hosting exchange is W2008R2" running as a guest on ESXi 4.1
Note: We plan to make other backups of the server to a NAS device in addition to IDrive.
TIA

A: Just a note on #2:  you'd need to restore your mailbox database to a Recovery Database.
You might want to give the TechNet article a read, to get a little more comfortable with the changes in 2010.

A: *

*Yes this will work. It's very very far from ideal, but as long as the information store is stopped, you can grab file level backups of the database

*I don't believe there's an easy way of restoring the mailbox in this scenario. A third party tool like On Track would have to be used

*This scenario would definitely make you have to worry about transaction logs. The way they typically work, is they are truncated following a backup. This method of backup would not trigger that so they would just grow indefinitely. You can fix that problem by making the database use circular logging, but that may make some recoveries difficult in the event you need to do it.

*A better way of doing this would be to buy software that handles Exchange backups. Symantec's BackupExec or BackupExec System Recovery are options. Shadowprotect has an Exchange backup product that looks really good. Mozy Pro offers an online Exchange backup option (I've never used it, but it looks like it would be better than this).

The solution that I do for most of my clients is this: ShadowProtect Server backs up the server with a single full backup followed by incremental backups every 15 minutes. 1 VSS backup is performed per day which truncates the logs. The base and incremental backups are copied offsite. Ontrack is used for any granular level restores (single mailboxes and such). This has tons of advantages. It's an image based backup, so full recoveries to dissimilar hardware are easy. It's a block level backup so the incrementals don't take up all that much disk space. I've got revisions galore to choose from for restores. I've got offsite copies for total disasters. Also, in a pinch, the shadowprotect backups can be converted into VM disks and virtualized.