text:
Q: JMeter request using JSR223 - 0 and empty response instead of real values Request in JSR223 Sampler works correctly, but here are Sampler result and Response data with 0 and empty values:

Metrics in Sample result in red rectangle are equal to 0.
No response data (both headers and body) are available to see.
Is it possible to get somehow real numbers instead of 0 0 0 0 0 0 for metrics in Sampler result tab and to have visible response in Response data tab?
JSR223 Sampler code:

A: As per reference documentation, you can call those methods:
 SampleResult.connectEnd();
 SampleResult.latencyEnd();
 SampleResult.sampleEnd();
 SampleResult.setResponseData(driver.getPageSource(), "UTF-8");

You can use SampleResult javadocs to see all method or subclasses or custom class of yours.
Note SampleResult is a variable name that JMeter binds into element, not the class, so:

*

*don't prefix it with org.apache.jmeter.samplers.SampleResult, just use SampleResult

*don't import org.apache.jmeter.samplers.SampleResult

Edit (after you added your JSR223 Sampler code):
To fill latency and connect time, use:

*

*SampleResult.setConnectTime()

*SampleResult.setLatency()

As you can get values from Webdriver#executeScript() using such code that exploits Timing API:
long pageLoadTime= (Long)js1.executeScript("return (window.performance.timing.loadEventEnd-window.performance.timing.responseStart)");
long latency= (Long)js1.executeScript("return (window.performance.timing.responseStart-window.performance.timing.navigationStart)");
long endtoEndRespTime= (Long)js1.executeScript("return (window.performance.timing.loadEventEnd-window.performance.timing.navigationStart)");
long connectTime= (Long)js1.executeScript("return (window.performance.timing.connectEnd -window.performance.timing.connectStart)");

A: *

*Connect time and latency - you need to get it from the Navigation Timing API using WebDriver.executeScript() function, once done you can use SampleResult.setConnectTime() and SampleResult.setLatency()

*Response can be obtained using WebDriver.getPageSource() function so you should be able to do something like:
SampleResult.setResponseData(driver.getPageSource())
SampleResult.setBytes(driver.getPageSource().length())

*Remove import of org.apache.jmeter.samplers.SampleResult as it comes as a pre-defined shortcut


text:
Q: Set Foreground of a GroupBox header template using a property from App.xaml.cs This is the Style for a WPF GroupBox.
I am able to set the value of Groupbox background and Groupbox border color from properties defined in App.xaml.cs as shown.
<Style x:Key="StyleGroupBox1" TargetType="GroupBox">
            <Setter Property="Background" >
                <Setter.Value>
                    <Binding Path="GroupBox_Background" Source="{x:Static Application.Current}"/>
                </Setter.Value>
            </Setter>
            <Setter Property="BorderBrush">
                <Setter.Value>
                    <Binding Path="Groupbox_BorderColor" Source="{x:Static Application.Current}"/>
                </Setter.Value>
            </Setter>
            <Setter Property="Margin" Value="1,1,1,1"/>
            <Setter Property="HeaderTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <TextBlock Text="{Binding}" FontWeight="Bold" FontFamily="Palatino Linotype" FontSize="17" Foreground="DarkRed" FontStyle="Italic">

                        </TextBlock>

                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>

How to set the ForeGround of GroupBox's header Template similar to the way in which i have set the background and bordercolor of the Groupbox(ie from a property defined in my app.xaml.cs)?ie currently the header text is set to DarkRed,but how to set it using a property in my App.xaml.cs?

A: <TextBlock
                Text="{Binding}"
                FontWeight="Bold"
                FontFamily="Palatino Linotype"
                FontSize="17"
                Foreground="{Binding Source={x:Static Application.Current}, Path=Groupbox_HeaderForegroundColor}"
                FontStyle="Italic">

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting integer while using strtok() in string I'm new to C and need your help.
I'm trying to get an integer from a string that has a number in it.
I have with me a code I did but the only problem is when I'm assigning years as int i think I'm getting some sort of an address. Is there a way to get my char years into an in years?
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>

 int main()
 {
   char sentence[]="trade_#_2009_#_invest_#_DEALING";

   char *word=strtok(sentence, "_#_");
   char *year=strtok(NULL,"_#_");   // assigning NULL for previousely where it left off
   char *definition=strtok(NULL,"_#_");
   char *synonyms=strtok(NULL,"_#_");

   printf("%s\n", word);
   printf("%s\n", year);
   printf("%s\n", definition);
   printf("%s\n", synonyms);

   return 0;
 }

A: int iYear = 0;
sscanf(year,"%d",&iYear);

This should be the simplest.
You might also want to look at atoi function.

A: Use strtol or strtoul.
Here's an example taken from the strtol page that I linked to above:
/* strtol example */
#include <stdio.h>      /* printf */
#include <stdlib.h>     /* strtol */

int main ()
{
  char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff";
  char * pEnd;
  long int li1, li2, li3, li4;
  li1 = strtol (szNumbers,&pEnd,10);
  li2 = strtol (pEnd,&pEnd,16);
  li3 = strtol (pEnd,&pEnd,2);
  li4 = strtol (pEnd,NULL,0);
  printf ("The decimal equivalents are: %ld, %ld, %ld and %ld.\n", li1, li2, li3, li4);
  return 0;
}


text:
Q: How to respond to 'Would you like to come with us?'
*

*Would you like to come with us?

*Oh, sure. I'd love to.

It is from our OXFORD student book. So my question is
Can students just answer 'I'd love to.' , 'Sure.', 'OK.' or 'That sounds great!'? without 'Yes or No'?

A: Yes, you can answer it that way. The "yes" would be understood. You can also include the "yes" : "Yes, I'd love to."
"I'd love to..." and "That sounds great..." could also mean a refusal, if followed by "but" and a reason not to go.


text:
Q: Count new lines from file doesn't work properly I am trying to count new lines from my file, but it doesn't seem to work. It gives me result 0 when there is 1 new line. How can I fix this?
getline(file, newstring);
char line;
int lines = 0;
for (int i = 0; i < newstring.length(); i++)
{

    if(line== '\n')
    {
        lines++;
    }

}
cout << lines;

A: As I understand it, this may also provide what you need:
#include <iostream>
#include <algorithm>
#include <fstream>
int main()
{
    std::ifstream inFile("file");
    // DISPLAY number of `\n` characters
    std::cout << std::count(std::istreambuf_iterator<char>(inFile),
                            std::istreambuf_iterator<char>(), '\n') << std:: endl;
    inFile.seekg(0); // reset the inFile stream to the first caracter to be read
    /** this also works - thanks to @Armin Montigny for the suggestion*/
    // DISPLAY number of `\n` characters
    std::cout << std::count(std::istreambuf_iterator<char>(inFile),
                            {}, '\n');
}

If I have a file like this:

This would count 11 new lines characters.

A: std::getline reads an entire line (and only one; it's called "getline", not "getlines") up to the line-terminating character, but the result does not include that terminator.
You don't need to look inside the string, you can just count how many times std::getline succeeds.
int lines = 0;
while (getline(file, newstring))
{
    lines++;
}
cout << lines;


text:
Q: Where does p-value should be drawn in case of two tailed Chi squared test? Here is an illustrative example of one tailed test:

In case of one tailed test, the p-value would be area to the left of the critical value 57.336 but in case of two tailed test the p-value is doubled. How to know where to draw the second area?

A: Your first chart illustrates the two-tailed situation.  You are trying to have the two tails having the same probability so you can say they cover values as extreme as or more extreme than the observation.  You can answer your question using the cumulative distribution function and its complement and inverse.
Let's take an example, where you observe the value of $65$ in your $\chi^2_{39}$-distribution; this above the median (near $39$).

*

*R gives pchisq(65,39) as $\mathbb P(X \le 65) \approx 0.994416$.

*Subtract form $1$ to get $0.005584$ as the probability of being extreme in a one-tailed sense

*Double this to get the two-tailed $p$-value of $0.011168$

*The other tail corresponds to the distribution below qchisq(0.005584,39) about $20.21$

*You can get this second value directly with qchisq(1-pchisq(65,39),39)
Incidentally, $\chi^2$ tests are typically one-tailed unless you are investigating fraud, as low $\chi^2$ statistics are typically associated with sample distributions close to the null hypothesis's prediction and so might not be seen as extreme.


text:
Q: Second request to API results in empty string First request to API:
    $siteUrl = $this->getConfig()->get('siteUrl');
    $headers = array(
        "Espo-Authorization: " . $this->getEncodedLoginData()
    );

    $curl = curl_init($siteUrl . '/api/v1/Account');
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $response = curl_exec($curl);
    if (!$response) {
        $GLOBALS['log']->addWarning('curlerr: ' . curl_error($curl));
    }
    curl_close($curl);

    $response = json_decode($response, true);

I get accounts info as expected. But when i try to do next request after some manipulations with accounts, in response i get empty string.
There is an example of next request:
    $siteUrl = $this->getConfig()->get('siteUrl');
    $headers = array(
        "Espo-Authorization: " . $this->getEncodedLoginData()
    );

    $curl = curl_init($siteUrl . '/api/v1/Contacts');
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($curl);
    if (!$response) {
        $GLOBALS['log']->addWarning('curlerr: ' . curl_error($curl));
    }

    curl_close($curl);

Doing requests to API from browser works properly.

A: Problem were in login/pass data. I don't know exactly how, but login/pass vars were changed before executing second request. Thanks for assistance!


text:
Q: Are flags ever automatically declined after edit I flagged this answer (which I think does not attempt to answer the question (Why should I use IDisposable instead of using in c#?). Soon after it was given this (incredibly minor, 6 character) edit, and then the flag was declined (my question is could these actions have been related).
The answer as it now stands:

1.) You should remove finalizer.
  2.) You can have using
  3.) You can call Dispose from try/finally block

