text:
Q: TFS 2010/Code Metrics Integration, Automated Builds Fail, Code Metrics Don't Run I'm trying to add an automatic post-build trigger to run NDepend (code metrics software) after an automated team build in TFS 2010.
NDepend's website provided code for integrating this capability, and so I have pasted their code into my .csproj file where they said for it to go, but I receive errors on the build.
The errors refer to two of the three "BuildStep" tags I have in the code snippet.  The following two snippets are giving me errors:
<BuildStep
    TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
    BuildUri="$(BuildUri)"
    Message="Running NDepend analysis">
  <Output TaskParameter="Id" PropertyName="StepId" />
</BuildStep>

and
<BuildStep
   TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
   BuildUri="$(BuildUri)"
   Id="$(StepId)"
   Status="Failed" />

However, this code snippet is NOT throwing up any problems:
<BuildStep
   TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
   BuildUri="$(BuildUri)"
   Id="$(StepId)"
   Status="Succeeded" />

I just don't understand why one works fine and a nearly identically laid out BuildStep tag does not.  Is there something simple that I'm just overlooking?
EDIT: Here is how it looks all together, if this makes a difference:
  <Target Name="NDepend"  >
    <PropertyGroup>
      <NDPath>c:\tools\NDepend\NDepend.console.exe</NDPath>
      <NDProject>$(SolutionDir)MyProject.ndproj</NDProject>
      <NDOut>$(TargetDir)NDepend</NDOut>
      <NDIn>$(TargetDir)</NDIn>
    </PropertyGroup>
    <Exec
      Command='"$(NDPath)" "$(NDProject)" /OutDir "$(NDOut)" /InDirs "$(NDIn)"'/>
  </Target>
  <Target Name="AfterBuild">
    <BuildStep         TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
        BuildUri="$(BuildUri)"
        Message="Running NDepend analysis">
      <Output TaskParameter="Id" PropertyName="StepId" />
    </BuildStep>
    <PropertyGroup>
      <NDPath>c:\tools\NDepend\NDepend.console.exe</NDPath>
      <NDProject>$(SolutionRoot)\Main\src\MyProject.ndproj</NDProject>
      <NDOut>$(BinariesRoot)\NDepend</NDOut>
      <NDIn>$(BinariesRoot)\Release</NDIn>
    </PropertyGroup>
    <Exec
      Command='$(NDPath) "$(NDProject)" /OutDir "$(NDOut)" /InDirs "$(NDIn)"'/>
    <BuildStep
        TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
        BuildUri="$(BuildUri)"
        Id="$(StepId)"
        Status="Succeeded" />
    <OnError ExecuteTargets="MarkBuildStepAsFailed" />
  </Target>

  <Target Name="MarkBuildStepAsFailed">
    <BuildStep
        TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
        BuildUri="$(BuildUri)"
        Id="$(StepId)"
        Status="Failed" />
  </Target>

EDIT: Added a bounty because I really need to get this going for my team.
EDIT: Included more specifics about the errors, I disguised the location/name of the file by "blah" for copyright reasons, I'm not sure if I'm technically able to release that info, so I am erring on the side of safe rather than sorry, but if you absolutely must know for the sake of fixing this problem, I'll see what I can do.  The following errors were listed in the results of the failed team build as well as various other warnings, but these errors were the only ones that I could see that pertained to the NDepend XML code above.
The errors I get when I run the team build:

C:*Blah*.csproj
  (172): The "BuildStep" task was not
  found. Check the following: 1.) The
  name of the task in the project file
  is the same as the name of the task
  class. 2.) The task class is "public"
  and implements the
  Microsoft.Build.Framework.ITask
  interface. 3.) The task is correctly
  declared with  in the
  project file, or in the *.tasks files
  located in the
  "c:\Windows\Microsoft.NET\Framework\v4.0.30319"
  directory.

and

C:*Blah*.csproj
  (194): The "BuildStep" task was not
  found. Check the following: 1.) The
  name of the task in the project file
  is the same as the name of the task
  class. 2.) The task class is "public"
  and implements the
  Microsoft.Build.Framework.ITask
  interface. 3.) The task is correctly
  declared with  in the
  project file, or in the *.tasks files
  located in the
  "c:\Windows\Microsoft.NET\Framework\v4.0.30319"
  directory.

EDIT: I thought I had it running right, but it sill isn't building properly. It's still throwing up the errors above when I build, despite mimicking @Ewald's suggested XML below.  I adjusted the property values of said code according to what I think should work as follows:
  <Target Name="NDepend"  >
    <PropertyGroup>
      <NDPath>c:\tools\NDepend\NDepend.console.exe</NDPath>
      <NDProject>$(SolutionDir)MyProject.ndproj</NDProject>
      <NDOut>$(TargetDir)NDepend</NDOut>
      <NDIn>$(TargetDir)</NDIn>
    </PropertyGroup>
    <Exec
      Command='"$(NDPath)" "$(NDProject)" /OutDir "$(NDOut)" /InDirs "$(NDIn)"'/>
  </Target>

  <Target Name="AfterBuild">
    <BuildStep
        TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
        BuildUri="$(BuildUri)"
        Name="CallMyTarget"
        Message="Call My Target"
        Condition="'$(IsDesktopBuild)'!='true'">
      <Output TaskParameter="Id" PropertyName="StepId" />
    </BuildStep>
    <CallTarget Targets="NDepend" ContinueOnError="false"/>
    <BuildStep
        TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
        BuildUri="$(BuildUri)"
        Id="$(StepId)"
        Status="Succeeded"
        Condition="'$(IsDesktopBuild)'!='true'" />
    <OnError ExecuteTargets="FailStep" />
  </Target>

  <Target Name="FailStep">
    <BuildStep
        TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
        BuildUri="$(BuildUri)"
        Id="$(StepId)"
        Status="Failed"
        Condition="'$(IsDesktopBuild)'!='true'" />
  </Target>

However, I did try just putting this code in:
  <Target Name="NDepend"  >
    <PropertyGroup>
      <NDPath>c:\tools\NDepend\NDepend.console.exe</NDPath>
      <NDProject>$(SolutionDir)MyProject.ndproj</NDProject>
      <NDOut>$(TargetDir)NDepend</NDOut>
      <NDIn>$(TargetDir)</NDIn>
    </PropertyGroup>
    <Exec
      Command='"$(NDPath)" "$(NDProject)" /OutDir "$(NDOut)" /InDirs "$(NDIn)"'/>
  </Target>

And the automated build went fine, no errors, but the NDepend just didn't run like it was supposed to.
I'm beginning to wonder (after consultation with various other sub-questions) if there's some slight difference in the XML schema used in TFS2010 vs TFS2008 that is causing me to have these problems.  So, with that in mind, does anyone know about any big differences in these schemas?
EDIT: Just keeping you all up to date with everything I've tried, I now tried this code:
<Target Name="AfterBuild">
    <PropertyGroup>
      <NDPath>c:\tools\NDepend\NDepend.console.exe</NDPath>
      <NDProject>$(SolutionDir)MyProject.ndproj</NDProject>
      <NDOut>$(TargetDir)NDepend</NDOut>
      <NDIn>$(TargetDir)</NDIn>
    </PropertyGroup>
    <Exec
      Command='"$(NDPath)" "$(NDProject)" /OutDir "$(NDOut)" /InDirs "$(NDIn)"'/>
</Target>

and it produced a different error message, as follows:

C:*Blah*.csproj
  (179): The command
  ""c:\tools\NDepend\NDepend.console.exe"
  "C:*Blah*\Sources\Main\MyProject.ndproj"
  /OutDir
  "C:*Blah*\Binaries\Debug\NDepend"
  /InDirs
  "C:*Blah*\Binaries\Debug\""
  exited with code 1.