To me, this makes no attempt to answer the question... Granted, the entire question is probably off-topic (I also voted to close the questions as "recommending a tool or library...").
Will a flag ever be automatically declined after an edit (or must this have been an honest flag decline)?
Related questions (but mostly older, so I'm not sure if the situation has changed):

*

*Flag declined after a day

*Flag Declined after posted edited the post

*Indicate that a post has been edited since being flagged

*Flag declined after an edit. How can we fix this?

A: Flags that are "not an answer" are never automatically declined or disputed by an edit. The only action that can dismiss these flags automatically is answer deletion, either directly (with the delete link), as a result of converting to comment or appending to question, as a result of question deletion, or by account destruction.
This answer comes off as handwaving to me. I didn't decline the flags, but I suppose handwaving counts as an attempt to answer the queston, if a really poor one.


text:
Q: Prestashop, Get other products with same ean13 in product page I'm newbie to smarty and php.
My situation is that my product_reference is unique but product_ean13 is similar in some products which are like each other. What I need is to have product_id of those products in one of them product page. I mean when visitors open a product page I want to show Image of those products which have the same ean13. Showing the images and HTML, CSS is ok for me, my problem is in PHP,SMARTY which should pass the value from PHP file to TPL file.
I guess I should write a function in Product.php file and pass array values to product.tpl file. But I couldn't.
Would you please help me?
Edited: As you may know a weakness in Prestashop 1.6 is that if your products nature is to have colors and size, like clothes and smartphones! you have two approach to create them. first approach is to create them as a combination of one product and second approach is to create them as separated and not related products. first approach has a good point that all of them will be showed up in product page when customer visits each of them and also have a weakness of exposure in category page which all those attributes will be seen as one product.(imagine between all colors of one shirt only one is seen and your costumer may like blue more but always the red is being showed in category page. or its not easy to know from category page that you also have the gold color of the smartphone) this solution will helps you what to create your products as separated products but you what to show them in product page of each of them. this way we will use benefit of both approach and we wont have the weakness of any of them. we use ean13 (or any other unused field you have, to use as a code that is a same value in same products)

A: I you have created the function in product.php, you should use it in ProductContronller.php and here you can assign a value that contains the list of your products wich has the same ean13.

A: we should add a class in product.php to get cover images of products with the same ean13:
public static function getImageByEan13Product($ean13_colors)
{
    $rows = Db::getInstance()->executeS('
        SELECT `id_product`, `id_image`
        FROM `'._DB_PREFIX_.'image`
        WHERE `id_product` IN ('.implode(',', $ean13_colors).') AND `cover` = 1'
    );
    $images = array();
    foreach ($rows as $row){
        $images[] = array(
            'idProduct' => $row['id_product'],
            'idImage' => $row['id_image']
        );
    }
    return $images;
}

and the following function which gets the color attributes of the products which contain same ean13 code:
public static function getColorByEan13Product($ean13)
{
    $rows = Db::getInstance()->executeS('
    SELECT `id_product`
    FROM `'._DB_PREFIX_.'product`
    WHERE `ean13` = '.$ean13.' AND `active` = 1 AND `id_product` IN (SELECT DISTINCT `id_product` FROM `'._DB_PREFIX_.'stock_available` WHERE `quantity` > 0)');
    $colors = array();
    foreach ($rows as $row){
        $colors[] = $row['id_product'];
    }
    return $colors;
}

and also there is another class in the ProductController.php named assignAttributesGroups() which provide attributes of the product. in this class we should add following code:
$ean13_colors = array();
$ean13_colors = Product::getColorByEan13Product($this->product->ean13);
$this->context->smarty->assign('ean13colors', $ean13_colors);

$ean13_images = array();
$ean13_images = Product::getImageByEan13Product($ean13_colors);
$this->context->smarty->assign('ean13images', $ean13_images);

then these two values ean13_images and ean13_coloes can be used in TPL file product.tpl and showed up instead of color attributes. like the code bellow:
{foreach from=$ean13images key=k item=v}
    {if $product->id != $v.idProduct}

            getProductLink($v.idProduct)|escape:'html':'UTF-8'}" class="pro_column_left selected">
            getImageLink($product->link_rewrite, $v.idImage, 'small_default')}" height="{$smallSize.height}" width="{$smallSize.width}" class="replace-2x img-responsive" {if !isset($from_product_secondary_column) || !$from_product_secondary_column} itemprop="image"{/if} />

    {/if}
{/foreach}

and the value ean13colors can be used where we want to show a balloon tooltip on mouseover the image to say whats the color attribute of the other product that is being showed by same ean13.


text:
Q: How to let user edit his first name and last name in Parse? Swift, Xcode 7 Hi I am a beginner at programming, I have Facebook hooked up with parse. all i want to know is how can a user edit his first name, last name.

A: PFQuery the user information by their currentUser.objectID then just get their new first name and last name then override it in parse.


text:
Q: How does cout << (i > 0); makes it equal to 1? in the statement, cout << (i>0), where i is positive, and greater than 0, how much of an impact does (? > 0) have to always (as far as I have tested) output 1?
#include <iostream>

using namespace std;

int main()
{
    int i = 2, j = 5;
    double k = 5.0;
    cout << (i%j > 0) << " " << (i/k >0) << " " << (100>0) << endl;
    cout << (i%j) << " " << (i/k) << endl;
    return 0;
}

Output:
1 1 1
2 0.4

A: (i>0) returns a boolean true/false, which is then automatically type-casted to 1 or 0 by cout.

A: The expressions you use in perentheses are being evaluated as 'true' or 'false', so when the expression is evaluated a true the output is 1, if false the output is 0. If you want you can enable boolalpha, like this:
cout << boolalpha << (i % j > 0) << (i / k > 0);// rest of code...

The output of this would be:
true false

A: Just set boolalpha like that: http://www.cplusplus.com/reference/ios/boolalpha/


text:
Q: jQuery move list item to end of list I have this list that can be sorted with sortable.
How can I move the li item with class .neutral to the end of the list when sorting is finished?
$(".thumbs").sortable({
    stop: function(event, ui) {
        // move .neutral at the end of this list
    }
});

red

green

none

yellow

blue

A: The equivalent would be the following:
$(".neutral").appendTo(".thumbs");
OR
$(".thumbs").append(".neutral");

You can move an element around a page by selecting it and appending or prepending it elsewhere.
NB: be careful with scope - if you're using classes and this UI appears multiple times on a page the above selctors will need to be scoped to the current instance using the ui parameter passed into the stop function.

A: You can append (moving) them to the end of the list with .appendTo(), like this:
$(".thumbs").sortable({
    stop: function(event, ui) {
      $(this).find('.neutral').appendTo(this);
    }
});

You can give it a try here, this gets all the .neutral elements inside and appends them to this which is the ul.thumbs we're currently in, this will work for multiple independent lists of thumbnails too.


text:
Q: React Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead I am new to react,
i am trying to use async function but i have facing the following error
"Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead."
import {
  Badge,
  Card,
  CardHeader,
  CardFooter,
  DropdownMenu,
  DropdownItem,
  UncontrolledDropdown,
  DropdownToggle,
  Media,
  Pagination,
  PaginationItem,
  PaginationLink,
  Table,
  Container,
  Row,
  UncontrolledTooltip,
} from "reactstrap";
// core components

import Header from "components/Headers/Header.js";
  import 'react-toastify/dist/ReactToastify.css';
import { Link } from "react-router-dom";

import axios from "axios";
import data from "./data";
var apitoken= localStorage.getItem('apitoken');

const api=axios.create({baseURL:"https://IP/DeAPI/api/v1/account"})
const options = {
  headers: {'Authorization': apitoken}
}

const asynchronousFunction = async () => {
  const response = await api.get("/",options)

  window.input=response.data.response

}

const mainFunction = async () => {
  const result = await asynchronousFunction()
  return result
}
const state = { students:window.input}
//console.log(window.input);
  const renderTableData=async ()=> {
    console.log("test"+await mainFunction())
    if(state.students) {

      return state.students.map((student, index) => {
         const { id, name, age, email } = student //destructuring
         return (

                      <Media className="align-items-center">
                         e.preventDefault()}
                        >

                        <Media>
                          {id}
                        </Media>
                      </Media>

                      <Badge color="" className="badge-dot mr-4">{name}</Badge>

                      <Badge color="" className="badge-dot mr-4">{age}</Badge>

                      <Badge color="" className="badge-dot mr-4">{email}</Badge>

         )
      })
    }
    else
    {
      console.log("Something went wrong")
    }
   }

const Accounts = () => {

  return (
    <>

      {/* Page content */}
      <Container className="mt--7" fluid>
        {/* Table */}
        <Row>

            <Card className="shadow">
              <CardHeader className="border-0">

All Account

              </CardHeader>

                    Account Name
                    Phone
                    Email
                    Account Owner
                    {/* Pincode	 */}

                {renderTableData()}

            </Card>

        </Row>

      </Container>
    </>
  );
};

export default Accounts;

What have i done wrong here;
I am trying to get the student data from api and render it in the component dynamically.
The issue is with

                {renderTableData()}

If i removed it its working,
Thanks in advance

A: You should use the lifecycle hook useEffect to fetch async data (when working with functional components).
you also want to save your data in state. This is the default way to work with apis in react. Simply storing it in a variable will not work due to React's async behaviour.
Your error here is that you are trying to render a promise, which is not valid JSX
you can use the hook like this
const [state, setState] = useState({})
...
useEffect(() =>{
async(() =>{
   const data = await mainFunction()
   setState(data)
})()
}, []) //empty array means to only run once