EDIT: The latest code I tried.  This was (according to NDepend's site) the "built-in NDepend MSBuild task."
<Target Name="AfterBuild">
    <PropertyGroup>
        <NDPath>c:\tools\NDepend\NDepend.console.exe</NDPath>
        <NDProject>$(SolutionDir)MyProject.ndproj</NDProject>
      </PropertyGroup>
      <UsingTask AssemblyFile="$(NDPath)\MSBuild\NDepend.Build.MSBuild.dll"
             TaskName="NDependTask" />
      <Target Name="NDepend"  >
        <NDependTask NDependConsoleExePath="$(NDPath)"
           ProjectFilePath="$(NDProject)" />
      </Target>
</Target>

But I get this error:

C:*Blah*.csproj (180): The element
   beneath element
  is unrecognized.

A: I use the following lines of code to achieve additional build steps
<Target Name="Customization">
    <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Name="CallMyTarget" Message="Call my target" Condition="'$(IsDesktopBuild)'!='true'" >
        <Output TaskParameter="Id" PropertyName="CurrentBuildStepId" />
    </BuildStep>

    <CallTarget Targets="MyTarget" ContinueOnError="false"/>

    <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Id="$(CurrentBuildStepId)" Status="Succeeded" Condition="'$(IsDesktopBuild)'!='true'" />

    <OnError ExecuteTargets="FailStep"/>
</Target>

<Target Name="FailStep">
    <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Id="$(CurrentBuildStepId)" Status="Failed" Condition="'$(IsDesktopBuild)'!='true'" />
</Target>

A: The code snippets only work when you run Team Build. They will probably fail when you run a desktop build. You can safely remove these lines because all they do is adding a line the build log if you are using Team Buid.


text:
Q: Overwrite value of the Database, independent of the Context: Ebean, play-Framework, Model, Optemistic Locking
Is it possible to set an annotation to a value of a model, which tells ebean that it shouldn't throw a "optemistic locking exception" for this value, because it is independent of the previous data?
Example usage: I have a lastAction value, which is updated frequently. It doesn't matter if this value is absolut correct, because it is just used to determin the automated logout time or deletion time (registered and guest user).

A: I believe that you can achieve this by using 2 separate tables one for optimistic-lockable attributes, another one for do-not-care attributes.
Later you can combine them in one DB view.
For example:
  create table optimistic_lockable {
    id bigint primary key
    ....
  }

  create table non_lockable {
     id primary key
     ,lockable_id foreign key refences optimistic_lockable (id)
  }

  create view model_view as
  select * from optimistic_lockable ol, non_lockable nl
  where ol.id = nl.lockable_id

You map your model to model_view. And IFF the DB engine allows to insert into view, you'll probably be fine ;)

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Premature end of Content-Length delimited message body" - Error while accessing json file from S3 bucket using pyspark I am trying to load a large (larger than my system memory) json from s3 bucket to spark Dataframe. but getting below error.

org.apache.http.ConnectionClosedException: Premature end of
Content-Length delimited message body (expected: 138345560; received:
67924532

*

*I am using spark 2.4.7 and Hadoop 2.7 distribution, with python 3.7.

*I have copied "hadoop-aws:2.7.3.jar" & "aws-sdk:1.7.4.jar" in

*Sparkhome/jars/ directory. Using JDK 1.8 (set SPARK_HOME, JAVA_HOME,
HADOOP_HOME) environment variables already.

*previously had python 3.8, java 15, spark 3.0 with hadoop 2.7 - downgraded because of this error.

# pyspark_job.py
from pyspark.sql import SparkSession

def create_spark_session():
    """
    Create spark session.
    Returns:
        spark (SparkSession) - spark session
    """
    spark = SparkSession \
        .builder \
        .master("local[4]") \
        .appName("Myappname") \
        .getOrCreate()
    return spark

def setConfigs(spark):
    """
    setting the environment configuration properties for s3 access
    arguments:
        spark (SparkSession) - spark session
    """
    ak = 'accesskey'    # as of now I am using the keys directly, once i get the basic functionality working, the keys will be taken from property file/env variable
    sk = 'secretkey'
    sc = spark.sparkContext
    sc._jsc.hadoopConfiguration().set("fs.s3a.access.key",  ak)
    sc._jsc.hadoopConfiguration().set("fs.s3a.secret.key", sk)
    sc._jsc.hadoopConfiguration().set("fs.s3a.readahead.range", '512M')

def process_events_data(spark, input_path):
    """Process the event data from s3 bucket as json files and get specific info.
    Arguments:
        spark (SparkSession) - spark session connected to local cluster
        input_path (str) - AWS S3 bucket path for source data
    returns
        Data Frame with event data
    """
    df = spark.read.format('json').load(input_path)
    #df = spark.read.json("input_path")
    return df

def main():
    bn = 'bucketname'
    sf = 'prefix/'
    fp = bn+sf
    input_path = 's3a://bucketname/prefix/filename.json'

    spark = create_spark_session()
    setConfigs(spark)

    edf = process_events_data(spark, input_path)

if __name__ == '__main__':
    main()

Error trace:

20/09/29 22:32:35 WARN TaskSetManager: Lost task 1.0 in stage 0.0 (TID
1, localhost, executor driver): TaskKilled (Stage cancelled) Traceback
(most recent call last):   File "pyspark_job.py", line 61, in
main()   File "pyspark_job.py", line 58, in main
process_events_data(spark, input_path)   File "pyspark_job.py", line 41, in process_events_data
df = spark.read.format('json').load(input_path)   File "spark_dir\spark-2.4.7_h2.7\python\lib\pyspark.zip\pyspark\sql\readwriter.py",
line 166, in load   File
"spark_dir\spark-2.4.7_h2.7\python\lib\py4j-0.10.7-src.zip\py4j\java_gateway.py",
line 1257, in call   File
"spark_dir\spark-2.4.7_h2.7\python\lib\pyspark.zip\pyspark\sql\utils.py",
line 63, in deco   File
"spark_dir\spark-2.4.7_h2.7\python\lib\py4j-0.10.7-src.zip\py4j\protocol.py",
line 328, in get_return_value py4j.protocol.Py4JJavaError: An error
occurred while calling o42.load. : org.apache.spark.SparkException:
Job aborted due to stage failure: Task 0 in stage 0.0 failed 1 times,
most recent failure: Lost task 0.0 in stage 0.0 (TID 0, localhost,
executor driver): org.apache.http.ConnectionClosedException: Premature
end of Content-Length delimited message body (expected: 138345560;
received: 71284276

already tried below solutions but still getting the error:
Premature end of Content-Length delimited message body SparkException while reading from S3 using Pyspark
I am not sure if some configuration is missing? or something wrong on S3 side? or do i need to read the json input line by line?
This is my first spark program, can anyone help.


text:
Q: Submit button does not trigger a jQuery bind'ed submit event on IE I have a problem with IE (8, have not tested on 7). I have a very simple situation: I create a form element
var formNode = $('<form>');

I attach a bunch of other elements to the form (fieldsets with input elements inside of tables). I then attach the form to the DOM, and then bind a submit handler:
formNode.bind('submit', function (ev) {
   alert('submit of form!');
   // do lots of stuff....
 }

This works with Safari on my Mac (yah, I'm a Mac guy), and on Safari and Firefox on Windows, but the alert is never called when I click the submit button when using IE 8. Instead, the browser tries to submit a GET request for /  (I have not set either a Method or an Action for the form - perhaps that is necessary?).
Any insights would be greatly appreciated as I am making changes hit-or-miss in order to debug.

A: There a variety of issues with listening for events from form elements with jQuery in Internet Explorer. There are a  series of comments on the jQuery forum about:
IE-specific issues with live ('submit'). Granted I know you are using bind and not live but many of the described problems involve attempts at using both.
I commented on your answer asking which version of jQuery you are using. If you haven't already and can do so I'd upgrade to the latest release.
A few code solutions:
Bind the submit handler to each child of the body elementadapted from synertech1 answer in the aforementioned jQuery forum discussion.
var submitHandler = function() { ... };

$("body").children().each(function() {
      $("form", this).bind("submit", submitHandler);
})

Bind to the submit input type
I hate this option because the form element is the more appropriate element to bind to.
 $('form > input[type*="submit"]').bind('click', function(event) {
     var form = $(this).parent;
     form.submit();
     event.preventDefault();
 });

A: You haven't said what level of HTML you're using, but FWIW, action is a required attribute on form elements in HTML4. So it wouldn't be too surprising if a browser behaved oddly without it. (In HTML5, the validator says it's not required any longer, probably because some of this stuff is now allowed on the submit buttons themselves.)

A: Are you remembering to return false (or event.preventDefault()) from your event handler? If not, the form will continue to submit, effectively navigating you to the action URL, or the same URL as the current document, if there is none. Though really there should be some action both for HTML validity and to provide a working non-JavaScript solution where possible (progressive enhancement and all that).
If you do have the return false, make sure no JavaScript errors are occurring in the handler code that abort the function before it gets to return false. Turn on JS error reporting in the Internet Options and/or use the debugger.


text:
Q: Type id  does not conform to id  -- but it does! Alright, I have two protocols in the same header file, let's call them Protocol1 and Protocol2.  I have a main app controller that conforms to both protocols, and an NSWindowController subclass that has the following member:
id <Protocol1, Protocol2> delegate;

I'm getting a warning at the end of my NSWindowController subclass implementation that "type id  does not conform to Protocol2".  But, as shown, the delegate must conform to both protocols, which it does.
Furthermore, the application works perfectly.  Is there some other way to do this?  I suppose I could just fold the two protocols in together, but that would hurt the modularity of the program.
EDIT:
Here are the two protocols.  As this is more of a test scenario, they're short.
@protocol TPTBController <NSObject>

-(void)sendGrowlMessage:(NSString *)message title:(NSString *)title;

@end

@protocol AddPower <NSObject>

-(void)addPower:(NSArray *)array;
-(void)setCanAddPower:(BOOL)can;

@end

A: The language spec isn't clear if the id-with-protocols actually supports a protocol list or not. Protocols can extend protocol lists, but it's not clear if that syntax supports it or not.
You could create a combined protocol:
@protocol AddPowerAndTPTBController <AddPower, TPTBController>
@end
...
id <AddPowerAndTPTBController> delegate;

Whilst not elegant, it would work; but it would require your delegate class to conform to the AddPoewrAndTPTBController as well, not just the two individually.

A: Are you importing the protocols on your NSWindowController subclass?
That the application works points me in that direction. It seems that when doing the static checking, the compiler can't figure that your class conforms to the protocols, while when actually dispatching messages it's succeeding (and that's why the application works as expected)

A: What happens if you break the protocols apart into separate files, then import them both into your NSWindowController class?


text:
Q: BASH bug or feature?: Shadowing a readonly global variable with a writable local variable (Possibly this is the same question as Function local read-only vs. global read-only variable with the same name)
In a script I wrote I'm using readonly key="$1" (for the program parameter) at the global level, and a function uses local key="$1" (for the function parameter this time), too.
To my surprise BASH 4.4 outputs:

...: local: key: readonly variable

In my understanding there is a global readonly variable, but the local variable should be independent of it, even when having the same name, right?
Or did I misunderstand something?
Reading the manual page on local did not bring me any further.
Or is it that local does not declare a local variable, but a local value for a (global) variable (thus the global read-only status preventing even a local change)?
Would be a rather confusing concept then IMHO.


text:
Q: Y axes has unexpected value when drawing rectangle I am drawing a rectangle using the drawRect method. I use x, y to give initial values for the rectangle. And these values are x = 150, y=300.
So I've got this:

Now I made the printing of coordinates in the log when touching the screen.
The problem is when I am touching the up left corner of rect (150, 300) I'm getting next values in the log:
D/TOUCH:: x=153, y=370
It is the correct value for X but incorrect for Y because as said I put initial Y==300. My question is why it is so?


text:
Q: Relative svg size My question>
The code
Please see it in full screen mode ;)

var elmids = ['playground'];

      var x, y = 0;
      function getXYpos(elm) {
        x = elm.offsetLeft;
        y = elm.offsetTop;

        elm = elm.offsetParent;

        while(elm != null) {
          x = parseInt(x) + parseInt(elm.offsetLeft);
          y = parseInt(y) + parseInt(elm.offsetTop);
          elm = elm.offsetParent;
        }

        return {'xp':x, 'yp':y};
      }

      function getCoords(e) {

        var xy_pos = getXYpos(this);

        if(navigator.appVersion.indexOf("MSIE") != -1) {
          var standardBody = (document.compatMode == 'CSS1Compat') ? document.documentElement : document.body;

          x = event.clientX + standardBody.scrollLeft;
          y = event.clientY + standardBody.scrollTop;
        }
        else {
          x = e.pageX;
          y = e.pageY;
        }

        x = x - xy_pos['xp'];
        y = y - xy_pos['yp'];
        document.getElementById('log').innerHTML = 'X= '+ x+ ' ,Y= ' +y;
      }

      for(var i=0; i<elmids.length; i++) {
        if(document.getElementById(elmids[i])) {
          document.getElementById(elmids[i]).onmousemove = getCoords;
        }
      }
@font-face {
        font-family: ubuntu-mono;
        src: url(ubuntu-mono.ttf);
      }

      @font-face {
        font-family: ubuntu;
        src: url(ubuntu.ttf);
      }

      html{
        height: 90%;
      }

      body{
        background-color: #9c7055;
        height: 90%;
        justify-content: center;
        overflow: hidden;
      }

      .bg{
        position: relative;
        top: -30%;
        bottom: 10px;
        height: 610px;
        width: 410px;
        margin-left: auto;
        margin-right: auto;
      }

      p{
        font-family: ubuntu-mono;
        font-size: 30px;
      }

      #cptpcp::after{
        content: "'s turn";
      }

      #cptpc{
        position: relative;
        width: 100%;
        top: -20px;
      }

      h1{
        top: -9vh;
        position: relative;
        text-align: center;
        font-size: 17vh;
        font-family: ubuntu;
        width: 100%;
      }
<!DOCTYPE html>

    <meta charset="utf-8">

        NaPa

      <?xml version="1.0" encoding="UTF-8" standalone="no"?>
      <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="450" height="610" viewBox="0 0 1000 1355.56" xml:space="preserve">
        <g transform="matrix(2.43 0 0 2.43 498.11 681.07)">
          <g>
            <g transform="matrix(0 -0.97 0.97 0 -0.09 257.4)">
              <path style="stroke: rgb(255,255,255); stroke-width: 9; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;"  transform=" translate(0, 0)" d="M -1.0658141e-14 -199.26991 L 1.0658141e-14 199.26991" stroke-linecap="round" />
            </g>
            <g transform="matrix(0 -0.94 0.94 0 -189.08 -0.11)">
              <path style="stroke: rgb(255,255,255); stroke-width: 8; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;"  transform=" translate(0, 0)" d="M -277.29633 0 L 277.29633 0" stroke-linecap="round" />
            </g>
            <g transform="matrix(0 -0.94 0.94 0 2.17 0.03)">
              <path style="stroke: rgb(255,255,255); stroke-width: 8; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;"  transform=" translate(0, 0)" d="M 275 -197.5 L -275 197.5" stroke-linecap="round" />
            </g>
            <g transform="matrix(0 -0.97 0.97 0 1.31 -258.98)">
              <path style="stroke: rgb(255,255,255); stroke-width: 8; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;"  transform=" translate(0, 0)" d="M 0 -198.51007 L 0 198.51007" stroke-linecap="round" />
            </g>
            <g transform="matrix(0 -0.94 0.94 0 188.96 0)">
              <path style="stroke: rgb(255,255,255); stroke-width: 8; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;"  transform=" translate(0, 0)" d="M 278.662 -2.842171e-14 L -278.662 2.842171e-14" stroke-linecap="round" />
            </g>
            <g transform="matrix(0 -0.94 0.94 0 -1.97 -2.84)">
              <path style="stroke: rgb(255,255,255); stroke-width: 8; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;"  transform=" translate(0, 0)" d="M 0 -200.06248 L 0 200.06248" stroke-linecap="round" />
            </g>
            <g transform="matrix(0 -0.94 0.94 0 -1.03 0.16)">
              <path style="stroke: rgb(255,255,255); stroke-width: 8; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;"  transform=" translate(0, 0)" d="M -277.29633 0 L 277.29633 0" stroke-linecap="round" />
            </g>
            <g transform="matrix(0 -0.94 0.94 0 1.77 -2.42)">
              <path style="stroke: rgb(255,255,255); stroke-width: 8; stroke-dasharray: none; stroke-linecap: butt; stroke-dashoffset: 0; stroke-linejoin: miter; stroke-miterlimit: 4; fill: rgb(0,0,0); fill-rule: nonzero; opacity: 1;"  transform=" translate(0, 0)" d="M -273 -200 L 273 200" stroke-linecap="round" />
            </g>
          </g>
        </g>
      </svg>

There are two main questions that that are related to each other :-

*

*How do i make the size of the svg and the div with the id 'playground' relative to the screen size

*And while keeping them relative to the screen size i should get the x,y coordinate of the mouse in the svg and the 0%,0% coordinate should be the start of the svg. unlike my code i want to get it in % not px i think i can use JQuery's $(window).width() & $(window).height() and use it to map the values from pixels to percent.

Hope I am clear if not please comment to this post.

A: Oh I just found an answer to this By using preserveAspectRatio="none" in the svg and resizing it in css and using JQuery's $(window).width() & $(window).height() I was able to map the values using this funtion(I tried creating a function like aurdinos map())
function map(x, in_min, in_max, out_min, out_max) {
  return Math.trunc((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min);
}


text:
Q: Displaying utf8 on flash? I am using flash to read contents from a UTF8 page, which has unicode in it.
The problem is that when Flash loads the data it displays ???????? instead all unicode.
What could be the problem?

A: By default Flash treats strings as if they are encoded using UTF-8. The reason that you are seeing characters that possibly substitute non-printable characters or invalid / missing glyphs could be that you set System.useCodepage to true - if that's what happened, then why did you do that?
Otherwise, the font that is used to display the characters may be missing glyphs for the characters you need. You can check that by using Font.hasGlyphs("string with the glyphs"); to make sure the text can be displayed. This would normally only apply to embedded fonts.
Yet another possibility is that the source text you are trying to display is not a UTF-8 encoded string. Some particularly popular file formats such as XML and HTML some times use a declaration of the format in no correspondence to the actual payload (example XML tag: <?xml encoding="utf-8" ?> can be attached to any XML regardless of the actual encoding of the document). In order to make sure that the text is in UTF-8 - read it as ByteArray and verify that the first bit of every byte is set to 0. Single-byte encodings that use national characters use the first bit to encode their characters, while UTF-8 never does that.

A: Flash internally uses UTF-8 to represent strings, so there should not be a problem if the entire stack uses UTF-8 encoding.
You probably have an implicit decode/encode step somewhere along the way.
This could really be a million things, unfortunately.  Start from the ground up, insert traces and/or log messages to see where the conversion fails.  Make sure your XML-content uses UTF-8, and especially if you're using PHP, make sure that all the PHP source files are saved in UTF-8 encoding - editing PHP files in simple text editors often results in Windows/Mac format source files, which will then break your character encoding. Also, verify HTML request/response headers to see if there is an encoding mismatch.


text:
Q: Non-parametric outlier extimation Are there ways to automatically detect outliers ( we can fix uni-dimensional datasets ) when the underlying distribution is difficult to model ?
Intuitively, reseampling techniques could help.
(1) You split the data into two sets, S1 and S2.
(2) You fit an empirical distribution on S1 (e.g. using hystograms).
(3) You develop an engine to detect if points in S2 are compatible with the non-parametric distribution fitted using data from S1.
(4) Repeat this for may S1, S2 splits and record how many times the point was detected as an outlier.
As an example of Step (3), one could evaluate the interquartile range based on S1 and check how many and which points in S2 do not fall in the interquartile range.
Questions:

*

*I am not sure that this intuitive idea make sense or can be made more rigorous or even implemented in a sensible way. Are there such methods ?

*Alternatively, is there a "standard" for outlier estimation in a non-parametric setting ?


text:
Q: HTTP Basic authentication user name I am using HTTP Basic authentication in a web application. Once the user enters the credentials into the browser login window, the application starts.
How can I retrieve the user name that the was entered in my javascript (ExtJS) based application?

A: Probably, the easiest way is to create a backend service (eg. a servlet in java) that will retrieve the userPrincipal name from the HttpServletRequest and return it in the JSON format. This way from the javascript page you can perform a normal AJAX call to query the service, and retrieve the principal (user name).


text:
Q: Sencha Touch 2 - Text input on android I have sencha touch 2 based app and I have facing issue while tapping and holding. Ideally i should get android context menu of copy paste but i dont.
Please refer to below two links.
http://try.sencha.com/touch/2.0.0/docs/Ext.field.TextArea.1/viewer.html
http://try.sencha.com/touch/2.2.0/docs/Ext.field.TextArea.1/viewer.html
On android first one gives the android (not tested on ios) copy paste menu but second one does not.  I am facing the smae problem in my live app also.
Please suggest if any solution

A: Reply to #bwags:
Ext.define('HCMDoctor.view.PFQuestion', {
extend : 'Ext.form.Panel',
xtype : 'PFQuestion',
id : 'pfView',
config : {
    layout : {
        type : 'auto',
        align : 'stretch'
    },
    flex : 1,
    scrollable : 'vertical',
    items : [{
                xtype : 'container',
                html : 'Click below to choose a different community',
                style : {
                    width : '98%',
                    marginLeft : '5px',
                    marginTop : '10px',
                    fontSize : '10px'

                }
            }, {
                xtype : 'selectfield',
                store : 'CommunityWiseQuestions',
                name : 'pfCommId',
                id : 'pfCommId',
                valueField : 'communityId',
                displayField : 'displayFull',
                centered : false,
                usePicker : false,
                defaultTabletPickerConfig : {
                    height : 400,
                    minHeight : 400,
                    width : 300,
                    minWidth : 300
                },
                style : {
                    marginTop : '10px',
                    marginBottom : '10px',
                    width : '96%',
                    marginLeft : '5px',
                    fontSize : '12px',
                    border : '1px solid #000'
                }
            }, {
                html : '',
                id : 'questionMessageDiv',
                style : {
                    textAlign : 'center',
                    width : '100%'
                }
            }, {
                xtype : 'panel',
                id : 'pfQuestionHolder',
                style : {
                    width : '98%',
                    marginLeft : '5px',
                    marginBottom : '10px'
                },
                tpl : [
                        '{discussionTitle}
{description}',
                        // '
Posted in
                        // {postedInCommunityName}',
                        '']
            }, {
                xtype : 'hiddenfield',
                id : 'pfQuestionId',
                name : 'pfQuestionId'

            }, {
                xtype : 'textareafield',
                id : 'pfAnswer',
                name : 'pfAnswer',
                placeHolder : 'Please write your answer here...',
                style : {
                    marginBottom : '10px',
                    width : '97%',
                    marginLeft : '5px',
                    fontSize : '12px',
                    border : '2px solid #000'
                }
                ,
                listeners : {
                    focus : function(comp, e, eopts) {
                        listeners : {
                            var ost = comp.element.dom.offsetTop;
                            this.getParent().getScrollable().getScroller()
                                    .scrollToEnd(true);
                            return true;
                        }
                    }
                }
            }, {
                xtype : 'button',
                text : 'Submit',
                id : 'submitPFQuestion',
                ui : 'confirm'
            }, {
                xtype : 'spacer',
                height : 10

            }, {
                xtype : 'container',
                html : 'Skip and Show Next Question',
                style : {
                    width : '98%',
                    marginLeft : '5px',
                    textAlign : 'center',
                    marginBottom : '80px'
                }
            }

    ]

},
initialize : function() {
    this.element.on({
                scope : this,
                tap : this.ignorePremiumQuestion,
                delegate : '#ignorePFQuestion'
            });

    return this.callParent();
},
ignorePremiumQuestion : function(obj, newValue, oldValue, eOpts) {
    HCMDoctor.app.getController('Main').showPFQuestionNext();
}

});
This is one of the views I have. I am not getting the default context menu of copy paste on android as well as ios.
Infact the sencha try URL doesnot produce copy paste menus.


text:
Q: The centroid, the first and second Napoleon points and $X(930)$ lie on a circle Can you provide an elementary proof for the claim given below?
Preliminary definitions:
$X(110)=$ focus of Kiepert parabola.
$X(137)=X(110)$ of orthic triangle .
$X(930)=$ anticomplement of $X(137)$ .

Claim. Given any scalene triangle $\triangle ABC$ . The centroid, the first and second Napoleon points and $X(930)$ of triangle $\triangle ABC$ lie on the same circle.

GeoGebra applet that demonstrates this claim can be found here.
Brute-force approach would be to use some CAS like Mathematica. We can calculate coordinates of these four triangle centers in terms of coordinates of triangle vertices and then using two different triples calculate center of the circle in two ways. If both calculations give the same center the proof is complete. But I am looking for more elegant proof of this claim.

A: There is a systematic way to treat this question not just in the above particular case but in that of any four of the around $40,000$ triangle centres documented in the "Encyclopedia of Triangle Centers" using the $p,q$ method.  We suppose that the centers are described by the triangle functions $f_i$ and put $x_i=f_1(b,1,a)+pf_i(1,a,b)$, $y_i=qf_i(1,a,b)$.  Then the four centres are cyclic if and only if the determinant of the $4×4$ matrix with rows $(x_i^2+y_i^2,x_i,y_i,1)$ is identically zero. This can sometimes be done by hand for simple centrrs but it is easy to mechanise it using, say, Mathematica to churn out as many of the $40,000^4$ potential results as desired.  We are using the notation of the above Encyclopedia which is available online.  We are also assuming, as we may, that the functions are homogeneous and sum symmetrically to $1$.  In addition, we regard the above determinant as a function of $a$ and $b$,, using the relationshios $p=\frac 12(b^2÷1-a^2)$ and $q^2=b^2-p^2$.
It is perhaps of interest to point out the following thene. It is a surprise if three arbitrary points in the plane lie on a line  Applied to triangle centres this means that usually three such are not collinear, unless the triangle is isosceles in which case all centres lie on the symmetry axis.  However there are special cases where they are collinear for all triangles--think euler.line.   A similar situation holds for four centres and cyclicity.  There are certain foursomes for which it is valid for any triangle (as in the OP) andthere are, for a given foursome,  certain special triangle shapes for which it holds.  All of these questions can be attacked by the above method.


text:
Q: navigating results in changes of state in react after passing state to Link component I'm making a purchase invoice app in react.
There are two pages in the app now.
One is a page to create new invoice which can be saved to database and exported to excel file. (Invoice.js)
The other is a page of a list of invoices each of them having modify/delete button. (Invoices.js)
When an invoice in the list's modify button is clicked, it links to the creation-page, and the invoice data, which is a state, are passed as parameter.
Without passing invoice data to the creation page, navigating had no problem at all.
However, after I put 'state' property to the Link component, the following error occurs.

Invoices.js:21
Uncaught TypeError: Cannot read properties of undefined (reading 'substring')
at Invoices.js:21:1
at Array.filter ()
at Invoices.js:21:1
at invokePassiveEffectCreate (react-dom.development.js:23487:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at flushPassiveEffectsImpl (react-dom.development.js:23574:1)
at unstable_runWithPriority (scheduler.development.js:468:1)
at runWithPriority$1 (react-dom.development.js:11276:1)

Here are my source codes
// App.js
const App = () => {
  return (
    <BrowserRouter>
      <Container maxWidth="lg">
        <NavBar />
        <Routes>
          <Route path="/" exact element={<Navigate to="/invoice/create" />} />
          <Route path="/invoice/create" element={<Invoice />} />
          <Route path="/invoice/view" element={<Invoices />} />
        </Routes>
      </Container>
    </BrowserRouter>
  );
};

// Invoices.js
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getInvoices } from '../../actions/invoices';
import InvoiceRow from './InvoiceRow';

const Invoices = () => {
  const [month, setMonth] = React.useState(new Date().getMonth() + 1);

  const invoices = useSelector((state) => state.invoices);
  const dispatch = useDispatch();

  const [invoicesCurrent, setInvoicesCurrent] = React.useState([]);

  useEffect(() => {
    dispatch(getInvoices());
  }, [dispatch]);

  useEffect(() => {
    setInvoicesCurrent(invoices.filter((invoice) => Number(invoice.invoiceDate.substring(5, 7)) === month));
  }, [invoices, month, dispatch]);

  ...

  // Link component used: invoice is the one of invoice in invoices state
    <Link to='/invoice/create'
          state={{ ...invoice }}>
      <Button>Modify</Button>
    </Link>

// Invoice.js
const InvoiceComponent = () => {
  const location = useLocation();
  const invoice = location.state;
  const [company, setCompany] = useState(invoice ? invoice.company : '');
  const [employee, setEmployee] = useState(invoice ? invoice.employee : '');
  const [invoiceDate, setInvoiceDate] = useState(invoice ? invoice.invoiceDate : new Date());
  const [orderId, setOrderId] = useState(invoice ? invoice.orderId : '');
  const [companyTel, setCompanyTel] = useState(invoice ? invoice.companyTel : '');
  const [companyFax, setCompanyFax] = useState(invoice ? invoice.companyFax : '');

  const items = useSelector((state) => state.items);
  const dispatch = useDispatch();

  useEffect(() => {
    const last = document.getElementById(`row-${items.length - 1}-0`);
    if (last != null) last.focus();
  }, [items.length]);

  useEffect(() => {
    if (invoice) {
      dispatch(updateItems(invoice.items));
    }
  }, [dispatch, invoice]);

  ...

I must share current app behavior.

*

*When 'Modify' button clicked, creation page is loaded with invoice data.

*Then navigating with 'Go back', 'Go forward', or clicking a link to any of both pages shows the upper error.

*in the useEffect hook in Invoices.js that calls setInvoicesCurrent,
when I console.log(invoices), it is not an array of invoice, rather it is an array of other state(items), which was used in Invoice.js

*Refreshing the page makes all thing reset.

Is there any guideline for managing redux store when navigating?

// console.log(invoices) in useEffect calling setInvoicesCurrent
// Normally opened:   invoices  (6) [{…}, {…}, {…}, {…}, {…},
{…}] 0: {_id: '1', company: 'cmp1', employee: 'e1', invoiceDate:
'2022-01-07T05:14:15.482Z', orderId: '', …} 1: {_id: '2', company:
'cmp2', employee: 'e1', invoiceDate: '2022-01-07T05:14:15.482Z',
orderId: '', …} 2: {_id: '3', company: 'comp3', employee: 'e1',
invoiceDate: '2022-01-07T05:14:15.482Z', orderId: '', …} 3: {_id:
'4', company: 'comp4', employee: 'e1', invoiceDate:
'2022-01-07T05:14:15.482Z', orderId: '', …} 4: {_id: '5', company:
'comp5', employee: 'e1', invoiceDate: '2022-01-07T05:14:15.482Z',
orderId: '', …} 5: {_id: '6', company: 'comp6', employee: 'e1',
invoiceDate: '2022-01-07T13:10:56.380Z', orderId: '', …} length: 6
[[Prototype]]: Array(0)
Each Array has the following data
0:
company: "cmp1"
companyFax: "1222222222" companyTel: "122331232" employee:
"e1" invoiceDate: "2022-01-07T05:14:15.482Z" items:
Array(2)   0: {name: 'item1', spec: 'spec1', qty: 1, price: 10000,
total: 10000, …}   1: {name: 'item2', spec: 'spec2', qty: 20,
price: 1000, total: 20000, …}   length: 2   [[Prototype]]:
Array(0) modifiedOn: "2022-01-07T05:25:14.771Z" orderId:
""
__v: 0
_id: "1"
// console.log(invoices) when ERROR occurs:  invoices  (6)
[Array(2), Array(2), Array(2), Array(2), Array(2), Array(2)]  0:
Array(2)    0: {name: 'item1', spec: 'spec1', qty: 1, price:
10000, total: 10000, …}    1: {name: 'item2', spec: 'spec2', qty:
20, price: 1000, total: 20000, …}    length: 2
[[Prototype]]: Array(0)  1: Array(2)    0: {name: 'item1',
spec: 'spec1', qty: 1, price: 10000, total: 10000, …}    1: {name:
'item2', spec: 'spec2', qty: 20, price: 1000, total: 20000, …}
length: 2    [[Prototype]]: Array(0)  2: (2) [{…}, {…}]
3: (2) [{…}, {…}]  4: (2) [{…}, {…}]  5: (2) [{…}, {…}]
length: 6  [[Prototype]]: Array(0)

A: You should not destructure the array to an object, It creates an object.
use like below
// Invoices.js
<Link to="/invoice/create" state={{ invoice }}>
  <Button>Modify</Button>
</Link>;

// Invoice.js
const { invoice } = location.state;

Note:
const a = [1,2,3];
console.log({...a}); // {0: 1, 1: 2, 2: 3}


text:
Q: How to remove text between two tags? I have such a code:
<input type="text">some dummy text i need to remove! <select>F.i.</select>

I tried to to use jQuery for this. But it doesn't seem to work.
$('div').children('select').prev().remove();

It deletes input instead of that text.
So, how to remove text which is simply between tags?

A: Sometimes it's just simpler to use the native API when working with next nodes.
var select = $("div > select")[0];

select.parentNode.removeChild(select.previousSibling);

You can also make your selector a little more specific if need be.
var select = $("div > input + select")[0];

You could use jQuery to do the remove as well if you did this:
var select = $("div > input + select")[0];
$(select.previousSibling).remove();

which means you could do it in one line:
$($("div > input + select")[0].previousSibling).remove();

but that gets a little hard to read.


text:
Q: alternative for Schwarz inequality I wish to show that
$$\sum_{n=1}^{\infty}|\langle e_n, x\rangle||\langle e_n,y \rangle| \leq \|x\|\|y\|$$
where $\{e_n\}$ is an orthonormal system. But my professor wants me to prove it without using Cauchy-Schwarz (or Hölder) inequality. His sugestion is to use the obvious inequality $(a-b)^2 \geq 0$ for the sequences $a_n = |\langle e_n, x\rangle|$ and $b_n = |\langle e_n, y\rangle| $. It follows that, in general,
$$ \sum_{n=1}^{\infty}\{(a_n - b_n)^2\} \geq 0 \implies \sum_{n=1}^{\infty}\{a_n^2 + b_n^2 - 2a_nb_n\}\geq 0$$
is this right? if so, by Bessel's inequality (i'm allowed to use it lol), $\sum a_n^2 = \sum|\langle e_n, x\rangle|^2 \leq \|x\|$ and $\sum b_n^2 =\sum |\langle e_n, y\rangle|^2 \leq \|y\|^2$. With this, I get to the inequality:
$$ 2\sum_{n=1}^{\infty}|\langle e_n, x\rangle||\langle e_n,y \rangle| \leq  \|x\|^2 + \|y\|^2$$
and... this is not quite what I want. Did i do something wrong or i'm forgetting something? how can I proceeed or restart it? any help will be very appreciated!
thanks in advance.

A: Here is an idea I have using Cauchy product (I don't know if you are allowed to use it) :
Because the series are absolutely convergent then with Cauchy product :
$$\left(\sum_{n=1}^{\infty} a_n b_n \right)^2 = \sum_{n=1}^{\infty}\sum_{k=1}^n (a_k b_{k}) (a_{n-k}b_{n-k}) $$
Moreover with what you have done using Bessel's inequality:
$$ ||x||^2||y||^2 \geq \left(\sum_{n=1}^{\infty} a_n^2 \right)\left(\sum_{n=1}^{\infty} b_n^2 \right)= \sum_{n=1}^{\infty}\sum_{k=1}^n a_k^2b_{n-k}^2$$
and using your professor's suggestion, for all $n \geq k \geq 1$ we have:
$$(a_kb_{n-k})(a_{n-k} b_{k}) \leq \dfrac{1}{2}(a_k^2 b_{n-k}^2+a_{n-k}^2b_k^2)$$
Therefore :
$$
\left(\sum_{n=1}^{\infty} a_n b_n \right)^2 =
\sum_{n=1}^{\infty}\sum_{k=1}^n a_k b_{n-k} a_{n-k}b_{k} \leq \sum_{n=1}^{\infty}\sum_{k=1}^n \dfrac{1}{2}(a_k^2 b_{n-k}^2+a_{n-k}^2b_k^2)
$$
Furthermore :
$$ \sum_{n=1}^{\infty}\sum_{k=1}^n \dfrac{1}{2}(a_k^2 b_{n-k}^2+a_{n-k}^2b_k^2) = \sum_{n=1}^{\infty} \dfrac{1}{2} \left(\sum_{k=1}^n a_k^2 b_{n-k}^2 + \sum_{k=1}^n a_{n-k}^2 b_{k}^2 \right) = \sum_{n=1}^{\infty}\sum_{k=1}^n a_k^2b_{n-k}^2$$
Hence:
$$ \left(\sum_{n=1}^{\infty} a_n b_n \right)^2\leq||x||^2||y||^2$$
Finally:
$$\sum_{n=1}^{\infty} |\langle e_n|x\rangle ||\langle e_n|y \rangle|\leq ||x|| ||y|| $$


text:
Q: Customizer sanitize_callback for input type number How to sanitize input control with "type" => "number". It would better if somebody actually explain in detail sanitize_callback on customizer.

A: Add a setting, specifying the sanitize_callback:
$wp_customize->add_setting(
    'my_input',
    array(
        'default' => '100.00',
        'sanitize_callback' => 'sanitize_float',
    )
);

Add the control:
$wp_customize->add_control(
    'my_input',
    array(
        'label' => 'Please enter a number:',
        'section' => 'my_section',
        'type' => 'number',
        'input_attrs' => array(
            'min' => '0.01', 'step' => '0.01', 'max' => '10000',
          ),
    )
);

Create a function to perform the sanitisation - filter_var should return the sanitised float or false:
function sanitize_float( $input ) {
    return filter_var($input, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
}

This is untested, but should get you started - it could, of course, be adapted to sanitize an integer.
[Adapted from http://themefoundation.com/wordpress-theme-customizer/]


text:
Q: passing multiple variables from HTML to Ajax than posting multiple variables from Ajax to php I have the following form, which has 3 values. Class, Section and School. The school is selected from a drop down list that is brought from database.
(for simplicity I have not included those details here.. ) (in reality my code works)
<form id="form1" name="form1" method="post" action="">
<input type="hidden" name="class" value="someclass">
<input type="hidden" name="section" value="somesection">
<select name="school" id="school">
<option> "school 1"  </option>
<option> "school 2"  </option>
<option> "school 3"  </option>
<option> "school 4"  </option>
<option> "school 5"  </option>
</select>
</form>

I am doing this for the Ajax, and for only 1 variable (the item from list) was working fine, however after adding the class and the section values, I was not able to get those 3 into the Ajax, so that I can post them into the PHP. (syntax might be wrong as this is just copy paste some of the portion of the code.)
$("#school").change(function ()
{
 resetValues();

    var school = { school:$(this).attr('value') };
    var class= { class:$(this).attr('value')    };
    var section= { section:$(this).attr('value')};

jQuery.ajax({
                  url: 'getTheData.php',
                  type: "POST",
                  dataType: "xml",
                  data:school&class&section,
                  async: false,
                  success: schoolOnSuccess
            });

And naturally I am using _POST to get the values on the getTheData.php the traditional way.
Where am I going wrong ?

A: Instead of using like this, you can serialize the form elements and send.
$("#school").change(function ()
{
   resetValues();
   var data = $("#formid").serialize();
   jQuery.ajax({
              url: 'getTheData.php',
              type: "POST",
              dataType: "xml",
              data:data,
              async: false,
              success: schoolOnSuccess
   });
});

You can access the values in php function by using the name of form elements.
The advantage of this method is, you don't have to change your script when you add or modify any form element.

A: You can try this:

    $('#school').change(function(){
        $.get('getTheData.php', $('#form1').serialize(),
        function(){
           alert('Success!');
        },function(){
           alert('Unsuccess!');
        });
    });

and request will send with data on url.

A: try this, make your object-data
data:{
        'post-field-name' : 'post-field-value'
}

so your ajax script will become :
jQuery.ajax({
    url: 'getTheData.php',
    type: "POST",
    dataType: "xml",
    data:{
        'school' : school,
        'class' : class,
        'section' : section
    }
    async: false,
    success: schoolOnSuccess
});


text:
Q: why am i getting a java.util.ConcurrentModificationException in the advanced for loop? Unlike other exception scenarios I've seen, the exception I keep getting happens at the for loop I commented below with //where it goes wrong//. And in my implementation, the List partialR doesn't change while I iterate it, so I am really confused.
public class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        result.add(new ArrayList<Integer>());
        return permute(nums, 0, result);
    }

    public List<List<Integer>> permute(int[] nums, int i, List<List<Integer>> result){
        if (i == nums.length){
            return result;
        }
        int num = nums[i];
        List<List<Integer>> partialR = permute(nums, i+1, result);
        System.out.println("partialR"+partialR);
        for (List<Integer> t : partialR){***//where it goes wrong//***
            System.out.println("t"+t);
            for (int j=0; j <= t.size(); j++){
                System.out.println("j="+j);
                List<Integer> subs = insert(t,num,j);
                result.add(subs);
                System.out.println("result"+result);
            }
        }
        System.out.println("result");
        return result;
    }
    public List<Integer> insert(List<Integer> t, int num, int j){
        List<Integer> temp = new ArrayList<>();
        if (j == 0){
            temp.add(num);
            temp.addAll(t);
            System.out.println("temp"+temp);
            return temp;
        }else if(j == t.size()){
            temp.addAll(t);
            temp.add(num);
            return temp;
        }
        List<Integer> temp1 = new ArrayList<Integer> (t.subList(j,t.size()-1));
        List<Integer> temp2 = new ArrayList<Integer> (t.subList(0,j-1));
        temp.addAll(temp1);
        temp.add(num);
        temp.addAll(temp2);
        return temp;
    }
}

A: You pass result to permute, and it returns result.
So when you do this:

List<List<Integer>> partialR = permute(nums, i+1, result);

Now partialR points to result too.
And then when you iterate over it with for (List<Integer> t : partialR),
you modify result when you do result.add(subs).
So in effect, you're modifying result while you're iterating over it,
which is not allowed by the fail-fast behavior of iterators in Java.
(You can read more about this in the javadoc of ConcurrentModificationException.)
You could fix this by creating a new ArrayList here:
List<List<Integer>> partialR = new ArrayList<>(permute(nums, i + 1, result));

There are some other mistakes too, unrelated to the concurrent modification.
In insert, the range of values to create temp1 and temp2 are incorrect.
Corrected and simplified, you can write:
List<Integer> temp1 = t.subList(j, t.size());
List<Integer> temp2 = t.subList(0, j);


text:
Q: Create pre filter layer in DbSet I want to protect my entities using a Field called Deleted to don't allow client really delete any entity. If he tries delete, the only thing is that entity.Deleted = true;
The problem is that everywhere I don't want to include deleted Entities I'll need to use
db.Entities.Where(e => e.Deleted == false).WhateverMethod();
I know I can use a method like this inside my Controller
private IQueryable<Entity> GetNotDeletedEntity() {
        return db.Entities.Where(e => e.Deleted == false);
}

And change every db.Entities.WhateverMethod() for GetNotDeletedEntity().WhateverMethod(), but I seems weird for me.
One note is that GetNotDeletedEntity() returns IQueryable, and db.Entities returns DbSet. This incongruency may be a problem in the future.
I think there's a way to extend DbSet to work like this
db.Entities // include all entities
db.NotDeletedEntities // include only entities e.Deleted == false
Any advice about how to DRY .Where(e => e.Deleted == false) would be great.

A: Seems like this guy was trying to accomplish something very similar. Take a look at Jon Skeet's explanation here: extension for DbSet


text:
Q: Proof regarding function growth Can someone please help me with this proof:
Let $f, g : \mathbb N → \mathbb Z^{+}.$ We say that $g$ is eventually dominated by $f$ if and only if there exists $n_{0} \in \mathbb Z^{+}$
such that every natural number $n$ greater than or equal to $n_{0}$ satisfies $g(n) ≤ f(n).$ We can express this in a predicate $P(f,g)$: "$g$ is eventually dominated by $f$" where $f, g : \mathbb N → \mathbb Z^{+}$ as $$P(f, g): \exists n_{0} \in \mathbb Z^{+}, \forall n \in \mathbb N, n ≥ n_{0} \implies g(n) ≤ f(n) $$
(a) Let $f(n) = n^2$ and $g(n) = n + 165$. Prove that $g$ is eventually dominated by $f$.
Now I know that the order of quantifiers is important for this part and that we start by introducing $n_{0}$ by giving it a concrete value. I have no idea where to go from there.
(b) Prove the following statement, which is a generalization of the previous part: $ \forall a, b \in \mathbb Z^{+}, g(n) = an + b $ is eventually dominated by $ f(n) = n^2$.
I'm assuming here we need to pick a suitable $n_{0}$ that other variables can easily depend on.

A: You just need to find a $n_0 \in \mathbb N$ such that $f(n) \ge g(n), \forall n \ge n_0$................................................1)
In part b), let us find $n_0$. Let us assume such an $n_0$ satisfying 1) does NOT exist. Then $\forall n \in \mathbb N, f(n)\lt g(n)$
or, $n^2 < an + b$............................2)
or, $n^2 - an - b < 0$ [ since for 2) to be correct the RHS of the inequality must be positive, we can switch it to the other side without changing the inequality sign].
or, $n(n-a) - b < 0$ .............................3)
Now, Note that $(a+b) \ge 1$ [since $g(1) \in \mathbb Z^+$]
choose n = (a+b).
Then , from 3):
$(a+b).b - b<0$ , or $b(a+b - 1)<0$ . Clearly, the last one is impossible since both the factors are positive.Contradiction.
Hence, there always exists an $n_0 \in \mathbb N$ such that $\forall n \ge n_0, f(n) \ge g(n)$


text:
Q: Docusign integrator key and username relationship I'm using a legacy service integration with DocuSign (through custom X-DocuSign-Authentication header attribute) and I'm a bit confused with the relationship between username and Integrator-Key.
For example, for test purposes I've used the following scenario:

*

*I've send a request to sign a document and obtained the envelopeId using Integrator-Key-1

*After I'm sending a request to get the recipient view url (for embedded signing) using the same credentials and provided envelopeId, but another Integrator-Key-2
I was expecting that the request should fail, but it works fine and the document is displayed for signature.
I'm getting the same result even in case the provided integrator key belongs to different user.
So, I'm really confused what the integrator-key is used for.
Thank you.

A: The integrator key identifies the integration. Once approved for use within a specific DocuSign environment (e.g., demo, prod), an integrator key can be used to issue API requests for data affiliated with any Account and/or User within that environment (provided, of course, that each API request includes proper info to authenticate the User who's making the API request).
So, for example, if you're an ISV who's building an integration that will be used by multiple customers across multiple DocuSign Accounts, you can use the same integrator key for all API calls that your integration issues, regardless of the Account and/or User affiliated with any particular request.

A: Integrator key (also known as a client id) is a unique identifier that authenticates your account with the DocuSign API. If you have two Integrator Keys for the same environment then you will be able to call DS APIs with any Integrator Key. But Integrator Key has more value for DocuSign, for instance if you have created an application with DS APIs with IK 1 and you reviewed this IK to be used in the PROD environment. After you have passed the review process, IK will be promoted to PROD environment enabling you to call DS APIs in Live/Prod environment within API rules and limits. Now in future you did any code changes on your end and your newly deployed code was not developed as per DS API Rules and Limits then DS can blacklist your IK to not to be used in PROD, which will impact your application to be stopped in the PROD directly.


text:
Q: variance of log of ratio of chi-square variables Let X be a chi-square variable with two degrees of freedom.
Let A and B be to arbitrary constants, with $A>B>0$.
I need the variance of
$Y=\log(1+AX)-\log(1+BX).$
The mean is, maybe not simple, but doable, since it is the ergodic channel capacity of a Reyleigh fading channel, well known in communication theory, and is given by a sum of Exponential integrals, unless I recall incorrectly.


text:
Q: jQuery selector first td of each row I have this stuff:

    nonono
    	foobar

    nonono2
    	foobar2

    nonono3
    	foobar2

I have tried with $('td:first') with no luck;
Expected return: nonono	, nonon2	 and nonon3
Thanks in advance!

A: You should use :first-child instead of :first:
Sounds like you're wanting to iterate through them. You can do this using .each().
Example:
$('td:first-child').each(function() {
    console.log($(this).text());
});

Result:
nonono
nonono2
nonono3

Alernatively if you're not wanting to iterate:
$('td:first-child').css('background', '#000');

JSFiddle demo.

A: var tablefirstcolumn=$("tr").find("td:first")
alert(tablefirstcolumn+"of Each row")

A: Use:
$("tr").find("td:first");

js fiddle - this example has .text() on the end to show that it is returning the elements.
Alternatively, you can use:
$("td:first-child");

.find() - jQuery API Documentation

A: try this selector -
$("tr").find("td:first")

Demo --> http://jsfiddle.net/66HbV/
Or
$("tr td:first-child")

Demo --> http://jsfiddle.net/66HbV/1/
	foobar	 should be foobar

A: You can do it like this

$(function(){
  $("tr").find("td:eq(0)").css("color","red");
})

    col_1
    col_2

    col_1
    col_2

    col_1
    col_2

    col_1
    col_2

A: try
var children = null;
$('tr').each(function(){
    var td = $(this).children('td:first');
    if(children == null)
        children = td;
    else
        children.add(td);
});

// children should now hold all the first td elements

A: $('td:first-child') will return a collection of the elements that you want.
var text = $('td:first-child').map(function() {
  return $(this).html();
}).get();


text:
Q: Реализация условного запроса к БД Добрый день сообщество. Прошу помощи в следующем:
На сайте реализовано переключение вкладок на JS. При нажатии на каждую вкладку на экран выводится результат запроса к БД.  Собственно код:

$resultat1 = mysql_query("SELECT * FROM main_table WHERE категория='cat1'",$connection);

Тобишь каждый таб показывает выборку лишь по одной, соответствующей ей, категории

$(document).ready(function() {
  $('.tabs_menu a').click(function(e) {
   e.preventDefault();
   $('.tabs_menu .active').removeClass('active');
   $(this).addClass('active');
   var tab = $(this).attr('href');
   $('.tab').not(tab).css({
    'display': 'none'
   });
   $(tab).fadeIn(400);
  });
 });

Также реализован поиск, который делает запрос к БД и выводит материалы по всем категориям.
Можно ли реализовать поиск с учетом отслеживания активного в данный момент таба? Условно говоря, если выбрана третья категория (таб), то и поиск будет идти лишь по третьей. Понимаю что следует сделать невидимый input type="radio" для каждого таба, и в запросе к бд проверять его, но как это реализовать я представления не имею.
Заранее спасибо

A: В коментариях @Mike дал отличный совет.
Создайте скрытое поле: <input type="hidden" id="categoryType" name="categoryType">, и при переходе на новый таб меняйте в нем значение, для этого нужно добавить одну строку в ваш js:

$(document).ready(function() {
  $('.tabs_menu a').click(function(e) {
   e.preventDefault();
   $('.tabs_menu .active').removeClass('active');
   $(this).addClass('active');
   var tab = $(this).attr('href');

                        $('#categoryType").val(tab); // Добавленная строка

   $('.tab').not(tab).css({
    'display': 'none'
   });
   $(tab).fadeIn(400);
  });
 });

И тогда у вас на сервере будет доступна информация о активном табе, $_REQUEST['categoryType']. Этот вариант подходит если у вас поиск работает без Ajax. В случае с Ajax все намного проще.
$.ajax({
   ...
   data: {
       ...
       categoryType: $('.active').attr('href'),
       ...
   },
   ...
});

И на сервера информация о активном табе будет лежать там же где и в первом случае $_REQUEST['categoryType'].


text:
Q: catalog_category_product_index_store1 table having wrong data in magento2.4.2 I have checked and found in my site catalog_category_product_index_store1 having category_id associated with other product ids. that's why it's showing on the category listing page but this product is not related to this category.
As I have tried to edit products and assign a different category. but still not fixed.
Can anyone explain how to fix this issue?

A: Magento 2 is using repositories and these repositories found their datas in the flat tables. As mentionned by Piyush in comment, these flat tables are only updated when you reindex. Basically it will make your flat table identical to what you have in your back office.If the flat data has thr wrong data the only way is that the back office config isn't the one you think it is.


text:
Q: How precise is websphere's session expiration? We wrote some jquery and java code to support passing a cookie with the expected session expiration time to the client, which then prompts the user two minutes before to give them the chance to extend their session.  If they fail to do so in time, they get forwarded on their next button click to a landing page.
Works great...most of the time.  Every so often, a tester trying to test this will wait 4 minutes after the prompt comes up, click a button only to find that their session is still alive despite waiting 2 full extra minutes longer than they should have had to for the session to die.
Is the spec just not that precise with when sessions expire?  Should we sort of blow this off as not a big deal?  we're using ibm's websphere as our app server.

A: I assume you set the session expiration time to two minutes on the server. That is, not the cookie expiration time.
The session should expired after two minutes. However the session can come back alive (but empty) after expired if application (click button) called getSession(true) instead of getSession(false).
If this isn't the case, can you enable the session trace : com.ibm.ws.session.*=all

A: WebSphere has a setting called HttpSessionReaperPollInterval that controls this behavior.

Use this property to specify, in seconds, a wake-up interval for the
  process that removes invalid sessions. The value specified for this
  property overrides the default installation value, which is between 30
  and 360 seconds, and ensures that the reaper process runs at a
  specific interval.

https://www.ibm.com/support/knowledgecenter/SSEQTP_8.5.5/com.ibm.websphere.base.doc/ae/rprs_custom_properties.html
Although the property can be adjusted, it may still not make sense to change the default value in your scenario.


text:
Q: Electron removes top bar when packed I'm building an Electron app, i have developed everything and it works fine, but when i use electron-packager . to build my application to an exe the top menú dissapears.
I initialize it using remote, because i do that in the renderization time;
const {electron, Menu} = require("electron").remote;

Then, i build the menu from a template;
  var m = new Menu();
  m = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(m);

It works fine when i run the app with electron . but when i pack it the top menu dissapears.
Two images to show what i am saying;

Thanks.


text:
Q: Kivy/KivyMD - Button does not react I have tried to write code using Kivy/KivyMD libraries after a break and I noted that I cannot make buttons to work. There is no reaction even when I use the old code I know was working fine.
There is no reaction after I click a button and I have this issue with both Kivy and KivyMD buttons.
Here is a sample code:
from kivy.app import App
from kivy.uix.button import Button

class ButtonApp(App):

    def build(self):

        btn = Button(text="Push Me !",
                     font_size="20sp",
                     background_color=(1, 1, 1, 1),
                     color=(1, 1, 1, 1),
                     size=(32, 32),
                     size_hint=(.2, .2),
                     pos=(300, 250))

        btn.bind(on_press=self.callback)
        return btn

    def callback(self, event):
        print("button pressed")

root = ButtonApp()
root.run()

I took the above sample code from this webpage: https://www.geeksforgeeks.org/python-working-with-buttons-in-kivy/. As I wrote this is true for both Kivy and KivyMD and there is simply no reaction once I press the button.
I'm using Pycharm version 203.7148.72, Kivy version 2.0.0, KivyMD version 0.104.1.
Thank you in advance for any assistance.

A: Posting as an answer for more visibility since the issue was solved in comments.
Make sure that kivy input sources are correctly configured for your device, in the config.ini file (<HOME_DIRECTORY>/.kivy/config.ini see https://kivy.org/doc/stable/guide/config.html?highlight=config), is an [input] section.
On desktop, you usually want at least a mouse to be configured in this section, the most simple way to achieve that being a mouse=mouse line, with optionaly the multitouch_on_demand option (i.e mouse=mouse,multitouch_on_demand).


text:
Q: How PHAR signature prevents tampering with files? I am wondering if it is possible to reuse a signature of a PHAR file. As it is described in the manual, each file has a manifest, which contains a lot of things which can be faked, and 4 bytes of CRC32 checksum, which is a poor choice (md5 or sha1 would be much secure), but can be faked harder than other stuff. I have doubts about the validity of checksum used by creating the signature for verifying. I mean it is slow to create a checksum by every inclusion of the phar file, but adding a manifest cache, which contains the checksum is not an option, if you want to stay secure (because it is relatively easy to modify this cache, if it is stored in the phar file). Do you know how phar packages solve this in a fast way?

A: The documentation is rather hard to follow, and in some places out of date, but the verification seems to be as follows:

*

*all files, even those in Tar or Zip format contain a manifest with a CRC check for basic self-validation; this is not tamper-proof, but will detect things like incomplete downloads

*files in the PHAR format can also contain a signature in one of several formats chosen by the creator

*as of PHAR 2.0 (PHP version unclear), the signature can also use an OpenSSL public-private key pair

*this signature is calculated on the whole contents of the archive, independent of the manifest, so can be trusted to detect tampering if it, or the public key, is distributed over a trusted channel

Your question talks of the speed of the signing and verifying process, and this is a key part of your suspicion that an insecure algorithm might be in play. Wikipedia summarises the performance of SHA-256/512 as 200 to 300 MiB/second on an inexpensive 64-bit CPU. Since a PHAR archive is unlikely to be as large as 200MiB, and since signature verification is performed on-demand, not on every execution (at least, I think so), the fraction of a second to hash the whole file is unlikely to be an issue. (Creation of the signature can also be postponed until all files are added, so again has no requirement for higher speed.)


text:
Q: Получить график с Google Analtytics Помогите, пожалуйста, мне нужно получить график данных с Google Analytics (GA). Дело в том, что нужно получить данные по определенным событиям, которые созданы были в GA, а не общие данные. Кажется это возможно сделать при помощи одного JavaScript и воспользоваться Google Charts для отображения.
Инет перерыл.. API гугла тоже.. %))
Спасибо
A: Подскажу вам некоторые ссылки для изучения:

*

*Core Reporting API Client Libraries

*Google APIs Console

*Google Analytics Core Reporting API
Надеюсь, что вы соберете это всё воедино.


text:
Q: Usage of Pipes in Ruby Loops So, maybe I'm over-complicating something that isn't that hard, but here goes.
In Ruby, there's a method of looping called .each.  I think that this is very cool--but what I'm finding less cool is the amount of stuff written about the pipe that comes after it (or any other do-type loop in Ruby, it would seem).  Sometimes there is a single thing in the pipe:
basket.each do |fruit|
    puts "This is a #{fruit}.\n"
end

But sometimes, there are two things in this pipe, like so:
contacts.each do |name, profession|
    puts "#{name} is a #{profession}.\n"
end

So what I'm wondering now, is it possible to have more than two items in that pipe?  Like if I have a huge, big, and ugly multi-dim array?
What if I add things to my pipe and they're not there?  Will it give the value in the pipe nil?  Or will it throw an error?
Again, sorry if this is obvious to long-time Rubyists, but I came from the land of strictly typed variables, and I'm now leaving PHP land, too. :)
EDIT
So what if I have something like this:
categories = [["Bathroom", "Bathroom Fixtures", "Plumbing"],
                      ["Ceiling Fixtures", "Chandeliers", "Flush Mounts", "Mini Chandeliers", "Semi-Flush Mounts", "Pendants", "Track Lighting", "Mini Pendants", "Directional", "Island/Pool Table", "Recessed Lighting"],
                      ["Outdoor", "Exterior", "Landscape Lighting"],
                      ["Fans", "Fans", "Fan Accessories"],
                      ["Lamps", "Lamps", "Shades"],
                      ["Wall Fixtures", "Sconces", "Foyer/Hall Lanterns"],
                      ["Specialty", "Undercabinet", "Light Bulbs", "Lighting Controls", "Glass", "Specialty Items", "Utility"],
                      ["Home Decor", "Decor/Home Accents", "Furniture"]]

Can I loop through it like this?
categories.each do |category, subcats|
    puts "The main category is #{category} and the sub categories are: "
    subcats.each do |subcat|
        puts "#{subcat}, "
    end
end

A: Lets start with a break down of the each method.
a = [1,2,3,4,5]

a.each do |num|
  puts num
end

# 1
# 2
# 3
# 4
# 5

The do ... end portion is called a block
This block accepts one parameter (an element in the array)
The way you pass parameters to a block is with |'s
If you supply more than one argument to the block:
a.each do |num, x|
  puts num
  puts x
end

# 1
#
# 2
#
# 3
#
# 4
#
# 5
#

x is nil for each iteration.
Lets write a method of our own that uses blocks so you can see how they work.
def my_each(a=[])
  a.each do |x|
    yield x if block_given?
  end
end

my_each(a) do |num|
  puts num
end

Here yield x is saying, execute the supplied block and pass x to it.
If you pass another parameter to your block, it is nil. Why?
Our implementation of my_each doesn't know anything about a second parameter so it does not yield anything so it remains nil.

A: When you have a simple array, the following things happen:
arr = [1,2,3,4]

arr.each do |x|
  p x
end
1
2
3
4
=> [1,2,3,4]

arr.each do |x,y|
  p x
  p y
end
1
nil
2
nil
3
nil
4
nil
=> [1,2,3,4]

so if ruby doesn't know what to put into the block argument, it simply sets it to nil. Now consider a nested array:
arr = [[1,2],[3,4],[5,6]]

arr.each do |x|
  p x
end
[1, 2]
[3, 4]
[5, 6]
=> [[1,2],[3,4],[5,6]]

arr.each do |x,y|
  p x
  p y
end
1
2
3
4
5
6
=> [[1,2],[3,4],[5,6]]

In this case, ruby assumes that you want to assign the two elements of the inner arrays to the block variables x and y. The same thing applies to hashes, where Ruby assigns the key and value to x and y:
hash = {1 => 2, 3 => 4, 5 => 6}

hash.each do |x,y|
  p x
  p y
end
1
2
3
4
5
6
=> {1=>2,3=>4,5=>6}

When you don't have enough elements in the nested arrays, the block variables are assigned nil, indeed. When there are too many of them, they are simply discarded:
arr = [[1,2,3],[4,5],[6]]

arr.each do |x,y|
  p x
  p y
end
1
2
4
5
6
nil
=> [[1,2,3],[4,5],[6]]

pretty straightforward!
EDIT:
As for your edited question: no, you cannot apply this 1:1 to Ruby code, you would have to manually apply the splat operator (*) to subcats. This way, ruby assigns all remaining elements to the 'splatted' block variable:
categories.each do |category,*subcats|
    puts "The main category is #{category} and the sub categories are: "
    subcats.each do |subcat|
        puts "#{subcat}, "
    end
end

although i would generate a comma-separated list of subcategories like this:
categories.each do |category,*subcats|
    puts "The main category is #{category} and the sub categories are: "
    puts subcats.join(', ')
end

EDIT 2:
Oh, and you would not handle a huge ugly evil multidimensional array by defining a lot of block parameters for its elements. You probably would iterate through it using nested loops as in almost every other language, if only because you never know how many elements it contains.

A: The pipes you are talking about is a parameter list of a block "variable". Actually that is some kind of a function pointer, and the pipes marks the parameter list.
Check the description of array.each.
This is not magic, the number of parameters is defined in the block, you can't add more than that, if you do, they won't get a value. The reason is for "sometime" there can be more than one, is that it's probably a hash.each, which has two parameters, a key and a value.
You can create your own functions with block parameters, read this.
For your iteration problem, you can use a hash, or you can write your own iterator.

A: Multiple Arguments to a Block
Array#each iterates over an array object, and passes either a single object into the block or returns an enumerator. You can redefine this behavior, but #each is the wrong method if you want multiple values at a time; see Enumerator#each_slice for an alternative.
Data Structures
Your problem would be easier to solve with the right data structure. Instead of an array, you should consider using a hash. For example:
categories =
  {"Bathroom"=>["Bathroom Fixtures", "Plumbing"],
   "Ceiling Fixtures"=>["Chandeliers", "Flush Mounts", "Mini Chandeliers"]}

categories.each do |key, value|
  puts "#{key}:"
  value.each { |v| puts "\t%s" % v }
end

This returns:
Bathroom:
    Bathroom Fixtures
    Plumbing
Ceiling Fixtures:
    Chandeliers
    Flush Mounts
    Mini Chandeliers


text:
Q: Calculus integration problem: $\int \sin^5 (x) \cos^2 (x)\,dx$ What's the integration of $$\int \sin^5 (x) \cos^2 (x)\,dx?$$

A: Hint: Write
$$
\sin^5(x)\cos^2(x)=(\sin^2(x))^2\cos^2(x)\sin(x).
$$
Now use $\cos^2(x)+\sin^2(x)=1$ and do the appropriate change of variable.
This is the general method to integrate functions of the type
$$
\cos^n(x)\sin^m(x)
$$
when one of the integers $n,m$ is odd.

A: $$ \int \sin^5 (x) \cos^2(x) dx $$
$$= \int(\sin^2(x))^2 \cos^2(x) \sin(x) dx$$
$$=-\int(1 - \cos^2(x))^2 cos^2(x) (-sin(x) dx) $$
Let $u = \cos(x)$
$\implies du = -\sin(x) dx$
$$= -\int(1 - u^2)² u² (du)$$
$$= -\int(1 - 2u^2 + u^4) u^2 du $$
$$= -\int(u^2 - 2u^4+ u^6) du$$
$$= -\left(\frac{u^3}{3} - \frac{2u^5}{5} + \frac{u^7}{7}\right) + C$$
$$= -u^3\left(\frac{1}{3} - \frac{2u^2}{5} +\frac{ u^4}{7}\right) + C $$
$$= -\cos^3(x) \left(\frac{1}{3} - \frac{2\cos^2(x)}{5} + \frac{\cos^4(x)}{7}\right) + C $$
$$= -\cos^3(x)\frac{15\cos^4(x) - 42\cos^2(x) + 35}{105} + C $$

A: Using trig identities, you can show that:
$$\sin ^5(x) \cos ^2(x)=\frac{5 \sin (x)}{64}+\frac{1}{64} \sin (3
   x)-\frac{3}{64} \sin (5 x)+\frac{1}{64} \sin (7 x)$$
To do this, first use the "Power-reduction formulas" to reduce to get:
$$\sin^5(x)=\frac{10 \sin x - 5 \sin 3 x+ \sin 5 x}{16}$$
$$\cos^2(x)=\frac{1 + \cos (2 x)}{2}$$
And then use:
$$\cos (2 x) \sin (nx) = {{\sin((n+2)x) - \sin((n-2)x)} \over 2}$$


text:
Q: Ring of Witt vectors and Fontaine's deRham period ring The construction I am interested in is the following:
Let $V$ be a complete discrete valuation ring of mixed characteristic $(0,p)$ with algebraically closed residue field $k$. Let $K=Frac(V)$ and fix an algebraic closure $\overline{K}$ of $K$, and $\overline{V}$ the integral closure of $V$ in $\overline{K}$. Define $R_{\overline{V}}$ to be the perfection $\lim_{\leftarrow \, Frob} \overline{V}/p\overline{V}$; take the Witt ring $W(R_{\overline{V}})$ one gets a surjective homomorphism $$\theta: W(R_{\overline{V}}) \rightarrow \widehat{\overline{V}}$$ by $\theta([x])= \lim_{\rightarrow \infty} \widetilde{x_m}^{p^m}$ where $x=(x_n)_{n\in \mathbb{N}} \in R_{\overline{V}}$ $\widetilde{x_m}$ a Lifting of $\overline{V}/p\overline{V}$ to $\overline{V}$ and $[\cdot]$ the Teichmüller representative. As is well known the kernel of $\theta$ is generated by a single element $\xi$. From here I am interested in understanding $A_N(\overline{V}):=   W(R_{\overline{V}})/\xi^N  W(R_{\overline{V}})$.
Now to my question: I want to see what comes out of this construction when I put in $W(k)=V$. At first I thought that it was quite simple because the projection on the first factor $R_{W(k)} \overset{\sim}{\rightarrow} k$ is an isomorphism which yields the isomoprhism $W(R_{W(k)}) \overset{\sim}{\rightarrow} W(k)$ but this does not account for the integral closure being taken in $\overline{K}=\overline{Frac(W(k))}$. So my question boils down to: what is the integral closure $\overline{W(k)}$ of $W(k)$ in $\overline{K}$ and how does above construction work for $\overline{W(k)}$?


text:
Q: Empty C++11 initialiser list results in container with one default constructed object The code below uses an empty C+11 style initialiser. When run the result is a std::vector containing one item, which appears to have been default constructed.
This is clearly an artificial case, and there are better ways of constructing an empty vector.  Nonetheles, the behaviour is counter-intuitive.  Is this a compiler/c++ runtime library bug?
I suspect one of std::vector's other constructors is actually getting called here.
#include <iostream>
#include <memory>
#include <vector>

int main(int argc, const char * argv[])
{
    typedef std::vector<std::shared_ptr<int>> Container;

    Container c{{}};

    std::cout << "Vector size is: " << c.size() << std::endl;

    for (auto item: c)
    {
        std::cout << "Item: " << item.get() << std::endl;
    }
}

Output:
Vector size is: 1
Item: 0x0
Program ended with exit code: 0

Compiler:
$ clang  --version
Apple clang version 3.0 (tags/Apple/clang-211.12) (based on LLVM 3.0svn)
Target: x86_64-apple-darwin12.4.0

A: Container c; is an empty container or Container c{};
Container c{{}}; constructs the container with a default-constructed std::shared_ptr<int>
Container c{{},{}}; constructs 2 shared_ptrs

A: The initializer list is not empty instead of Container c{{}}; use Container c({});  // to pass an initializer list. Container c{} will be default initialized.


text:
Q: Using rvest with drake: external pointer is not valid error When I first run the code below, everything is ok. But when I change something in html_file %>%... comand, for example commenting tolower(), I get the following error:
Error: target title failed.
diagnose(title)error$message:
  external pointer is not valid
diagnose(title)error$calls:
   1. └─html_file %>% html_nodes("h2") %>% html_text()

Code:
library(rvest)
library(drake)

some_string <- '

A

X

'

html_file <- read_html(some_string)
title <- html_file %>%
  html_nodes("h2") %>%
  html_text()

plan <- drake_plan(
  html_file = read_html(some_string),
  title = html_file %>%
    html_nodes("h2") %>%
    html_text() %>%
    tolower()
)

make(plan)

I found two possible solutions but I'm not enthusiastic about them.
 1. Join both steps in drake_plan into one.
 2. Use xml2::write_html() and xml2::read_html() as suggested here.
Is there a better way to solve it?
P.S. Issue was already discussed here, Rstudio forum, and on github.

A: By default, drake saves targets as RDS files (other options here). So https://github.com/tidyverse/rvest/issues/181#issuecomment-395064636, which you brought up, is exactly the problem. I like (1) because text is compatible with RDS. Speaking broadly, it is up to the user to choose good targets compatible with drake's data storage system. See https://books.ropensci.org/drake/plans.html#how-to-choose-good-targets for a discussion and links to similar issues. But you want to go with (2), you could return the file path to your HTML file from within a dynamic file.


text:
Q: Модель не проходит проверку is_valid() У меня есть модель бланка. Она должна создаваться в отдельной форме, но по какой-то причине не проходит проверку is_valid()   - (Если убрать, выдает ValueError). Есть предположение, что ошибка выдается из-за того, что не все поля заполняются (в моделе их 12, а в форме я заполняю 9), но остальные поля мне не нужны для заполнения, и они стоят с параметрами default="..." . Помогите!
# models.py
from django.db import models
from datetime import date
from django.contrib.auth.models import User

class Blank(models.Model):
    first_name = models.CharField("Имя", max_length=50)
    second_name = models.CharField("Фамилия", max_length=50)
    third_name = models.CharField("Отчество (если есть)", max_length=50, default='')
    email_addr = models.EmailField("email-адрес", unique=True)
    phone_num = models.CharField("Номер телефона", max_length=15, default="", unique=True)
    passport_id = models.CharField("Серия и номер паспорта", max_length=11, unique=True)
    age = models.DateField("Дата рождения", default=date(2002, 1, 1))
    registration_address = models.CharField("Адрес регистрации", max_length=100)
    photo = models.ImageField("Фото", default=None, upload_to='photos/')
    is_blank_valid = models.BooleanField("Заявление составлено правильно?", default=False)
    is_passport_reissue = models.BooleanField("Паспорт перевыпущен?", default=False)
    blank_date = models.DateField("дата оформления", default=date.today)

    def __str__(self):
        return str(self.second_name + ' ' + self.first_name + ' ' + self.third_name)

    class Meta:
        verbose_name = "заявление"
        verbose_name_plural = "заявления"

# forms.py
from django.forms import ModelForm
from .models import Blank

class BlankForm(ModelForm):
    class Meta:
        model = Blank
        fields = ["second_name", "first_name", "third_name", "email_addr",
                  "phone_num", "passport_id", "age",
                  "registration_address", "blank_date", "photo"]

# view.py
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import redirect, render

from .forms import BlankForm

...

def blankCreate(request):
    if request.method == 'POST':
        blankform = BlankForm(request.POST)
        if blankform.is_valid():
            blankform.save()
            return redirect('dashboardView')
    else:
        blankform = BlankForm()
    return render(request, 'blankCreate.html', {'form': blankform})

# blankCreate.html
{% extends 'index.html' %}

{% block context %}

Blank create system

    <form method="POST">
        {% csrf_token %}

Фамилия: {{form.second_name}}

Имя: {{form.first_name}}

Отчество: {{form.third_name}}

Эл. почта: {{form.email_addr}}

Номер телефона: {{form.phone_num}}

Серия и номер паспорта: {{form.passport_id}}

Возраст: {{form.age}}

Адрес регистрации: {{form.registration_address}}

Фото: {{form.photo}}

        <button>Create new blank</button>
    </form>
{% endblock %}


text:
Q: How do I write a sed or a awk command that finds a pattern and deletes it in a text file I have the following lines in a text file:
docker pull ${DOCKER_REGISTRY}/{REPOSITORY}/{IMAGE_NAME}:FOO.${TAG_NAME}
docker pull ${DOCKER_REGISTRY}/{REPOSITORY}/{IMAGE_NAME}:BAR.${TAG_NAME}
docker pull ${DOCKER_REGISTRY}/{REPOSITORY}/{IMAGE_NAME}:BAZ.${TAG_NAME}

I want to write a sed or awk command that finds all occurrences of FOO., BAR. and BAZ. in the above lines in a file and deletes these occurrences so that the result looks like this in the end:
docker pull ${DOCKER_REGISTRY}/{REPOSITORY}/{IMAGE_NAME}:${TAG_NAME}
docker pull ${DOCKER_REGISTRY}/{REPOSITORY}/{IMAGE_NAME}:${TAG_NAME}
docker pull ${DOCKER_REGISTRY}/{REPOSITORY}/{IMAGE_NAME}:${TAG_NAME}

A: Sed one:
sed 's/\b\(FOO\|BAR\|BAZ\)\.//' input_file

A: When you want to replace to first occurance of :something. in every line, test
sed 's/:[^.]*[.]/:/' inputfile

When this works and you want it replaced in the file without making a backup, you can use the option -i:
sed -i 's/:[^.]*[.]/:/' inputfile

When ${DOCKER_REGISTRY}/{REPOSITORY}/{IMAGE_NAME} might have a :, the pattern is matched at the wrong place. When you are sure that the ${TAG_NAME} is without :, use
sed -r 's/:[^.]*[.]([^:]*)$/:\1/' inputfile

Edit: After the comment of @potong, I replaced '.' with ':' in the replacement strings. I kept the wrong character.

A: Use one of these Perl one-liners:
# Remove { FOO, BAR or BAZ } and the following '.' :
perl -pe 's/(FOO|BAR|BAZ)[.]//' in_file > out_file

# Remove *anything* between the last ':' (exclusive) and '.' (inclusive) :
perl -pe 's/\A(.+:)[^.]+[.]/$1/' in_file > out_file

The Perl one-liners use these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-p : Loop over the input one line at a time, assigning it to $_ by default. Add print $_ after each loop iteration.
The regex uses:
\A : beginning of the line,
(.+:) : capture into variable $1 everything between the first character and the first semicolon,
[^.]+[.] : 1 or more occurrence of any character other than '.', followed by '.'. It is surrounded by brackets to match a literal dot: [.]
SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches
perldoc perlre: Perl regular expressions (regexes)
perldoc perlre: Perl regular expressions (regexes): Quantifiers; Character Classes and other Special Escapes; Assertions; Capture groups

A: In awk the variable FS containing a regex can help.
$ cat file

docker pull ${DOCKER_REGISTRY}/{REPOSITORY}/{IMAGE_NAME}:FOO.${TAG_NAME}
docker pull ${DOCKER_REGISTRY}/{REPOSITORY}/{IMAGE_NAME}:BAR.${TAG_NAME}
docker pull ${DOCKER_REGISTRY}/{REPOSITORY}/{IMAGE_NAME}:BAZ.${TAG_NAME}

In the input, we can see that the 3 words, each one with 3 characters (FOO, BAR, BAZ) and followed by dot. We can make a regex for the match inside the FS separator...
FS='[A-Z]{3}\\.'

In the awk manual we can read that "the value of FS may be a string containing any regular expression. In this case, each match in the record for the regular expression separates fields."
https://www.gnu.org/software/gawk/manual/html_node/Regexp-Field-Splitting.html
So we have
awk -v FS='[A-Z]{3}\\.' '{print $1 $2}'  file

docker pull ${DOCKER_REGISTRY}/{REPOSITORY}/{IMAGE_NAME}:${TAG_NAME}
docker pull ${DOCKER_REGISTRY}/{REPOSITORY}/{IMAGE_NAME}:${TAG_NAME}
docker pull ${DOCKER_REGISTRY}/{REPOSITORY}/{IMAGE_NAME}:${TAG_NAME}

..without comma: $1 $2
The same result gives the regex with the 3 specific words:
$ awk -v FS='(FOO|BAR|BAZ)\\.' '{print $1 $2}'  file
docker pull ${DOCKER_REGISTRY}/{REPOSITORY}/{IMAGE_NAME}:${TAG_NAME}
docker pull ${DOCKER_REGISTRY}/{REPOSITORY}/{IMAGE_NAME}:${TAG_NAME}
docker pull ${DOCKER_REGISTRY}/{REPOSITORY}/{IMAGE_NAME}:${TAG_NAME}

--


text:
Q: What does ct stand for in drugs? What does "ct" stand for in the following product advertised by Wallmart:
"Buy:ANY ONE (1) Dulcolax® Tablets 25ct+, Dulcolax® Suppositories 4ct+, Dulcolax Pink"
http://wm6.walmart.com/MediaOMP/2014/BoehringerIngelheim/01_BOE_67418_DulcolaxBate/images/Dulcolax_2015_Walmart_rebate_form.pdf

A: It stands for count, and in this context means the number of tablets, number of suppositories, etc.
This is a common abbreviation for labelling quantities of products for sale.

Count (ct), a frequently used abbreviation for a quantity of an object

http://en.m.wikipedia.org/wiki/CT
(See Time and units of measure section.)
Some additional examples of ct meaning the number of product units in a package/container:
http://www.amazon.com/Crayola-8ct-Washable-Markers-Fine/dp/B00006IFJ3
http://www.missionmenus.com/en/products/view/mission-flour-burrito-8ct

A: Not sure, but I think that in this context, ct stands for coated tablet.
From The Free Dictionary:

a solid disc of one or more pharmaceutic agents that is (1) coated with sugar or a flavoring to mask the taste or (2) enteric-coated, meaning that it is coated with a substance that resists dissolution in the stomach but allows release of the medication in the intestine.


text:
Q: Delete row in gridview after confirmation message Previously in order to delete my record i will use double click, but when it comes to tablet or phone the double click will identify as zoom in / zoom out, therefore i change to onclick with confirmation message and here comes the problem, how should i delete it after user press ok?

P/S: I didn't use button but by selecting the row to delete the data

current onclick code
e.Row.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this order? ');");

Previous doubleclick delete code
//e.Row.Attributes.Add("ondblclick", "__doPostBack('CView','Select$" + e.Row.RowIndex + "');");

the full code of it
protected void CView_RowDataBound(Object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#cccccc'");
        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
        e.Row.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this order?');");
        //e.Row.Attributes.Add("ondblclick", "__doPostBack('CView','Select$" + e.Row.RowIndex + "');");
    }
}