A: You should not put anything except JSX into JSX. The problem is that async function returns Promise instead of JSX. You should rather use React.useEffect and React.useState to solve the loading problem. Let me show you.
Acutally another problem might be returning an array. Try wrapping it into <>...</> as I did.
import * as React from "react";
import {
  Badge,
  Card,
  CardHeader,
  CardFooter,
  DropdownMenu,
  DropdownItem,
  UncontrolledDropdown,
  DropdownToggle,
  Media,
  Pagination,
  PaginationItem,
  PaginationLink,
  Table,
  Container,
  Row,
  UncontrolledTooltip,
} from "reactstrap";
// core components

import Header from "components/Headers/Header.js";
import 'react-toastify/dist/ReactToastify.css';
import { Link } from "react-router-dom";

import axios from "axios";
import data from "./data";
var apitoken= localStorage.getItem('apitoken');

const api=axios.create({baseURL:"https://IP/DeAPI/api/v1/account"})
const options = {
  headers: {'Authorization': apitoken}
}

const TableData = () => {
  const [students, setStudents] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  React.useEffect(async () => {
    const response = await api.get("/",options);
    setStudents(response.data.response);
    setLoading(false);
  }, []);
  if (loading) {
    return <>Loading...</>;
  }

  return (
    <>
      {students.map((student, index) => {
        const { id, name, age, email } = student //destructuring
        return (

              <Media className="align-items-center">
                 e.preventDefault()}
                >

                <Media>
                  {id}
                </Media>
              </Media>

              <Badge color="" className="badge-dot mr-4">{name}</Badge>

              <Badge color="" className="badge-dot mr-4">{age}</Badge>

              <Badge color="" className="badge-dot mr-4">{email}</Badge>

        )
      })}
    </>
  )
}

const Accounts = () => {
 return (
    <>

      {/* Page content */}
      <Container className="mt--7" fluid>
        {/* Table */}
        <Row>

            <Card className="shadow">
              <CardHeader className="border-0">

All Account

              </CardHeader>

                    Account Name
                    Phone
                    Email
                    Account Owner
                    {/* Pincode	 */}

                <TableData />

            </Card>

        </Row>

      </Container>
    </>
  );
};

export default Accounts;

A:

{state.students?.map((student, index) => {
         const { id, name, age, email } = student //destructuring
         return (

                      <Media className="align-items-center">
                         e.preventDefault()}
                        >

                        <Media>
                          {id}
                        </Media>
                      </Media>

                      <Badge color="" className="badge-dot mr-4">{name}</Badge>

                      <Badge color="" className="badge-dot mr-4">{age}</Badge>

                      <Badge color="" className="badge-dot mr-4">{email}</Badge>

         )
      })
}

Try this one instead


text:
Q: XMLPad temp files I am using XMLPad 3.0 to edit my app.config files in a .NET application. For some reason, XMLPad is leaving the ~filename.xml files around in the folder where the XML file I just edited are.
Is there a setting to turn this off?

A: Turn off "create backup files" in global settings | files


text:
Q: How can I retrieve the password policy in LDAP? I am trying to figure out what the password policy for a system is.  Al I could dig up is that the password policy is stored in LDAP in a field called "userPassword" with the following details.  But I can't figure out how to read the rules.  I am using JXPlorer to connect to the database.  Any help would be greatly appreciated.
EQUALITY:
octetStringMatch

NAME:
userPassword

objectClass:
synthetic_JXplorer_schema_object
top

OID:
2.5.4.35

SYNTAX:
1.3.6.1.4.1.1466.115.121.1.40

SYNTAX Description:
Octet String

X-ORIGIN:
RFC 4519

A: In LDAP, the password is stored in the userPassword attribute.
The password policy is a server side configuration. There is no official finalized standard for LDAP password policy, but an internet draft which has been implemented by various vendors, but not all.
Servers that implement that internet draft expose an operational attribute in each user entry : pwdPolicySubentry, and the value is the DN of the password policy enforced for that user.

$ ldapsearch -p 1389 -D cn=directory\ manager -w secret12 -b "" '(uid=bjensen)' dn pwdPolicySubentry
dn: uid=bjensen,ou=People,dc=example,dc=com
pwdPolicySubentry: cn=Default Password Policy,cn=Password Policies,cn=config


text:
Q: Affine transformations in Oxyplot I would like to perform a simple affine transformation to a LineSeries
Unfortunately I cannot simply do this:
foreach (var point in myLineSeries.Points)
{
    point.X = point.X * Math.Cos(angle_rad) + point.Y ...
    point.Y = ...
}

...as the properties X and Y of a DataPoint do not have a public set accessor
Is there a way to perform such operations (simple rotations/translations) on LineSeries without having to call Clear on it and then Add new transformed DataPoints (which doesn't seem very elegant to me)

A: Rather than manipulating points directly in your LineSeries, use MVVM instead: do your calculations in your View Model and then bind results to your View.

ViewModel:
public class MyViewModel
{
    public ObservableCollection<DataPoint> Data1 { get; set; }
    public ObservableCollection<DataPoint> Data2 { get; set; }

    public MyViewModel()
    {
        Data1 = new ObservableCollection<DataPoint>();
        Data2 = new ObservableCollection<DataPoint>();

        double pi = Math.PI;
        double a = pi / 4; // rotation angle
        double fw = 5; // wave frequency
        double fs = 100 * fw; // sampling rate
        double te = 1; // end time
        int size = (int)(fs * te);

        // do your calculations
        var x1 = Enumerable.Range(0, size).Select(p => p / fs).ToArray();
        var y1 = x1.Select(p => Math.Sin(2*pi*fw*p)).ToArray();

        //populate your Model (original data)
        for (int i = 0; i < y1.Length; i++)
            Data1.Add(new DataPoint(x1[i], y1[i]));

        // transform original data
        var x2 = Data1.Select(p => p.X * Math.Cos(a) - p.Y * Math.Sin(a)).ToArray();
        var y2 = Data1.Select(p => p.X * Math.Sin(a) + p.Y * Math.Cos(a)).ToArray();

        // populate your Model (transformed data)
        for (int i = 0; i < y2.Length; i++)
            Data2.Add(new DataPoint(x2[i], y2[i]));
    }
}

XAML:
<Window x:Class="WpfApp93.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:oxy="http://oxyplot.org/wpf"
        xmlns:local="clr-namespace:WpfApp93"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="350">

    <Window.DataContext>
        <local:MyViewModel/>
    </Window.DataContext>

    <Grid>
        <oxy:Plot>
            <oxy:LineSeries ItemsSource="{Binding Data1}"
                            DataFieldX="X"
                            DataFieldY="Y"/>
            <oxy:LineSeries ItemsSource="{Binding Data2}"
                            DataFieldX="X"
                            DataFieldY="Y"/>
        </oxy:Plot>
    </Grid>
</Window>


text:
Q: 2 week sum ending on every second Tuesday I have some data in a format like the reproducible example below (code for data input below the question, at the end). Two things:

*

*Not all dates have a value (i.e. many dates are missing).

*Some dates have multiple values, eg 16 June 2020.

#>        date value
#> 1 30-Jun-20    20
#> 2 29-Jun-20  -100
#> 3 26-Jun-20    -4
#> 4 16-Jun-20   -13
#> 5 16-Jun-20    40
#> 6  9-Jun-20    -6

For two week periods, ending on Tuesdays, I would like to take a sum of the value column.
So in the example data above, I want to sum ending on:

*

*two weeks ending on Tuesday 16 June 2020 (i.e. from 3 June 2020 - 16 June 2020, inclusive)

*two weeks ending on Tuesday 30 June 2020 (17 June 2020 - 30 June 2020 inclusive)

*I'd ultimately like the code to continue summing all two week periods ending on every second Tuesday for when there's more data.

So my desired output is:
#2_weeks_end     total
#30-Jun-20    -84
#16-Jun-20     21

Tidyverse and lubridate solutions would be my first preference.
Code for data input below:
df <- data.frame(
  stringsAsFactors = FALSE,
                date = c("30-Jun-20","29-Jun-20",
                       "26-Jun-20","16-Jun-20","16-Jun-20","9-Jun-20"),
                value = c(20L, -100L, -4L, -13L, 40L, -6L)
)
df

A: Solution using findInterval().
df$date <- dmy(df$date)
df_intervals <- seq(as.Date("2020-06-03"), as.Date("2020-06-03")+14*3, 14)

df %>%
  mutate(interval = findInterval(date, df_intervals)) %>%
  mutate(`2_weeks_end` = df_intervals[interval+1]-1) %>%
  group_by(`2_weeks_end`) %>%
  summarise(total= sum(value))

Returns:
# A tibble: 2 x 2
  2_weeks_end   total
  <date>     <int>
1 2020-06-16    21
2 2020-06-30   -84

A: Here is an option if you like weekly or any other unit that is in lubridate by default:
library(dplyr)
library(lubridate)
df%>%
    mutate(date = as.Date(date, format = "%d-%b-%y"))%>%
    group_by(week_ceil = ceiling_date(date - 1L, unit = "week", week_start = 2L))%>%
    summarize(sums = sum(value))

Here is a data.table approach that creates a reference table followed by a non-equi join:
library(data.table)
setDT(df)
df[, date := as.Date(date, format = "%d-%b-%y")]

ref_dt = df[,  .(beg_date = seq.Date(from = floor_date(min(date), unit = "week", week_start = 3L),
               to = max(date),
               by =  "2 weeks"))]
ref_dt[, end_date := beg_date +13L]

df[ref_dt,
   on = .(date > beg_date,
          date <= end_date),
   sum(value),
   by = .EACHI]

##         date       date  V1
##1: 2020-06-03 2020-06-16  21
##2: 2020-06-17 2020-06-30 -84


text:
Q: Sphinx - reference to an image from different locations I am using Python Sphinx (via ReadTheDocs).
I have a repository which contains a few sub-modules, and I'm trying to create a unified documentation, but still keep the the docs assets in each module separately.
My folder hierarchy is:
MyProject
  docs
    index.rst
    module_1_link.rst
      _static
        <more irrelevant assets...>
  module_1
    docs
      README.rst
      _static
        myimage.png

The index.rst file looks like this:
.. toctree::
    :caption: Module1
    module_1_link

The file module_1_link.rst just contains a link to the README file of module 1:
.. include:: ../module1/docs/README.rst

And the README.rst of module 1 references the image:
.. image:: _static/myimage.jpg

When I look at the README file of module 1 (inside GitHub) - myimage.png is shown perfectly.
But, when I run the documentation via sphinx I get:
 WARNING: image file not readable: _static/myimage.jpg

I can't find a way to reference the same image from both the README file and the index file rendered by sphinx and see it in both places.

A: Change the reference to the image in README.rst to be relative to the documentation root.
.. image:: /module1/docs/_static/myimage.jpg

See also Sphinx documentation on paths to images.

When used within Sphinx, the file name given (here gnu.png) must either be relative to the source file, or absolute which means that they are relative to the top source directory. For example, the file sketch/spam.rst could refer to the image images/spam.png as ../images/spam.png or /images/spam.png.


text:
Q: How can I run a textarea value into JavaScript code? Maybe the title needs edited to be more accurate.
I have a website where I am trying to write a coding tutorial, mostly for my own experience.
I thought a great way to teach is giving the learner a chance for a hands on experience, so I decided to try to allow the user to code in the browser, in a textarea, and more or less see the output. At first, I was using the eval function. It worked okay, for the first assignment (which was to create a string equal to "This is a string", very original, I know), but I couldn't make it flexible enough to work with much more than that, or any multi-line things.
So I guess my question is, is there a way to do this, with any libraries? I know that codecademy has done this, but...
Anyway, thank you for any answers/suggestions you have for me!
EDIT
I should imply, I suppose, that I need to run this code, and output whatever is returned, etc. I can handle most of that, but just want to know how to run it in the first place, or if there is a way to do so, without eval.

A: Here's a nice way to do Eval with JS (github.com/dtao/lemming.js) –  LiamB 16 mins ago
LiamB has provided me with a resource I can use, that is much more dynamic than eval, as per the question. Thanks!


text:
Q: Let gold tag badge duplicates prevail above those of other close voters I just closed a question as duplicate of another with my gold tag badge dupe-hammer (timeline).
I used another duplicate target as the one another user suggested which had just one vote until the time I voted to close. However, this first duplicate (which I found less useful than mine), was still on top in the duplicate notification.
Can we force the duplicate that was chosen by the gold tag badge holder to be on top when closing the question? (Or at least when it outnumbers the existing close votes.)


text:
Q: Why I am getting net::ERR_ABORTED 404 (Not Found) in my django project? I have downloaded a template from online which has these files-

*

*index.html

*gallery.html

*generic.html

I tried to connect these files into my django project.my django settings.py is:
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '6+!*vrjoh*c56kf4u#1+7q=!t&yr6jbakf*8!d^)g-rgvj3w-_'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'blog.apps.BlogConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'projectapp.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'projectapp.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR,'static')
]
STATIC_ROOT= os.path.join(BASE_DIR,'assets')