I'm still searching the answer through google. If someone else asked the same question before do share me the link. Thank you

A: Just try to assign the OnclientClick in aspx code for the button as follows
<asp:TemplateField>
      <ItemTemplate>
            <asp:Button ID="deletebtn" runat="server" CommandName="Delete"
             Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this order? ');" />
      </ItemTemplate>
</asp:TemplateField>

A: Try the following code
<asp:GridView ID="GridView1" runat="server" OnRowDeleting="OnRowDeleting" AutoGenerateColumns = "false" OnRowDataBound = "OnRowDataBound">
<Columns>
    <asp:BoundField DataField="..columnname.." HeaderText="...." />
    <asp:BoundField DataField="..columname.." HeaderText="...." />
    <asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>

Then on Row DataBound
   protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
    string item = e.Row.Cells[0].Text;
    foreach (Button button in e.Row.Cells[2].Controls.OfType<Button>())
    {
        if (button.CommandName == "Delete")
        {
            button.Attributes["onclick"] = "if(!confirm('Do you want to delete " + item + "?')){ return false; };";
        }
    }
    }
    }

Then on row deleting
 protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
 {
     // delete code
int index = Convert.ToInt32(e.RowIndex);
DataTable dt = ViewState["dt"] as DataTable;
dt.Rows[index].Delete();
ViewState["dt"] = dt;
BindGrid();
 }