I included those static files in 'static' folder.I did run python manage.py collectstatic
and the first template is:
{%load static%}
<!DOCTYPE HTML>

        <title>Snapshot by TEMPLATED</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="{%static 'assets/css/main.css' %}" />

Hey, I'm Snapshot

A fully responsive gallery template by TEMPLATED

Continue

What's New

                                        Full Gallery

About Me

Mus sed interdum nunc dictum rutrum scelerisque erat a parturient condimentum potenti dapibus vestibulum condimentum per tristique porta. Torquent a ut consectetur a vel ullamcorper a commodo a mattis ipsum class quam sed eros vestibulum quisque a eu nulla scelerisque a elementum vestibulum.

Aliquet dolor ultricies sem rhoncus dolor ullamcorper pharetra dis condimentum ullamcorper rutrum vehicula id nisi vel aptent orci litora hendrerit penatibus erat ad sit. In a semper velit eleifend a viverra adipiscing a phasellus urna praesent parturient integer ultrices montes parturient suscipit posuere quis aenean. Parturient euismod ultricies commodo arcu elementum suspendisse id dictumst at ut vestibulum conubia quisque a himenaeos dictum proin dis purus integer mollis parturient eros scelerisque dis libero parturient magnis.

Follow Me

Twitter

Facebook

Instagram

Get in Touch

                                    <form action="#" method="post">

                                            Name
                                            <input name="name" id="name" type="text" placeholder="Name">

                                            Email
                                            <input name="email" id="email" type="email" placeholder="Email">

                                            Message
                                            <textarea name="message" id="message" rows="6" placeholder="Message"></textarea>

<input value="Send Message" class="button" type="submit">

                                    </form>

                                © Untitled Design: TEMPLATED. Images: Unsplash.

I have succeded to connect the css files with the static.But in console i am getting this error:
GET http://127.0.0.1:8000/index/%7B%20%static%20'assets/js/jquery.min.js'%%7D net::ERR_ABORTED 404 (Not Found)
127.0.0.1/:131 GET http://127.0.0.1:8000/index/%7B%20%static%20'assets/js/jquery.poptrox.min.js'%%7D net::ERR_ABORTED 404 (Not Found)
127.0.0.1/:132 GET http://127.0.0.1:8000/index/%7B%20%static%20'assets/js/jquery.scrolly.min.js'%%7D net::ERR_ABORTED 404 (Not Found)
127.0.0.1/:133 GET http://127.0.0.1:8000/index/%7B%20%static%20'assets/js/skel.min.js'%%7D net::ERR_ABORTED 404 (Not Found)
127.0.0.1/:134 GET http://127.0.0.1:8000/index/%7B%20%static%20'assets/js/util.js'%%7D net::ERR_ABORTED 404 (Not Found)
127.0.0.1/:135 GET http://127.0.0.1:8000/index/%7B%20%static%20'assets/js/main.js'%%7D net::ERR_ABORTED 404 (Not Found)

As a beginner,i tried some ways.But I dont know how to resolve this problem.Can anyone help please?

A: try this
the way to add the static URL is not correct.
  # error

Refer this https://docs.djangoproject.com/en/3.1/howto/static-files/#configuring-static-files


text:
Q: Changing the color of the animate box Is there a way to change the coloring of the boxes that are generated by Animate or Manipulate? The color of what is gray by default.
Animate[ArrayPlot[CellularAutomaton[n, {{1}, 0}, {40, All}]], {n, 0,
  255, 1}, AnimationRunning -> False]

A: You can wrap Animate and Manipulate with Style and set the DefaultOptions for Panel:
 Style[#, DefaultOptions -> {Panel -> {Background -> LightBlue}}] & @
   Animate[ArrayPlot[CellularAutomaton[n, {{1}, 0}, {40, All}]], {n, 0, 255, 1},
      AnimationRunning -> False]

 Style[#, DefaultOptions -> {Panel -> {Background -> LightBlue}}] & @
   Manipulate[ArrayPlot[CellularAutomaton[n, {{1}, 0}, {40, All}]], {n, 0, 255, 1}]


text:
Q: Insert one array into another array resulting multidimensional arrray There are two arrays:
$arr1 = array
(
    [0] => A
    [1] => B
    [2] => C
    [3] => D
)

$arr2 = array
(
    [0] => d
    [1] => e
    [2] => f
)

I want to make a multidimensional array that would look something like this:
$arr3 = array
(
    [0] => A => array
           (
                [0] => d
                [1] => e
                [2] => f
           )
    [1] => B
    [2] => C
    [3] => D
)

I guess first array's value should be the key of the second array.

A: This should do the trick:
$arr3 = $arr1;
$arr3[0] = array('A' => $arr2);

A: If you want to set dynamicaly then you can use:
$arr3 = $arr1;
$arr3[0] = array($arr3[0] => $arr2);

A: $arr1 = array('A','B','C','D');
$arr2 = array('d','e','f');
$array = $arr1;
$array[0] = array($arr1[0]=>$arr2);
var_dump($array);

Please see https://eval.in/645288


text:
Q: Python function annotation: specify possible parameter types with | (or) I want to use function annotations in Python 3 to specify parameter types, for TypeHinting in PyCharm (https://www.jetbrains.com/pycharm/help/type-hinting-in-pycharm.html).
This works, but not if I have more than one possible type for one parameter. PyCharm help suggests the use of | (or) in this case, and I recall that I have seen this elsewhere as well. My definition looks like this:
def derive_psd(data: numpy.ndarray, sampling_rate: int | float) -> (numpy.ndarray, float):

When I try to import this function I get the following error message:
TypeError: unsupported operand type(s) for |: 'type' and 'type'

Apparently Python compiler does not like the pipe, but what would be the right way to specify two possibilites for types? How would I specify a default value in such a case (e.g. None)?


text:
Q: Implementing onclick listener for app widget I have an app widget which displays some rss feeds.It contains a text view which will display news title and an image view to diplay image.In that widget I want to add two buttons which function as next and previous to navigate through news titles.I know how to do this in an activity but how can I implement onclick listener for these buttons in widget
Here is my xml=>
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
<ImageView
            android:id="@+id/imageView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:scaleType="centerCrop"
            android:src="@drawable/logo" />
<ImageView
            android:id="@+id/imageView2"
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/imageView1"
            android:scaleType="centerCrop"
            android:src="@drawable/titlebg2" />
<ImageView
            android:id="@+id/imageView3"
            android:layout_width="wrap_content"
            android:layout_height="2dp"
            android:layout_below="@+id/imageView2"
            android:layout_centerHorizontal="true"
            android:scaleType="centerCrop"
            android:src="@drawable/foot" />
<ImageView
            android:id="@+id/imageView4"
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:layout_alignParentLeft="true"
            android:layout_alignTop="@+id/imageView2"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="5dp"
            android:scaleType="centerCrop"
            android:src="@drawable/img" />
<Button
            android:id="@+id/next"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/imageView1"
            android:layout_marginRight="3dp"
            android:layout_marginTop="3dp"
            android:background="@drawable/up" />

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/up"
            android:layout_alignBottom="@+id/up"
            android:layout_marginLeft="16dp"
            android:layout_marginRight="25dp"
            android:layout_toRightOf="@+id/imageView4"
            android:text="TextView"
            android:textColor="#ffff" />
      <Button
            android:id="@+id/previous"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignBottom="@+id/imageView2"
            android:layout_alignLeft="@+id/up"
            android:layout_marginBottom="3dp"
            android:background="@drawable/down" />

    </RelativeLayout>

</LinearLayout>

Follwing is my onupdate function,
=>
 public void onUpdate( Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds )
        {

         parse();//Here Iam parsing the xml
         RemoteViews remoteViews;
             ComponentName watchWidget;

            remoteViews = new RemoteViews( context.getPackageName(), R.layout.widget_main );
            watchWidget = new ComponentName( context, madhyamambig.class );

            remoteViews.setTextViewText( R.id.title, Title[0]);

            Bitmap bitmap;
            try {
                bitmap = BitmapFactory.decodeStream((InputStream)new URL(image[0]).getContent());

                 remoteViews.setImageViewBitmap(R.id.imageView4, bitmap);
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                            appWidgetManager.updateAppWidget( watchWidget, remoteViews );

        }

On an activity, we can simply do this like,
     int i=0;
      next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

 Bitmap bitmap;
                try {
                    bitmap = BitmapFactory.decodeStream((InputStream)new      URL(image[i+1]).getContent());

                     remoteViews.setImageViewBitmap(R.id.imageView4, bitmap);
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                                appWidgetManager.updateAppWidget( watchWidget, remoteViews );

            }
          }

        });

I want to implement the same in widget.Somebody please help me...Thanks in advance..

A: You can use RemoteViews.setOnClickPendingIntent method.
Then launch a PendingIntent that will be caught by a service, a broadcast receiver or a service. The context targeted by this intent will be able to manipulate the source widget by using RemoteViews again.
Click processing is a bit more complicated as everything that is a stake here is to manipulate UI elements in a remote process.


text:
Q: user-Defined SQL Function gives error "Invalid column name 'Employee_Name'." I am working one something and I can't get it to work. I am trying to Create a user defined function named Employee_Name. Pass an Employee Id as a parameter.Return the First Name, Last Name, and Phone Number of the employee whose ID matches the id passed to the user defined function.Create a query that uses the function and returns information for the employee with an id of 5. But In order to finish the function employee name I can not get it to work. I keep getting this error:
Msg 207, Level 16, State 1, Procedure Employee_Name, Line 10
Invalid column name 'Employee_Name'.
Msg 208, Level 16, State 1, Line 2
Invalid object name 'Employee_name'.

The code looks like this:
   CREATE FUNCTION Employee_Name
(
    @EmployeeID int
)
RETURNS TABLE
AS
RETURN
(
    SELECT * FROM Employees
    WHERE Employee_Name = @EmployeeId
)
GO

SELECT * FROM Employee_name (1)

Now to get the Return on First name,lastname and phone wouldnt I so a select on the employees id where it goes like this
Select
FirstName,
LastName,
PhoneNumber
From EmployeeId

Or something like that.Now to get the employee with and Id of 5 would i use the count or  do something that has an =5; I am not to sure still confused.
Edit: This is what I have again:
    CREATE FUNCTION Employee_Name
(
    @EmployeeID int
)
RETURNS TABLE
AS
RETURN
(
    SELECT FirstName,LastName,HomePhone
    FROM Employees
    WHERE Employee_Name = @EmployeeId
)
GO

A: WHERE Employee_Name = @EmployeeId <<<-

should that be
WHERE Employee_Id = @EmployeeId

? (or whatever your Id column is named).

A: That's probably because function has the same name as the column.
Try this:
SELECT * FROM Employees
WHERE Employees.Employee_Name = @EmployeeId

or rather
SELECT * FROM Employees
WHERE Employees.EmployeeId = @EmployeeId

A: This line:
WHERE Employee_Name = @EmployeeId

does not make sense. Surely you mean something like
WHERE Employees.EmployeeId = @EmployeeId

?
And this query:
Select
FirstName,
LastName,
PhoneNumber
From EmployeeId

should surely be this:
SELECT FirstName,
       LastName,
       PhoneNumber
  FROM Employees
 WHERE EmployeeId = ...

?


text:
Q: Setting Attributes for Components in React not working I'm following a video course on React, and it is showing us the basics of creating a shopping cart that will eventually look something like this:

I am still early in the course. I am building a component and setting the attributes. Right now, it should just show "Zero" and have the word "Increment" on the button. The problem is, I cannot see the word "Zero" in the Chrome browser. Chrome shows that the word is there, though:

Here is my React code for counter.jsx:
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';

class Counter extends Component {
    state = {
        count: 0
    };
    styles = {
        fontSize: 30,
        fontWeight: 'bold',
    };
    render() {
        return (

                {this.formatCount()}
                <button className='btn btn-secondary btn-sm'>Increment</button>

        );
    }

    formatCount() {
        const { count } = this.state;
        return count === 0 ? 'Zero' : count;
    }
}

export default Counter;

It is called in index.js:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.css';
import Counter from './components/counter';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Counter />
  </React.StrictMode>
);

The course has a forum, and I asked a question about this yesterday >> HERE <<, but there has been no answer, and I cannot continue building the project with the 1st step not working.
Can someone point out what it is that I did wrong?
Also, I personally think that the formatCount() function should declare count as:
    formatCount() {
        const { count } = this.state.count;
        return count === 0 ? 'Zero' : count;
    }

But, that makes it so that the text "Zero" no longer appears in the Chrome debugger. Why?
(I included the bootstrap tag because the index page uses bootstrap, and it could be doing something that is hiding my text)


text:
Q: How to access request object in @MessageMapping method with spring websocket implementation I am integrating an existing spring MVC web application with spring websockets. I was successfully able to integrate by following the instructions in
https://spring.io/guides/gs/messaging-stomp-websocket/
The existing web application has a filter, which sets a few of the attributes. I have a requirement to access the attributes set by the filter in the controller i,e in @MessageMapping method.
Could some one tel how can we access the request object in the @MessageMapping method?

A: When a STOMP client connects to the application, it first has to request a protocol upgrade to switch to websocket. Once using that websocket connection, the messages sent/received don't go through your regular Servlet filter - only the first HTTP request (the "Handshake") did.
Depending on your use case, there are several ways to achieve this.
If it's related to Authentication, then there are existing features for this in the Spring Framework, but also in Spring Security.
If it's related to the HTTP session, you can easily ask for all HTTP session attributes to be copied into the websocket session - or even customize the Handshake for your own needs (see reference doc). Once done, you can inject the Websocket scope in a @MessageMapping controller method and get those attributes (see reference doc).


text:
Q: On iOS is there a way to make all actions on a certain singleton object happen in its own dedicated thread? I'm building a VoIP handset application on iOS (using the PJSIP library), and PJSIP requires you to register the thread that accesses it and manages its configuration, for thread safe purposes. This means handling or managing calls to that library can't be handled by GCD and need to either be on the main thread (terrible solution as it will block and the UI will not draw if there are issues), or create your own dedicated thread.
I've created my own dedicated thread and runloop in my app delegate and perform some selectors on it, but it's messy. I want to encapsulate all of the calls to the current session into a singleton object that I create at launch and have all of those calls occur in their own thread.
Apple's documentation is a bit sparse so I'm trying to figure out if there is a more intelligent way to manage the registered thread on this PJSIP instance. Hell, there may be something I haven't even thought of.
I know it's more of a technical question, but I'd be interested to see what ideas people come up with.
I've already built a category on top of NSThread that allows me to perform blocks on that particular thread but it's an ugly ugly hack.