A: If below line deletes the row from gridview
e.Row.Attributes.Add("ondblclick", "__doPostBack('CView','Select$" + e.Row.RowIndex + "');");

and you want to call above functionality on confirmation then you can do following changes.
if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#cccccc'");
        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
        e.Row.Attributes.Add("onclick", "var vconfirm = confirm('Are you sure you want to delete this order?'); if (vconfirm){ __doPostBack('CView','Select$" + e.Row.RowIndex + "');}");
    }


text:
Q: Having issue parsing back to an int after removing a character in Python? Here's the code that's giving me issues:
newI = int(str(i).replace(char, ""))
newJ = int(str(j).replace(char, ""))

I'm getting the issue in the first assignment. i and j are both two digit integers before this runs, and char has been assigned a value if it was found in either of them when they're parsed to strings. For instance, if i is 27 and j is 73, I'm hoping to cancel out the 7s. So I parsed to strings, found the character, and now I'm trying to parse back to ints with the character removed. I'm getting the error

ValueError: invalid literal for int() with base 10: ''.

Can anyone give me some tips? Here's some more code:
for j in range(10, i):
    for char in str(j):
        if char in str(i):
            newI = int(str(i).replace(char, ""))
            newJ = int(str(j).replace(char, ""))

A: Just set the count to 1:
"55".replace("5","", count=1)

A: In your example you have two nested for-loops. Using set intersections will be more efficient, especially if you are doing a bunch of large i, j values:
strI = str(i)
strJ = str(j)

# remove any similar characters (once)
for c in set(str(i)) & set(str(j)):
    strI = strI.replace(c, "", count = 1)
    strJ = strJ.replace(c, "", count = 1)

newI = int(strI)
newJ = int(strJ)


text:
Q: Adding instant search to wordpress page I'm new to the site and to web development in general. I have a domain name, a hosting site, and wordpress installed. That took me most of a day. Now I'm trying to add this functionality to my site http://www.9lessons.info/2010/09/youtube-instant-search-with-jquery-and.html as a proof of concept before heavily modifying it.
The problem is that while I can paste that code into an HTML file and run it perfectly, I can't get my wordpress site to fire it off within a page no matter what I try. After spending a good 6 hours banging my head around with things like child templates, the function.php file, etc. etc. I still can't get it working. What am I missing?

A: I finally figured this out. What ended up working is putting the script portion in a .js file within the theme directory, calling it using the functions.php in my child theme, and having the HTML input field and div tag in the body of the page.
Hopefully this can spare others the same pain I went through.