A: I can think of a few solutions for this. If there are only ever going to be a limited number of methods you could create a static wrapper for each one that gets the singleton instance and then executes the method on the single thread. You could choose per method if you want it to block the calling thread or not.
Another option that comes to mind, that is more elegant and scales better, is to use an event system. You can define an event for each of your methods and if a function wants to execute a method, it would trigger the event. If you need data to be returned from an event you can have the caller register for an event signifying that the method has been completed.
The final solution that comes to mind would be to create a proxy object that will respond to any message using the forwardInvocation: method and call the selector on the real singleton instance on a single thread. (look at Apple's documentation for more information: Forwarding). This is the most complex but probably the most elegant in the end. This would allow for the addition of new function in the future without having to do any extra wrapping.


text:
Q: Open only one Tk.Toplevel window I bound the opening of a new window (Tk.Toplevel) on a button. However, if I press the button twice, two windows turn on.
Can I deactivate the button until the new window is turned off, or display a message box if I press the button twice ?

A: If you don't want to import an external library. You can simply check if root contains any instance of Toplevel using isinstance().
Here is an example:
from tkinter import *
from tkinter import messagebox

def top():

    if not any(isinstance(x, Toplevel) for x in root.winfo_children()):
            top = Toplevel(root)
            lbl = Label(top, text='TopLevel')
            lbl.pack()

    else:

        messagebox.showinfo("showinfo", "Top level already exists")

root = Tk()

btn = Button(root, text='text', command=top)
btn.pack()

root.mainloop()

If you simply want to disable the button.
from tkinter import *
from tkinter import messagebox

def top():

        btn['state'] = 'disabled'
        top = Toplevel(root)
        lbl = Label(top, text='TopLevel')
        lbl.pack()

        top.protocol("WM_DELETE_WINDOW", lambda : btn.configure(state='normal') or top.destroy())

root = Tk()

btn = Button(root, text='text', command=top)
btn.pack()

root.mainloop()

A: You can disable/enable button or you can assign TopLevel to global variable which at start has value None and you check if it is still None before creating window. if it is not None then don't create window. When you close window then you set it again None.
This method can be use for any object which can be only one at some moment - ie. bullet in game.
import tkinter as tk  # PEP8: `import *` is not preferred

# --- functions ---

def close_top():
    global single_top

    single_top.destroy()
    single_top = None

def open_top():
    global single_top

    if single_top is None:
        single_top = tk.Toplevel(root)
        l = tk.Label(single_top, text='TopLevel')
        l.pack()
        single_top.protocol("WM_DELETE_WINDOW", close_top)
    else:
        print("Top level already exists")

# --- main ---

single_top = None

root = tk.Tk()

b = tk.Button(root, text='TOP', command=open_top)
b.pack()

root.mainloop()

EDIT:
The same structure with disabled button
import tkinter as tk  # PEP8: `import *` is not preferred

# --- functions ---

def close_top():

    single_top.destroy()

    b['state'] = 'normal'

def open_top():
    global single_top

    b['state'] = 'disable'

    single_top = tk.Toplevel(root)
    l = tk.Label(single_top, text='TopLevel')
    l.pack()
    single_top.protocol("WM_DELETE_WINDOW", close_top)

# --- main ---

root = tk.Tk()

b = tk.Button(root, text='TOP', command=open_top)
b.pack()

root.mainloop()


text:
Q: Symfony 4 security login allow checking for entity property being false as well as username Just stumbled across an issue, the system i've developed allows multiple user accounts with the same email address, only the user entity has a soft delete flag. Now if there are 2 users with the same email but 1 of them is flagged as deleted the login is picking up the first row in the database which is the deleted one, rather than being able to check if deleted = false during login
I have this in the security yaml:
security:
  providers:
    chain_provider:
      chain:
        providers: [app_user_username,app_user_email]
    app_user_username:
      entity:
        class: App\Entity\User
        property: username
    app_user_email:
      entity:
        class: App\Entity\User
        property: email

  firewalls:
    dev:
      pattern: ^/(_(profiler|wdt)|css|images|js)/
      security: false
    main:
      anonymous: ~
      provider: chain_provider
      user_checker: App\Security\UserChecker
      stateless: true
      json_login:
        failure_handler: App\Security\LoginFailureHandler
        check_path: /user/login
      guard:
        authenticators:
          - App\Security\TokenAuthenticator
  encoders:
    App\Entity\User:
      algorithm: bcrypt
      cost: 15

So it allows login using json for email or username, but symfony does the user selection itself before it gets to the final controller, what i need it to do is select the user in this sort of fashion:
SELECT * FROM user WHERE (email = 'email@email.com' OR username = 'username') AND deleted = 0

NOTE: There will never be more than 1 user with the same email/username that is not deleted but there will likely be multiple deleted ones with a single active one.


text:
Q: Error in ext-base.js This is my EXTJS code:
Ext.onReady(function(){
var treeLoader=new Ext.tree.TreeLoader({
                dataUrl:'json.php'
                                      });
var rootNode=new Ext.tree.AsyncTreeNode({
             text:'Root'
                                       });
var tree=new Ext.tree.TreePanel({
         renderTo:'treecontainer',
         loader:treeLoader,
          root:rootNode
                               });
});

HTML code:
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Tree Formation </title>
<link rel=stylesheet" type="text/css" href="ext-all.css" />
<script src="ext-base.js"> </script>
<script src="ext-all.js"> </script>
</head>
<body>
<script src="tree.js"> </script>
<title id="title">Tree Formed</title>
</body>
<div id="treecontainer" style="height:300px;width:200px;">
</div>
<html>

Json.php:
 [
      {id:'1',text:'No Children',leaf:true},
      {id:'2'.text:'Has Children',
           children:[{
                       id:'3',
                       text:'Youngster',
                       leaf:true
                     }]
      }

After executing the above code,it's displaying with only 'Root' as done,rest not displaying.When i click on that 'Root' Error encountered as "ACCESS IS DENIED" at LINE 7,CHAR 20287 in ext-base.js.Can u tell me what it's ....?
]

A: Looks like you don't have the correct path to your Json.php file, or you don't have read access.


text:
Q: Display value of checkbox in textarea I have here a code that will display the value of the checkbox when checked. My problem is I don't know how I will add up all the numbers, that when I checked a checkbox the number or value will display automatically to the text area and when I checked another checkbox it will add up to the first checkbox that I checked and when I checked another checkbox it should also add up from the first two checkbox. How will I do that?
                <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

            <title></title>
            <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

                <form name="form1" method=post>
                    <textarea name="type" rows="5" cols="35" onclick="this.focus();this.select();"></textarea>

                    <input type="checkbox" name="mis1" id="id1" value="1" onclick="add_sub(this);">1

                    <input type="checkbox" name="mis2" id="id2" value="2" onclick="add_sub(this);">2

                    <input type="checkbox" name="mis6" id="id3" value="3" onclick="add_sub(this);">3

                    <input type="checkbox" name="mis6" id="id4" value="4" onclick="add_sub(this);">4
                </form>

A: Please check this fiddle if this is what you meant:
http://jsfiddle.net/zyfmt4at/5/
this is the script:
var currNum = 0;
var txtArea = document.getElementById("txtArea");
var form = document.getElementById("mainForm");
function add_sub(el){
    debugger;
                if (el.checked)
                {
                    currNum += parseInt(el.value,10);
                }
                else
                {
                    currNum -= parseInt(el.value,10);
                }
                txtArea.value = currNum;
}

form.addEventListener("click", function(ev){
    if(ev.target.getAttribute("type") == "checkbox"){
        add_sub(ev.target);
    }
},false);

this is the HTML:

        <form id="mainForm" name="form1" method=post>
            <textarea id="txtArea" name="type" rows="5" cols="35" onclick="this.focus();"></textarea>

            <input type="checkbox" name="mis1" id="id1" value="1">1

            <input type="checkbox" name="mis2" id="id2" value="2">2

            <input type="checkbox" name="mis6" id="id3" value="3">3

            <input type="checkbox" name="mis6" id="id4" value="4">4
        </form>

A: The solutions proposed above are based on an assumption that the checkbox values are numbers, in case you are in need of string values. You may suggest this.
function add_sub(el)
{

  var cbs = document.getElementById('checkboxes').getElementsByTagName('input');
  var textareaValue = '';
  for (var i = 0, len = cbs.length; i<len; i++) {
    if ( cbs[i].type === 'checkbox' && cbs[i].checked) {
          textareaValue += cbs[i].value + ' ';
    }
  }

   document.getElementById('textarea').value = textareaValue;
}

and
<textarea id="textarea" name="type" rows="5" cols="35" onclick="this.focus();this.select();"></textarea>

     <input type="checkbox" name="mis1" id="id1" value="1" onclick="add_sub(this);">1

     <input type="checkbox" name="mis2" id="id2" value="2" onclick="add_sub(this);">2

     <input type="checkbox" name="mis6" id="id3" value="3" onclick="add_sub(this);">3

     <input type="checkbox" name="mis6" id="id4" value="4" onclick="add_sub(this);">4

And the working plunker:
http://plnkr.co/edit/HWHRsBn7s7vJ9KI4UauU

A: Some tips:

*

*Don't listen to click events to detect changes in checboxes. They can change in other ways, e.g. with the keyboard. You can listen to change events instead.

*Don't use event handler content attributes in the HTML source. Add event listeners using JS.

*Don't add the same event listener to all events. Delegate it to a common ancestor instead.

*br elements are ugly. Better use display: block.

var sum = 0,
    form = document.forms.form1,
    text = form1.elements.type;
text.addEventListener('focus', text.select.bind(text));
form.addEventListener('change', function(e) {
  if(e.target.type == 'checkbox') {
    sum += e.target.value * (e.target.checked ? 1 : -1);
    text.value = sum;
  }
});
label { display: block; }
<form name="form1" method="post">
  <textarea name="type" rows="5" cols="35">0</textarea>
  <input type="checkbox" name="mis1" id="id1" value="1">1
  <input type="checkbox" name="mis2" id="id2" value="2">2
  <input type="checkbox" name="mis6" id="id3" value="3">3
  <input type="checkbox" name="mis6" id="id4" value="4">4
</form>


text:
Q: Constants DL and Fiddle is not defined I am trying to run asposewords for ruby. I check configuration found nothing problem with them. But on running I get this error

/usr/lib/ruby/vendor_ruby/rjb.rb:47:in `load': Constants DL and Fiddle is not defined. (RuntimeError)

I think I have a problem with my rjb, but don't know how to fix it.

A: Thank you for using Aspose.Words Java for Ruby. Currently we support the following platforms:
Ruby 2.2.x or above and respective DevKit.
Java 1.5 or above
Can you please check and confirm which Ruby version you are using?
For more details you can go through the documentation page http://www.aspose.com/docs/display/wordsjava/Aspose.Words+Java+For+Ruby
If you still face any issues, please let us know and we will be glad to help.


text:
Q: Fail Webdriver test if element is present I'm new to Webdriver and I'm wondering how do I make my test case fail if an element is present. Using the following code I can send an output that if the element id errorMessages is present an output will be displayed. Is there anyway I can make the test fail also?
if (driver.findElements(By.id("errorMessages")).size() != 0) {
    System.out.println("Error..Warning Subscriber already exists ");
}

A: With TestNG you can simply use Assert.fail("your message"); inside the if block to mark the test as failed. Something like:
if (driver.findElements(By.id("errorMessages")).size() != 0) {
   Assert.fail("Error..Warning Subscriber already exists ");
}

See this for overloading

A: I think you are looking at it in the wrong way. Rather than checking if the size is what you expect and then forcing the test to fail, use the inbuilt assertion methods so it reads much more like a logical statement:
assertTrue(driver.findElements(By.id("errorMessages")).size() == 0, "Error..Warning Subscriber already exists");

Documentation from the TestNG site
The inbuilt assertion methods will then print out that message if that assertion fails.


text:
Q: What is the probability at least one line in a document will exactly equal the column width? In an English text document with fixed 92 character line breaks, what is the probability that at least one line will be exactly 92 characters long?
The document is 125 lines.
I want to determine how reliably I can determine column width by examining the existing document contents.
I have no idea where to start.

A: You need the distribution of the number of letters in a word in English where a word that has a trailing punctuation mark adds one letter.  For example, if every word were $5$ letters long except for the last word of a sentence words would always end at $5 \bmod 6$ letters and you would never have a line come out even.  Given the distribution of word lengths you could then figure out the chance a line comes out even.  You could do even better if you knew the distribution of pairs of words.  I suspect that if you have a one letter word the next word is more rarely two letters (although I am is reasonably common) than normal.


text:
Q: How to change CSS properties back AFTER click? What is happening

As you can see, the Add button works fine before I click the Remove button. After I click the Remove button, the Add button stays the same color.
What I would like to happen is for the Add button reverts to its old color.
I think the reason its doing this is because in my jQuery I change the colors, but I never change them back after the click is over.
If someone could help me with this I would really appreciated it!
My code
HTML

                                        <button type="button" class="btn btn-default button-bullet">  </button>

                                    <input type="text" name="Worksheet-Problem" class="form-control" placeholder="Problem..." aria-label="Write worksheet problem here">

                                        <button type="button" class="btn btn-default button-add" aria-label="Add">  </button>

CSS
/*get rid of grey shadow when press on buttons*/
.btn.button-add, .btn.button-bullet, .btn.button-bullet:active, .btn.button-add:active, .btn.button-add:focus,
.btn.button-bullet:focus {
    box-shadow: none;
  -webkit-box-shadow: none;
}

/*get rid of Boostrap default grey for buttons*/
.btn.button-add, .btn.button-bullet {
  background-color: transparent;

}

.btn.button-add:hover, #Done-Button:hover{
    background-color: #E5FFFB;
}

.glyphicon-plus-sign, .glyphicon-ok-sign{
    color: #02C8A7;
}

jQuery
$(".worksheet-problems").on("click", ".button-add", function(){
    $(this).css("background-color", "#02C8A7");
    $(this).children(".glyphicon").css("color", "#E5FFFB");
});

JSFiddle
UPDATE
I realized that the glitch is not because I click the Remove button. It's because when I click the Add button, I change the color of that Add button and also clone it to become the next Problem row.
So though these answers change the color of the Add button when the Remove button is clicked, I realize I need something that changes the Add button back after it is cloned to the next row.
Is there some way to delay reverting the Add button color back for half a second? I'm trying to use delay but I don't think I'm using it correctly because nothing is happening.
Updated jQuery
$(".worksheet-problems").on("click", ".button-add", function () {
    var $row = $(this).closest('.row');
    var $wsProbRow = $row.clone(true);
    $wsProbRow.find("input[type='text'][name='Worksheet-Problem']").val("");
    $wsProbRow.insertAfter($row);
    $(this).css("background-color", "#02C8A7");
    $(this).children(".glyphicon").css("color", "#E5FFFB").delay(500).queue(function(){
        $(this).css("background-color", "transparent");
        $(this).children(".glyphicon").css("color", "#02C8A7");
    });
});

Updated JSFiddle

A: Simply update your remove button code to below, to reverse the color changes just only for last row.
$(".worksheet-problems").on("click", ".button-bullet", function() {
    if ($(".worksheet-problems").children().length > 1) {
      //reverse color changes to last row
      $(this).closest('.worksheet-problems .row').last().find(".button-add")
             .css("background-color", "")
             .children(".glyphicon").css("color", "");
      //remove current row
      $(this).closest('.row').remove();

    }
  });

UPDATE
After your update to question now I got your problem use below snippets & complete example.
$(document).ready(function() {
  // have the html reay with you & when needed insert into DOM
  var wsProbRow = $('.worksheet-problems .row')[0].outerHTML;

update add function to below
 $(".worksheet-problems").on("click", ".button-add", function() {
    $(this).closest(".worksheet-problems").append($(wsProbRow));
  });

See below the working example

$(document).ready(function() {
  var wsProbRow = $('.worksheet-problems .row')[0].outerHTML;

  $(".worksheet-problems").on("mouseenter", ".form-group", function() {
    $(this).find(".button-add").fadeIn(100);
    if ($(".worksheet-problems").children().length > 1) {
      $(this).find(".button-bullet").children(".glyphicon").removeClass("glyphicon-one-fine-dot");
      $(this).find(".button-bullet").children(".glyphicon").addClass("glyphicon-minus-sign");
    }
  });
  $(".worksheet-problems").on("mouseleave", ".form-group", function() {
    $(this).find(".button-add").fadeOut(100);
    if ($(".worksheet-problems").children().length > 1) {
      $(this).find(".button-bullet").children(".glyphicon").removeClass("glyphicon-minus-sign");
      $(this).find(".button-bullet").children(".glyphicon").addClass("glyphicon-one-fine-dot");
    }
  });

  $(".worksheet-problems").on("mouseenter mouseleave", ".button-bullet", function() {
    if ($(".worksheet-problems").children().length > 1) {
      $(this).toggleClass("light-red-background");
    }
  });
  $(".worksheet-problems").on("click", ".button-add", function() {
    $(this).closest(".worksheet-problems").append($(wsProbRow));
  });

  $(".worksheet-problems").on("click", ".button-add", function() {
    $(this).css("background-color", "#02C8A7");
    $(this).children(".glyphicon").css("color", "#E5FFFB");
  });

  $(".worksheet-problems").on("click", ".button-bullet", function() {
    if ($(".worksheet-problems").children().length > 1) {

      $(this).closest('.row').remove();

    }
  });

  $(".worksheet-problems").on("click active focus", ".button-bullet", function() {
    if ($(".worksheet-problems").children().length > 1) {
      $(this).css("background-color", "#F53240");
      $(this).children(".glyphicon").css("color", "#FCC1C5");
    } else {
      $(this).css("background-color", "transparent");
    }
  });

})
/*import custom font*/

@import 'https://fonts.googleapis.com/css?family=Work+Sans:100,200,300,400,500,600,700,800,900';
.container-fluid {
  background-color: #86E1D8;
}

/*Page*/

.container {
  margin-top: 50px;
  height: 100vh;
  background-color: white;
  font-family: 'Work Sans', sans-serif;
  /*Background shadow*/
  -webkit-box-shadow: 1px 1px 13px 3px rgba(155, 155, 155, 1);
  -moz-box-shadow: 1px 1px 13px 3px rgba(155, 155, 155, 1);
  box-shadow: 1px 1px 13px 3px rgba(155, 155, 155, 1);
}

/*remove header grey line*/

.page-header {
  border-bottom: none;
}

/*Get rid of that blue outline when input text*/

/*.form-control{
    border: none;
    border-color: #cccccc;
    -webkit-box-shadow: none;
    box-shadow: none;
}*/

/*Get rid of blue outline Chrome*/

.btn:focus,
.btn:active:focus,
.btn.active:focus,
.btn.focus,
.btn:active.focus,
.btn.active.focus {
  outline: none;
}

.btn {
  border: 0px solid transparent;
}

/*Buttons*/

.button-add {
  display: none;
}

#Done-Button {
  margin-right: 20px;
  background-color: white;
}

/*get rid of grey shadow when press on buttons*/

.btn.button-add,
.btn.button-bullet,
.btn.button-bullet:active,
.btn.button-add:active,
.btn.button-add:focus,
.btn.button-bullet:focus {
  box-shadow: none;
  -webkit-box-shadow: none;
}

/*get rid of Boostrap default grey for buttons*/

.btn.button-add,
.btn.button-bullet {
  background-color: transparent;
}

.btn.button-add:hover,
#Done-Button:hover {
  background-color: #E5FFFB;
}

.btn.light-red-background {
  background-color: #FCC1C5;
}

.glyphicon-minus-sign,
.glyphicon-plus-sign {
  font-size: 28px;
}

.glyphicon-minus-sign {
  color: #F53240;
}

.glyphicon-plus-sign,
.glyphicon-ok-sign {
  color: #02C8A7;
}

.glyphicon-ok-sign {
  font-size: 70px;
}

/*Circle icon*/

.glyphicon.glyphicon-one-fine-dot {
  margin-top: -1.4em;
  overflow: hidden;
}

.glyphicon.glyphicon-one-fine-dot:before {
  content: "\25cf";
  font-size: 3em;
}

/*Circular buttons*/

.btn-circle {
  width: 30px;
  height: 30px;
  text-align: center;
  padding: 0px;
  font-size: 12px;
  line-height: 1.428571429;
  border-radius: 15px;
}

.btn-circle.btn-lg {
  width: 50px;
  height: 50px;
  padding: 10px 16px;
  font-size: 18px;
  line-height: 1.33;
  border-radius: 25px;
}

.btn-circle.btn-xl {
  width: 70px;
  height: 70px;
  font-size: 24px;
  line-height: 1.33;
  border-radius: 35px;
}

/*Add borders when hover or click on input boxes*/

input[type="text"] {
  outline: none;
  box-shadow: none !important;
  border: 1px solid white;
  /*make the borders invisble by turning same color as background*/
}

input[type="text"]:hover,
input[type="text"]:focus {
  border: 1px solid #cccccc;
  border-radius: 8px;
}

/*Style input text boxes*/

input[type='text'][name='Worksheet-Name'] {
  font-size: 36px;
  margin-top: 20px;
  margin-left: 15px;
}

input[type='text'][name='Worksheet-Problem'] {
  font-size: 20px;
}

/*Change placeholder*/

input[type='text'][name='Worksheet-Name']::-webkit-input-placeholder {
  /* Chrome/Opera/Safari */
  font-weight: 500;
  font-size: 36px;
}

input[type='text'][name='Worksheet-Name']::-moz-placeholder {
  /* Firefox 19+ */
  font-weight: 500;
  font-size: 36px;
}

input[type='text'][name='Worksheet-Name']:-ms-input-placeholder {
  /* IE 10+ */
  font-weight: 500;
  font-size: 36px;
}

input[type='text'][name='Worksheet-Name']:-moz-placeholder {
  /* Firefox 18- */
  font-weight: 500;
  font-size: 36px;
}

/*Change placeholder*/

input[type='text'][name='Worksheet-Problem']::-webkit-input-placeholder {
  /* Chrome/Opera/Safari */
  font-weight: 400;
  font-size: 20px;
}

input[type='text'][name='Worksheet-Problem']::-moz-placeholder {
  /* Firefox 19+ */
  font-weight: 400;
  font-size: 20px;
}

input[type='text'][name='Worksheet-Problem']:-ms-input-placeholder {
  /* IE 10+ */
  font-weight: 400;
  font-size: 20px;
}

input[type='text'][name='Worksheet-Problem']:-moz-placeholder {
  /* Firefox 18- */
  font-weight: 400;
  font-size: 20px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

      <form>

              <input type="text" name="Worksheet-Name" class="form-control input-lg" placeholder="Worksheet Name..." aria-label="Write worksheet name here">

                    <button type="button" class="btn btn-default button-bullet">  </button>

                  <input type="text" name="Worksheet-Problem" class="form-control" placeholder="Problem..." aria-label="Write worksheet problem here">

                    <button type="button" class="btn btn-default button-add" aria-label="Add">  </button>

      </form>

A: I updated your code with the following changes:
Added a class called '.button-selected' to the button once the button was selected (so we can keep track of which buttons have been selected)
$(".worksheet-problems").on("click", ".button-add", function(){
     $(this).addClass('button-selected');
});

When the '.button-bullet' is selected, I remove 'button-selected' from the previous row's button
$(".worksheet-problems").on("click", ".button-bullet", function () {
    var previousRow = $(this).closest('.row').prev();
    previousRow.find('.button-selected').removeClass('button-selected');

    if ($(".worksheet-problems").children().length > 1) {
        $(this).closest('.row').remove();
    }
});

I also added a few lines of CSS to handle the new class addition 'button-selected'
.btn.button-add.button-selected{
  background-color: rgb(2, 200, 167);
}

.glyphicon-plus-sign{
  color: #02C8A7;
}

.button-selected .glyphicon-plus-sign{
  color: #E5FFFB;
}

Here is the updated fiddle with working code
https://jsfiddle.net/iamnottony/q64280L4/4/


text:
Q: How can I authenticate with credentials in the request parameters with spring-security? I am kind of new to Spring Boot and Spring Security.
I have a situation where I need a request to be authenticated and the username and password are in the request parameters like this localhost:8080?username=bob&password=123
Can someone help me understand how I need to configure my security config, I am trying to do this as Java Config not XML. I also need to disable users trying to authenticate with basic HTTP authentication. So that the only way they can gain access is by providing a username and password in the request parameters. So far my config looks like this:
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .httpBasic().disable()
        .authorizeRequests()
            .antMatchers("/test**").authenticated()
            .antMatchers("/pass**").permitAll();

}

I am not sure how I can look for the credentials in the request parameters.


text:
Q: How to start a loop from a specific index of a list in python? I have this csv file with this data:
1 this_is_x, this_is_y
2 info about x, info about y
2 10,20
3 10,10
4 5,10

with open('my_file.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
next(csv_reader)
for row in csv_reader:
    x, y = row
    list_x.append(x)
    list_y.append(y)

How to start the loop from 10,20 for appending x and y in list_x and list_y without the first two rows?

A: If you repeat the next() statement, one more line will be skipped at the beginning of the file:
    import csv

    list_x = []
    list_y = []

    with open('my_file.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        next(csv_reader)  # skip header line
        next(csv_reader)  # skip second line
        for x, y in csv_reader:
            list_x.append(x)
            list_y.append(y)

Note how you can avoid using intermediate variables while reading in the tuple.

A: As far as I know, csv.reader() method returns a reader object which iterates over lines in the given CSV file, which is not subscriptable, and that means you can't slice it. You can avoid the first two lines by creating a list from csv.reader() returned object and then, just slice it like [2:] to abandon the first two lines of csv file.
Code is given below:
import csv

list_x = []
list_y = []

with open('so_test.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for x, y in list(csv_reader)[2:]:
        list_x.append(x)
        list_y.append(y)

print(list_x)
print(list_y)

And the output is:
['10', '10', '5']
['20', '10', '10']

[P.S.]: This code is tested in python 3.6.8 version.


text:
Q: Define, Importing and Using Custom Element in TypeScript and HTML I am trying to define a custom element and use it in the HTML template, but it doesn't show up, nothing gets logged from the console. It seems the element doesn't get defined this way.
What am I doing wrong? I am using webpack and TypeScript.
I have defined a class that extends a HTML element in top-bar.ts
export class TopBar extends HTMLElement {

    shadowDOM : ShadowRoot;

    constructor() {
        super();
        console.log('from constructor');
        this.shadowDOM = this.attachShadow({mode:"open"});
    }

    connectedCallback() : void {
        this.render();
    }

    render() : void {
        this.innerHTML = `

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

LoRa Dashboard

        `
    }

}

customElements.define("top-bar", TopBar);

and in index.ts, I import the TopBar.
import * as TopBar from './components/top-bar'

and in index.html, I put the top-bar element
<!DOCTYPE html>

    <title>LoRa Dashboard</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

    <top-bar></top-bar>

A: So after a while, I finally found that top-bar.ts doesn't seem to get included in the bundle.
It seems like top-bar doesn't get included although I have imported it in index.ts, my suspect is because that nothing from top-bar.ts is used anywhere in index.ts, only in HTML (when testing). That's why the custom element never gets defined.
So I added a dummy function in top-bar.ts and called it in index.ts only to get it included. This works for my project for now, and I'm new to TypeScript and JavaScript, but I'm sure that there is a better workaround instead of calling a dummy function just to get it included.


text:
Q: Input submit button value disappears when clicked in IE9 I'm running into a weird issue with submit buttons in IE9.  When the "Continue" or "Back" input is clicked, the value disappears.

A: I don't think you should be putting an onclick event on a submit input. A better way to do it would be put an onsubmit on the form and put a javascript function in it which dictates the action of the form depending on the value of the submit button value

A: Update: The issue ended up being a js conflict.


text:
Q: How to add sound to NotifyOSD? I want to hear a sound when notification bubbles pop up. Is it possible to add a custom sound?
Thanks in advance!

A: Right now this ain't possible, but there's a bug about it on Launchpad (see link below), and someone seems to be working on it. Expect the change soon!
Bug: https://bugs.launchpad.net/notify-osd/+bug/549900


text:
Q: Error al instalar flask-mysql
Soy nuevo usando python3 y deseo que me ayuden ya que al insertar el comando sudo pip3 install flask-mysqldb ocurre el siguiente error

A: La solución ya esta, pero publico la respuesta por si a alguien más le pasa lo mismo.
Este error suele ser muy típico el los sistemas Linux y la solución a ello es instalando unos paquetes
El comando para instalar los paquetes.
sudo apt-get install libmysqlclient-dev python-dev


text:
Q: iframe contentWindow is undefined when use window.frames[name] to access If use following way to get the contentWindow, the value is undefined
<html>
<head>
    <title>iframe test</title>
</head>
<body>
    <iframe id="frame1" src="frame1.html" name="frame1"></iframe>
<script>
    document.body.onload = function() {
        console.info("index loaded");
        var frame1 = window.frames["frame1"];
        console.info(frame1.contentWindow);
    }
</script>
</body>
</html>

If use the other way like following, it works fine:
var frame1 = document.getElementById("frame1");
console.info(frame1.contentWindow);

I tested on FF 29.0.1, chrome 34, IE11, they all work the same way.
So I have two questions:

*

*why the first way can't get contentWindow value

*iframe.contentWindow is compatible in all browser?

A: window.frames["frame1"];

is the contentWindow, it gets a named window, and in your case it's the same thing as
document.getElementById("frame1").contentWindow

FIDDLE


text:
Q: Turn encoded ASCII strings into raw characters to store in a MySQL table I need to turn multiple strings, e.g. =E2=86=92 into raw characters in PHP. These strings come from the body of emails retrieved via IMAP.

A: You will need to extract the individual sequences representing a single byte, and convert the hex number to a byte.
A regular expression can be used to extract the =XX sequences, the hexdec() function can convert a hex string sequence to an integer, and the chr() function can convert an integer to a byte.
$inputString = '=E2=86=92';

$binaryString = preg_replace_callback('/=[A-F0-9]{2}/', function($match) {
    return chr(hexdec($match[0]));
}, $inputString);

http://3v4l.org/4MWiq


text:
Q: .NET 3.5 View State We have always had View State Disabled.  We updated our project to WAP and changed the properties of all our projects including web to .NET 3.5.  We notice now that some of our pages have more view state.  Does .NET 3.5 add soemthing that we are not aware of that might turn this on or add something to view state when previously it was disabled in .NET 2.0?

A: Even with viewState disabled
<form id="formMain" runat="server" enableviewstate="false">

the page will include some (much less than normal) viewState information.
from http://msdn.microsoft.com/en-us/library/ms972427.aspx

The page itself saves 20 or so bytes of information into ViewState,
  which it uses to distribute PostBack
  data and ViewState values to the
  correct controls upon postback. So,
  even if ViewState is disabled for the
  page or application, you may see a few
  remaining bytes in ViewState.