text:
Q: Nokogiri Node Set I am trying to use Nokogiri to scrape a web page.  Right now, I am able to set a variable links to the following on a web page:
links = page.css('.item_inner')

and links is a:
Nokogiri::XML::NodeSet

Then I iterate through this NodeSet(links):
links.each{|link| puts link.css('.details a')}

In order to get some more information.  But now the method above's class is now a:
Fixnum

and returns a list of (I'm not sure exactly what they are returning but it looks like a list of these:
<a se:clickable:target="true" href="/nyc/sale/1056207-coop-150-sullivan-street-soho-new-york?featured=1">150 Sullivan Street #34</a>

Now I know that there are key/value pairs within this but I am unable to access them at this point.  How can I access say the href here and the actual name?

A: Once you have a single link as a node, its href is link['href'] and so forth, and the link text ("150 Sullivan Street") is its content.
NOTE: A css search always yields what is effectively an array of found nodes (actually a NodeSet). If you are quite sure that there is only one of something to be found by your search, you can skip past that by using at_css instead, thus yielding a single node.


text:
Q: Create new column based of two columns I have two columns in a dataframe. I want to create third column such that if first column > second column than 1 ow 0. As below
Df
Value1  value 2.  Newcolumn

*
  101.      0

*
    97.      1

A: Comparing two columns in a Pandas DataFrame and write the results of the comparison to a third column. It can do easily by these syntaxes
conditions=[(condition1),(condition2)]
choices=["choice1","choice2"]

df["new_column_name"]=np.select(conditions, choices, default)

*

*conditions are the conditions to check for between the two columns

*choices are the results to return based on the conditions

*np.select is used to return the results to the new column

The dataframe is:
import numpy as np
import pandas as pd
#create DataFrame
df = pd.DataFrame({'Value1': [100,101],
                   'value 2': [101,97]})

#define conditions
conditions = [df['Value1'] < df['value 2'],
              df['Value1'] > df['value 2']]

#define choices
choices = ['0', '1']

#create new column in DataFrame that displays results of comparisons
df['Newcolumn'] = np.select(conditions, choices, default='Tie')

Final dataframe
print(df)

Output:
Value1  value 2 Newcolumn
0     100      101         0
1     101       97         1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Radio buttons submitting no values This seems (and should be) simple, but I have no idea why the values for my radio buttons appear empty
<!DOCTYPE html>

<form method="post" action="action_page.php">

Intermediate	Advanced	No selection

                1. Bash

            <input type="radio" name="td1" id="td1" value="BashInter"/>

        <input type="radio" name="td1"  value="BashAdv"/>

        <input type="radio"  name="td1" value="" />

                2. C

            <input type="radio" name="td2" id="td2" value="CInter"/>

        <input type="radio" name="td2"  value="CAdv"/>

        <input type="radio"  name="td2" value="" />

                3. C++

            <input type="radio" name="td3" id="td3" value="C++Inter"/>

        <input type="radio" name="td3"  value="C++Adv"/>

        <input type="radio"  name="td3" value="" />

<input type="submit" value="Submit">
</form>

If you click "Submit", the form-data will be sent to a page called "action_page.php".

If run on W3Schools' (ugh) server, it correctly outputs the input.
e.g.

td1=BashInter&td2=CAdv&td3=

However, my server, for print_r($_POST); returns

[td1] => [td2] => [td3] =>

regardless of what is selected.
Looking at the HTTP headers confirms that nothing is being sent.
All other aspects of the form correctly send their values.

I have tried a number of variants in relation to the values, but nothing has altered the fact that no data actually appears to be sent by the radio buttons.

A: You didn't specified that your form must be send as a POST one, so used method is defaulted to GET.
Try with
<form action="action_page.php" method="POST">

A: Last radio button of every set has been kept empty and has black value.
Which means <input type="radio"  name="td3" value="" /> needs to be  replaced with <input type="radio"  name="td3" value="Some value 3" />
So in case you are selecting last radio button from every set then obviously it wont return anything.
Apart from this there is not other problem as long as your HTML code is concerned. If you still face any problem please upload your PHP code as well.
I also suggest to give some some meaningful label to each radio.
Here is the code you may try
<!DOCTYPE html>

<form method="POST" action="action_page.php">

Intermediate	Advanced	No selection

                1. Bash

            <input type="radio" name="td1" id="td1" value="BashInter"/> BashInter

        <input type="radio" name="td1"  value="BashAdv"/> BashAdv

        <input type="radio"  name="td1" value="Some value 1" /> Some value 1

                2. C

            <input type="radio" name="td2" id="td2" value="CInter"/> CInter

        <input type="radio" name="td2"  value="CAdv"/> CAdv

        <input type="radio"  name="td2" value="Some value 2" /> Some value 2

                3. C++

            <input type="radio" name="td3" id="td3" value="C++Inter"/> C++Inter

        <input type="radio" name="td3"  value="C++Adv"/> C++Adv

        <input type="radio"  name="td3" value="Some value 3" /> Some value 3

<input type="submit" value="Submit">
</form>

If you click "Submit", the form-data will be sent to a page called "action_page.php".


text:
Q: Scala and SBT install on Debian with Java 8 I have java 8 server runtime on Debian.
Tried:
dpkg -i scala-2.11.7.deb
scala depends on java6-runtime-headless; however:
Package java6-runtime-headless is not installed.
But is ok:
scala -version
Scala code runner version 2.11.7 -- Copyright 2002-2013, LAMP/EPFL
Now installing SBT from bintray repo:
My Java 8 is deactivated, installs open openjdk-7-* ...
Have to "apt-get purge openjdk-7-*" (wrong way)
EDIT: Problem corrected with:
update-alternatives --config java

A: Here is the list of commands that I used to install in a clean Debian Jessie instance created using Vagrant:
Install Java 8
sudo add-apt-repository ppa:webupd8team/java

Edit the file /etc/apt/sources.list.d/webupd8team-java-jessie.list to replace jessie with trusty so that it will have the following line:
deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main

And then execute:
sudo apt-get update
sudo apt-get install oracle-java8-installer

Confirming that Java 8 is properly installed:
java -version

Which outputs:
java version "1.8.0_72"
Java(TM) SE Runtime Environment (build 1.8.0_72-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.72-b15, mixed mode)

Installing Scala 2.11.7:
wget -c www.scala-lang.org/files/archive/scala-2.11.7.deb
sudo dpkg -i scala-2.11.7.deb

This works fine to me and, just to confirm that I'm using the most recent version, I've executed:
sudo apt-get update
sudo apt-get install scala

And then:
scala -version

Which outputs:
Scala code runner version 2.11.7 -- Copyright 2002-2013, LAMP/EPFL

Install SBT:
wget -c https://bintray.com/artifact/download/sbt/debian/sbt-0.13.9.deb
sudo dpkg -i sbt-0.13.9.deb

Everything works as expected and then I've executed the following commands to ensure that I'm using the most recent version of SBT:
sudo apt-get update
sudo apt-get install sbt

At this point, Java 8, Scala and SBT were successfully installed on my machine.


text:
Q: In amazon-sqs-java-messaging-lib, what is the difference of numberOfMessagesToPrefetch 0 or 1? This question is about the library https://github.com/awslabs/amazon-sqs-java-messaging-lib. This library can be used for accessing AWS SQS, it is provided by AWS itself.
The library supports prefetching of messages. I wonder, what values have which impact here. The default is set to 1.
Which impact do the following value for numberOfMessagesToPrefetch have?

*

*0

*1

*> 1

A: Prefetching of messages into a local buffer that allows your application to immediately process messages from Amazon SQS without waiting for the messages to be retrieved.
numberOfMessagesToPrefetch Determine the number of messages we should attempt to fetch from SQS.
These numbers are configurable
MAX_BATCH = 10;
MIN_BATCH = 1;

After the first receiveMessage call is made, the client attempts not only to satisfy that call, but also pre-fetch extra messages to store in a temporary buffer. Future receiveMessage calls will be satisfied from the buffer, and only if the buffer is empty will the calling thread have to wait for the messages to be fetched.
Client-Side Buffering
Another Stackoverflow answer

A: If you step through the library you end up at this method AmazonSQS#receiveMessage(ReceiveMessageRequest)
which further links to API_ReceiveMessage.
From there you get the info that values between 1 and 10 are acceptable values.
The library seems to transfer any message it receives to an internal ArrayDeque from which you can retrieve the messages. The limiting factor of that queue is the numberOfMessagesToPrefetch you orginally configured.
If you use a value larger than 10 continous calls will be made, till the queue is completly filled.

Passing 0 means that there is no prefetch. Messages will be retrieve when the SQSMessageConsumer#receive method is called. As its synchronized internally I assume it most likely ends up calling AmazonSQS#receiveMessage with a value of 1.

Another point to note is that when you're using the SQSMessageConsumer#receive method you can only retrieve one message at a time. So eventually the calls to AmazonSQS#receiveMessage might end up only retrieving 1 message at a time, assuming the case where the buffer is always full and sufficient messages are available (e.g. under high load).


text:
Q: How do I spawn wolves? How do I spawn wolves in singleplayer Minecraft using Single Player Commands; what command do I use?

A: You can summon wolves using the following command:
/summon Wolf ~ ~ ~

If you want to summon a tamed wolf, use the following syntax:
/summon Wolf ~ ~ ~ {Owner:<PlayerName>}

Note that you cannot use @p here, it must be the player's name typed out.
If you want to summon a wolf with a specific collar colour, use the command:
/summon Wolf ~ ~ ~ {CollarColor:14}

for example. Modify the number from 0 to 16 to change the colour.

A: The command to spawn mobs using the SPC mod is /spawn [name] [quantity]. For example, you would type /spawn wolf 5 to spawn five wolves.


text:
Q: When the modifier option is true, validation object must have at least one operator - Collection 2 package - Meteor I get the following error when trying to create a user :
Exception while invoking method 'createUser' Error: When the modifier option
is true, validation object must have at least one operator

Here is how I am calling the createUser method :
Template.register.events({
  "submit #register_form": function(event) {
    event.preventDefault();

    var $form   = $("#register_form");
    var attr    = {};
    var profile = {};

    // We gather form values, selecting all named inputs
    $("input[name]", $form).each(function(idx) {
      var $input = $(this);
      var name   = $input.attr("name");

      if (name == "email" || name == "password") {
        attr[ name ] = $input.val();
      }
      else if (name != "repeat_password") {
        profile[ name ] = $input.val();
      }
    });
    attr.profile = profile;

    // Creating user account (Cf Accounts module)
    Accounts.createUser(attr, function(error) {
      console.log(error);
    });
  },
});

attr has the following value :

And here is how I define the users schema :
// Setting up Simple Schema (cf module)
var profile_schema = new SimpleSchema({
  firstname: {
    type:   String,
    regEx:  /^[a-z0-9A-Z_]{3,15}$/
  },
  lastname: {
    type:   String,
    regEx:  /^[a-z0-9A-Z_]{3,15}$/
  },
  celular: {
    type:     String,
    optional: true,
  },
});

var schema = new SimpleSchema({
  emails: {
    type:   [Object],
  },
  "emails.$.address": {
    type:   String,
    regEx:  SimpleSchema.RegEx.Email
  },
  "emails.$.verified": {
    type:   Boolean
  },
  profile: {
    type:     profile_schema,
    optional: true,
  },
  createdAt: {
    type:   Date
  },
});

// Attaching Simple Schema to the users collection (Cf collection2 module)
Meteor.users.attachSchema(schema);

I can't find what is not right. Any suggestion is most welcomed!

A: Adding my comment as an answer for visibility
You need to add the services object to your user schema as follows
services: {
    type: Object,
    blackbox: true
}

You need to add this even though you are not using any oAuth because Meteor adds a "service" for email login.  You should always have it.


text:
Q: I am having trouble downloading the ADT Plugin using the URL provided When I try to download the ADT Plugin in Eclispe using the URL provided https://d1-ss1.google.com/android/eclispe/ It comes back saying that it can't find this location.  I have tried using "http:" also and get the same error.
I have also tried downloading the plugin (ADT-8.0.0.zip) as directed.  When I try to configure the ADT Plugin (Window>preferences), Android is not listed in the left panel.
Can anyone tell me whats wrong?

A: It's dl-ssl (as in "download secure sockets layer"), not d1-ss1 - just copy/paste the URL from the instructions into Eclipse:
http://developer.android.com/sdk/eclipse-adt.html#installing


text:
Q: Selecting max in linq query or rewriting to method chain syntax I managed to turn this SQL query:
SELECT c.carId, c.Codename, count(c.CarId) as [CarCount],
  FROM [DbEfTesting].[dbo].[Cars] c
  left join Accessories a on c.CarId = a.CarId
  left join CarsPeople cp on cp.CarId = c.CarId
  left join People p on cp.PersonId = p.PersonId
  group by c.CarId, c.Codename

into a LINQ query:
var x = from c in _context.Cars
    join a in _context.Accessories on c.CarId equals a.Car.CarId
    join j in _context.CarsPeople on c.CarId equals j.CarId
    join p in _context.People on j.PersonId equals p.PersonId
    group c by new { c.CarId, c.Codename } into g
    select new VMCarAggregate()
    {
        CarId = g.Key.CarId,
        Codename = g.Key.Codename,
        CarCount = g.Count()
    };

But now I'm lost trying to include a max value e.g the SQL:
SELECT c.carId, c.Codename, count(c.CarId) as [CarCount], max(a.AccessoryId) ...

I googled it and found lots of answers for method syntax. If I were using method chain syntax, I know I could do something like this:
_context.Accessories.Max(a => a.AccessoryId);

but I can't figure out how to do the group by in method chain syntax so either:
How can I convert that query to method syntax?
or
How can I inject a select on the max a.AccessoryId in the LINQ query format?

A: Try the below code once:
var x = from c in _context.Cars
                    join a in _context.Accessories equals a.Car.CarId
                    join j in _context.CarsPeople on c.CarId equals j.CarId
                    join p in _context.People on j.PersonId equals p.PersonId
                    group new { c.CarId, c.Codename, a.AccesoryId } by new { c.CarId, c.Codename } into g
                    select new
                    {
                        CarId = g.Key.CarId,
                        Codename = g.Key.Codename,
                        CarCount = g.Count(),
                        MaxAccesory = g.Max(z => z.AccesoryId)
                    };


text:
Q: UILabel detect line breaks I am currently using a UILabel to display multiple lines of text. The line break most is set to NSLineBreakByWordWrapping so the the label automatically inserts line breaks. How can I detect where those line breaks are? Basically, I want to return a string with each \n break included.

A: Here is my work around for detecting line breaks inside UILabel
- (int)getLengthForString:(NSString *)str fromFrame:(CGRect)frame withFont:(UIFont *)font
{
    int length = 1;
    int lastSpace = 1;
    NSString *cutText = [str substringToIndex:length];
    CGSize textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)];
    while (textSize.height <= frame.size.height)
    {
        NSRange range = NSMakeRange (length, 1);
        if ([[str substringWithRange:range] isEqualToString:@" "])
        {
            lastSpace = length;
        }
        length++;
        cutText = [str substringToIndex:length];
        textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)];
    }
    return lastSpace;
}

-(NSString*) getLinebreaksWithString:(NSString*)labelText forWidth:(CGFloat)lblWidth forPoint:(CGPoint)point
{
    //Create Label
    UILabel *label = [[UILabel alloc] init];
    label.text = labelText;
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByWordWrapping;

    //Set frame according to string
    CGSize size = [label.text sizeWithFont:label.font
                         constrainedToSize:CGSizeMake(lblWidth, MAXFLOAT)
                             lineBreakMode:UILineBreakModeWordWrap];
    [label setFrame:CGRectMake(point.x , point.y , size.width , size.height)];

    //Add Label in current view
    [self.view addSubview:label];

    //Count the total number of lines for the Label which has NSLineBreakByWordWrapping line break mode
    int numLines = (int)(label.frame.size.height/label.font.leading);

    //Getting and dumping lines from text set on the Label
    NSMutableArray *allLines = [[NSMutableArray alloc] init];

    BOOL shouldLoop = YES;
    while (shouldLoop)
    {
        //Getting length of the string from rect with font
        int length = [self getLengthForString:labelText fromFrame:CGRectMake(point.x, point.y, size.width, size.height/numLines) withFont:label.font] + 1;

        [allLines addObject:[labelText substringToIndex:length]];

        labelText = [labelText substringFromIndex:length];
        if(labelText.length<length)
            shouldLoop = NO;
    }

    [allLines addObject:labelText];
    //NSLog(@"\n\n%@\n",allLines);

    return [allLines componentsJoinedByString:@"\n"];
}

How to use
NSString *labelText = @"We are what our thoughts have made us; so take care about what you think. Words are secondary. Thoughts live; they travel far.";

NSString *stringWithLineBreakChar = [self getLinebreaksWithString:labelText forWidth:200 forPoint:CGPointMake(15, 15)];
NSLog(@"\n\n%@",stringWithLineBreakChar);

You just need to set parameters required by getLinebreaksWithString and you will get a string with each "\n" break included.
OutPut

A: Here is my solution to this problem.
I iterate through all whitespace characters in the provided string, set substrings (from beginning to current whitespace) to my label and check the difference in the height. When the height changes I insert a new line character (simulates a line break).
func wordWrapFormattedStringFor(string: String) -> String {
    // Save label state
    let labelHidden = label.isHidden
    let labelText = label.text

    // Set text to current label and size it to fit the content
    label.isHidden = true
    label.text = string
    label.sizeToFit()
    label.layoutIfNeeded()

    // Prepare array with indexes of all whitespace characters
    let whitespaceIndexes: [String.Index] = {
        let whitespacesSet = CharacterSet.whitespacesAndNewlines
        var indexes: [String.Index] = []

        string.unicodeScalars.enumerated().forEach { i, unicodeScalar in
            if whitespacesSet.contains(unicodeScalar) {
                let index = string.index(string.startIndex, offsetBy: i)
                indexes.append(index)
            }
        }

        // We want also the index after the last character so that when we make substrings later we include also the last word
        // This index can only be used for substring to this index (not from or including, since it points to \0)
        let index = string.index(string.startIndex, offsetBy: string.characters.count)
        indexes.append(index)

        return indexes
    }()

    var reformattedString = ""

    let boundingSize = CGSize(width: label.bounds.width, height: CGFloat.greatestFiniteMagnitude)
    let attributes = [NSFontAttributeName: font]

    var runningHeight: CGFloat?
    var previousIndex: String.Index?

    whitespaceIndexes.forEach { index in
        let string = string.substring(to: index)
        let stringHeight = string.boundingRect(with: boundingSize, options: .usesLineFragmentOrigin, attributes: attributes, context: nil).height

        var newString: String = {
            if let previousIndex = previousIndex {
                return string.substring(from: previousIndex)
            } else {
                return string
            }
        }()

        if runningHeight == nil {
            runningHeight = stringHeight
        }

        if runningHeight! < stringHeight {
            // Check that we can create a new index with offset of 1 and that newString does not contain only a whitespace (for example if there are multiple consecutive whitespaces)
            if newString.characters.count > 1 {
                let splitIndex = newString.index(newString.startIndex, offsetBy: 1)
                // Insert a new line between the whitespace and rest of the string
                newString.insert("\n", at: splitIndex)
            }
        }

        reformattedString += newString

        runningHeight = stringHeight
        previousIndex = index
    }

    // Restore label
    label.text = labelText
    label.isHidden = labelHidden

    return reformattedString
}

Image - Comparison of output string with label text.
This solution worked really well in my case, hope it helps.


text:
Q: GetHashCode() Returning Different Values For Identical Object Values I was attempting to use the GetHashCode() value to determine if an object has changed after it's been validated via ajax calls in an ASP.NET MVC application.  However, I noticed that this did not work because the hash code value when returned during validation would be different than the hash code generated when the object was created again from the model binding with the same values in another request after the validation request.  I was able to solve this problem by creating a SHA hash instead, but I'm curious on why I was seeing this behavior.
I know that hash codes generated from GetHashCode() should not be persisted and can differ on different platforms and over time.  I thought that the time period was short enough when I first came up with this idea since these two calls were made in milliseconds of each other and when debugging I confirmed that the model contained the exact same values, but still produced a different hash code.
I'm curious about why this behavior is exhibited.  Why would this happen even though this is a single run of the application, albeit a web application?  Does this have to do with the ASP.NET life cycle?
In case needed here's the class & GetHashCode implementation I was using:
class DispositionSubmission
{
    [Display(Name = "Client")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Client is required.")]
    public string ClientId { get; set; }
    public string Carrier { get; set; }
    public Dictionary<string, string> DispositionInfo { get; set; }
    public DispositionType Type { get; set; } //int based enum

...

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = (int)15485863;
            int bigPrime = (int)15485867;

            hash = hash * bigPrime ^ ClientId.GetHashCode();
            hash = hash * bigPrime ^ (Carrier ?? "").GetHashCode();
            hash = hash * bigPrime ^ DispositionInfo.GetHashCode();
            hash = hash * bigPrime ^ Type.GetHashCode();

            return hash;
        }
    }
}

A: DispositionInfo does not have a type that overrides GetHashCode(). Two identical dictionaries with the same objects in them will have different hash codes.
You will need to adjust your GetHashCode() to either not include the dictionary or make it more complex to get the hash code of each key and value in the dictionary and add them up.

A: GetHashCode will return the same result for the exact same object. If the object has been reallocated, it doesn't matter if you have identical values in all fields, you will get a different result. This is because what you're really using is Object.GetHashCode(), which knows nothing about its other fields anyway.
This behavior is important because if you're using the hash as a way to refer to the object, changing any of its values would make it impossible to reference again.
If you want to have behavior where objects with identical fields have the same hash code, you'll need to implement it yourself.
Edit: To clarify: DispositionInfo, the dictionary, specifically exhibits this behavior. The other fields do not, because they are designed to be immutable (string, int, etc.) Consider getting the hash a different way, or overriding GetHashCode with a custom class that inherits from Dictionary<string, string>.


text:
Q: General questions about Parametric equations My textbook doesn't explain this very well, so what I want to know is:

*

*What is the purpose of parametric equations?

*What is a parameter?

*What is the advantage of these equations over a function y=f(x)?

*What do they essentially enable you to do?

I find this topic to be impenetrable so a thorough explanation in simple terms would be very much appreciated. Thank you.

A: We usually think of functions like $f(x)$ by their graph; for instance, to $f(x) = 1$ we associate a horizontal line, and to $f(x) = \sin x$ we associate the sin wave. However there is another good way to looking at functions: by their image. The function $f(x) = 0$ has domain and the real numbers, but its image is a single point (just 0). For $f(x) = \sin x$, the image is the interval $[-1,1]$. You might say that this is pretty much useless, because (for example) $f(x) = |x|$ and $f(x) = e^x$ have almost exactly the same images but are wildly different.
It turns out that looking at the image works a lot better in dimensions higher than 1, which is what parametric equations do. We can think of $f(x)$ as a parametric equation with just one parameter, namely $x$, and its image lies in just the real line. Similarly, the pair $(f(x), g(x))$ is a parametric equation whose image lies in the plane. If we take $f(x) = \cos x, g(x) = \sin x$, the image is a circle - much richer than in the one-dimensional case. Using more functions than just a pair we can look at paths in higher-dimensional space, like 3-space, and trace out lines in it. Using more parameters we can trace out surfaces or more complicated objects. Keep in mind that just as we can look at the function $f(x)$ as a parametrization of its image, which lies somewhere in the line, we can look at the pair $(f(x), g(x))$ as a function instead of a parametric equation. Its graph won't lie in the plane anymore though - we have to plot the argument against it, so it will lie in 3-space.
In summary, the parametric equation/function dichotomy isn't really a dichotomy at all. It just arises from two different ways of looking at functions - by their graphs and by their images.
Added: The fact that parametric equations represents a "broader" class of curves than the graph of simple functions arises because we can represent more thing in higher dimensions than in lower ones. When we go from the graph to the image, we're really just projecting down by collapsing an axis. For instance, the way we go from a sin wave to the interval $[-1,1]$ in my  example is by squishing the $x$-axis down to a point.

A: I don't believe that there is a specific definition of what a parameter really is; it is implicitely understood as a one-dimensional (mostly real, but it could be complex) number used to describe a set. For example, a line that passes through the origin and a vector $(a,b,c)$ in $\mathbb{R}^3$ can be described geometrically as
$$
V:\{(at,bt,ct)\in\mathbb{R}^3|t\in\mathbb{R}\}
$$
where $t$ is the parameter.
Note that the choice of the letter $t$ for the parameter many times is associated with the idea of time as a variable in applications, and its used as such in the theory of ordinary differential equations, for example.

A: Parametric equations allow you to represent figures that you would not be able to represent using standard functions. This is because of the strict requirement of the function that it pass the vertical line test, i.e., "no two $x$'s have the same $y$". But we'd like to have circles, or ellipses, which clearly fail this criterion!
The solution is to use parametric equations, which allows one to describe a figure by a $group$ of functions, rather than as a singular function. A basic example is the unit circle, which can be described parametrically as
$$(x(t),y(t))=(\cos t,\sin t)$$
Here, the parametrization is dependent on the "free" variable $t$ (whose domain is $[0,2\pi]$, since that is the period of the circle). The $x$-coordinate is determined by $\cos$ and the $y$-coordinate by $\sin$. As $t$ goes from $0$ to $2\pi$, the given parametrization "traces out" the circle. Hope that helps.

A: A parametrization is just another type of function. For example lets say we have a regular old function of one variable $y=f(x)$. Then we can view the graph of the function (which is in $\mathbb{R}^2$) as the image of a function $g:\mathbb{R}\to \mathbb{R}^2$ given by $s(t)=(t,f(t))$. Here we call $t$ a parameter because for every $t\in \mathbb{R}$ corresponds to exactly one point of the graph of $y=f(x)$. Viewing $t$ as representing time we can think of the parametrization of the graph of $y=f(x)$ as the path of a particle traveling along the graph. For example at time $t=1$ the particle is at the point $(1,f(1))$, at time $t=2$ the particle has now arrived at the point $(2,f(2))$ and so forth. The parametrization now allows us to view the graph of $y=f(x)$ not as a static object, but as a dynamical object, i.e., it is the path traversed by a particle through the evolution of time. But certainly graphs of functions are not the only spaces parametrizable. For example circles are parametrized by trigonometric function and circles are not the graphs of functions. Higher dimensional manifolds (shapes) such as surfaces may be parametrized as well, but in this case we can't view the parametrization as the trajectory of a particle in time, but the case of curves I think is sufficient for getting a feel of what a parametrization is and why they are useful.


text:
Q: How to get the number of frames captured in a video stream? I need to get the number of frames captured of a video using OpenCV with Java. I'm capturing the video through a webcam. I tried to use:
CV_CAP_PROP_POS_MSEC

in capture.get() but it seems like it is not working. I found a similar question here but didn't get any successful way to do this. I'm using OpenCV 2.4.8. Can anyone please give me any idea of how to do this? Thanks in advance!


text:
Q: Why does this simplification make my function slower? The following function computes the Fibonacci series by tail recursive and squaring:
(defun fib1 (n &optional (a 1) (b 0) (p 0) (q 1))
  (cond ((zerop n) b)
    ((evenp n)
     (fib1 (/ n 2)
          a
          b
          (+ (* p p) (* q q))
          (+ (* q q) (* 2 p q))))
    (t
     (fib1 (1- n)
          (+ (* b q) (* a (+ p q)))
          (+ (* b p) (* a q))
          p
          q))))

Basically it reduces every odd input to a even one, and reduces every even input by half. For example,
F(21)
    = F(21 1 0 0 1)
    = F(20 1 1 0 1)
    = F(10 1 1 1 1)
    = F(5 1 1 2 3)
    = F(4 8 5 2 3)
    = F(2 8 5 13 21)
    = F(1 8 5 610 987)
    = F(0 17711 10946 610 987)
    = 10946

When I saw this I thought it might be better to combine the even and odd cases (since odd minus one = even), so I wrote
(defun fib2 (n &optional (a 1) (b 0) (p 0) (q 1))
    (if (zerop n) b
     (fib2 (ash n -1)
          (if (evenp n) a (+ (* b q) (* a (+ p q))))
          (if (evenp n) b (+ (* b p) (* a q)))
          (+ (* p p) (* q q))
          (+ (* q q) (* 2 p q)))))

and hoping this will make it faster, as the equations above now becomes
F(21)
    = F(21 1 0 0 1)
    = F(10 1 1 1 1)
    = F(5 1 1 2 3)
    = F(2 8 5 13 21)
    = F(1 8 5 610 987)
    = F(0 17711 10946 1346269 2178309)
    = 10946

However, it turned out to be much slower (takes about 50% more time in e.g. Clozure CL, CLisp and Lispworks) when I check the time needed for Fib(1000000) by the following code (Ignore the progn, I just don't want my screen filled with numbers.)
(time (progn (fib1 1000000)()))
(time (progn (fib2 1000000)()))

I can only see fib2 may do more evenp than fib1, so why is it that much slower?
EDIT: I think n.m. get it right, and I edited the second group of formulae. E.g. in the example of F(21) above, fib2 actually computes F(31) and F(32) in p and q, which is never used. So in F(1000000), fib2 computes F(1048575) and F(1048576).
Lazy evaluation rocks, that's a very good point. I guess in Common Lisp only some macro like "and" and "or" are evaluated lazily?
The following modified fib2 (defined for n>0) actually runs faster:
(defun fib2 (n &optional (a 1) (b 0) (p 0) (q 1))
    (if (= n 1) (+ (* b p) (* a q))
     (fib2 (ash n -1)
          (if (evenp n) a (+ (* b q) (* a (+ p q))))
          (if (evenp n) b (+ (* b p) (* a q)))
          (+ (* p p) (* q q))
          (+ (* q q) (* 2 p q)))))

A: Insert printing of the intermediate results. Pay attention to p and q towards the end of the computation.
You will notice that fib2 computes much larger values for p and q at the last step. These two values account for all the performance difference.
The ironic thing is that these expensive values are unused. This is why Haskell doesn't suffer from this performance problem: the unused values are not actually computed.

A: If nothing else, fib2 has more conditionals (while computing the arguments). That may well change how the code flow is done. Conditionals imply jumps, implies pipeline stalls.
It would probably be instructive to look at the generated code (try (disassemble #'fib1) and (disassemble #'fib2) and see if there's any blatant differences). It might also be worth to change the optimization settings, there's usually a fair few optimizations that are not done unless you request heavy optimization for speed.


text:
Q: How important is an SSL certificate for a internal website? I know many people have asked the same question but I think it really depends on the type of the website. So that's why I am asking the question about my website.
I am developing a PHP web application for an insurance company. the application contains all information about the customers but this app is only used by the admins and salesman of the company. The admin creates a user then that user can add customers or renew their insurance. the address will be something like example.com/manage/ and the login is only for the users that admin person has created. Of course I will be using validation, salt, encryption, etc. But do I need SSL certificate?

A: Yes, whenever traffic is transported across an untrusted network.

*

*Using HTTPS encrypts the traffic. Otherwise, an attacker could read customer information or internal documents in the clear whenever they are transmitted. And if a password or other keys are ever transmitted as clear text, then an attacker could use those to get even better access.

*SSL certficates can authenticate a server to a user which makes man in the middle-attacks more difficult. Otherwise, an attacker could set up a proxy between the user and the real server, and record all communications even when they're encrypted.
Consider the following attack scenarios:

*

*A sales rep connects to your website while sitting in a coffee-shop. The Wi-Fi has been compromised, and all network traffic is recorded by a malicious hacker. If you do not verify the identity of the server and encrypt all traffic, the attacker can record and misuse confidential information or sensitive customer data, e.g. by selling the data to a competitor.

*The physical internet connection of your office is compromised. Your website is hosted outside of the office. All requests to the server are intercepted and redirected to a proxy which records all information. The same chaos as above ensues.
This is not of an issue when the server is only accessible via an Intranet which is already sufficiently secured and encrypted (e.g. via a VPN). Note that in some jurisdictions there are strong privacy requirements when handling customer data. Should you be breached without having secured the data properly, you could face legal action there.


text:
Q: React remove bootstrap.tsx Hello i have created new react app
there is index.tsx in src   and all it contains is
 import("./bootstrap")

if i remove this import or modify it the app stops working
the bootstrap.tsx file contains this
import React from 'react';
import { render } from 'react-dom';
import App from './App';

const Root: React.FC = () => <App />;

render(<Root />, document.getElementById('root'));

how can i remove it ?
i would like to if my index.tsx would containt
something like this
ReactDOM.render(
    <BrowserRouter>
      <App />
    </BrowserRouter>,

  document.getElementById('root')

app.tsx

interface AppProps {
  appPath?: string;
}

const App: React.FC<AppProps> = () => {
  return (
    <HashRouter>
      <Route path="/" exact component={View1Component} />
    </HashRouter>
  );
};

export default App;

A: I just came across this problem.
To remove bootstrap simply run the command below in your terminal
npm uninstall bootstrap
This will automatically uninstall bootstrap from your dependencies

A: Hi and welcome to Stack Overflow.
Just by the nature of this question I assume there's plenty answers on the internet and for sure in S.O. that will answer this.
Also, I invite you to put the error that it appears when you remove that bootstrap import.
However, I will try my best for now, have you tried the obvious, npm uninstall bootstrap and the removing the import line from the index file?
Let us know how it goes!


text:
Q: OpenSCAD: Rotating around a particular point? The following code rotates the second cube around the origin.  How can I rotate the second cube around its center point ([5,5,0]) instead?
cube([10,10,1]);
rotate([0,0,45]) cube([10,10,1]);

A: This module will perform the desired rotation.
// rotate as per a, v, but around point pt
module rotate_about_pt(a, v, pt) {
    translate(pt)
        rotate(a,v)
            translate(-pt)
                children();
}

cube([10,10,1]);
rotate_about_pt(45,0,[5,5,0]) cube([10,10,1]);

In newer versions (tested with the January 2019 preview) the above code generates a warning. To fix that, update the parameters to rotate:
module rotate_about_pt(z, y, pt) {
    translate(pt)
        rotate([0, y, z]) // CHANGE HERE
            translate(-pt)
                children();
}

A: If you are willing to 'center' the shape it is much easier:
cube(center =true,[10,10,1]);
rotate([0,0,45]) cube(center =true,[10,10,1]);


text:
Q: Required if doesn't working when comparing an enum with string in Jquery I need a slight help from you. I have a "RequiredIf" which is comparing a value from "EnumDropdown" and a "string" field but the code is not working in Jquery validation. Can anyone please suggest a way to do that.Below are the code snippets.
ViewModel :
[RequiredIf("ValidationOption", CustomerParameter.Phone, ErrorMessageResourceType = typeof(Customer_cshtml), ErrorMessageResourceName = "PhoneRequired")]
public string Phone { get; set; }
[RequiredIf("ValidationOption", CustomerParameter.Account, ErrorMessageResourceType = typeof(Customer_cshtml), ErrorMessageResourceName = "CustomerRequired")]
public string Account{ get; set; }
public CustomerParameter ValidationOption { get; set; }

JQUERY:
$.validator.addMethod('requiredif', function (value, element, parameters) {
    var id = '#' + parameters['dependentproperty'];
    var targetvalue = parameters['targetvalue'];
    targetvalue = (targetvalue == null ? '' : targetvalue).toString();
    var control = $(id);
    var controltype = control.attr('type'); --->//This line is getting undefined for EnumDropdownList property
    var actualvalue ;
    if (controltype === 'checkbox') {
        actualvalue = control.is(':checked').toString();
    } else if (controltype === 'radio') {
        actualvalue = $('input[name='+parameters['dependentproperty']+']:checked').val()
    } else {
        actualvalue = control.val();
    }

    // in the following, targetvalue is the name of the property (e.g.Phone or Account)
    // but actual value is the value of selected enums value (e.g. 0 or 1)
    // so the rules are not being added
    if (targetvalue === actualvalue)
        return $.validator.methods.required.call(this, value, element, parameters);


text:
Q: How can one efficiently find the (x,y) values of the rectangles that enclose a chosen % of nonrandom data points in mathematica? A half hour of searching for answers did not give useful results.
This is typical data:

I need to find the (x,y) values of at least 6 rectangles with one corner at (0,0) and the opposite corner at (x,y) which enclose a defined percentage of all 10^6 data points.
4/20/18 Update:
I have added Carl Woll's code to the program. It gives a fast and accurate answer for the (x,y) values of the rectangles that enclose a chosen % of the data points. Here is the full code:
(*----------------------------------------------------------------*)
(*Remove all symbols*)
Remove["Global`*"];
(*--------------------------------*)
(*Side force data in kgF*)
forceside =
  Round[{1.46372184`, 1.5154776`, 1.62452304`, 1.64008152`,
    1.64888136`, 1.64924424`, 1.7485826400000002`,
    1.9107900000000002`, 1.92067848`, 1.95651288`,
    1.9618200000000001`, 2.02047048`, 2.0909145600000003`,
    2.13232824`, 2.1611772`, 2.22912648`, 2.36516112`, 2.43143208`,
    2.5262344800000003`, 2.57454288`, 2.61110304`, 2.66857416`,
    2.7966708`, 2.93379408`, 3.24033696`}, 0.0001];
(*Assume rear force data is identical to side force data*)
forcerear = forceside;
(*Bottom force data in kgF*)
forcebottom =
  Round[{1.67655096`, 1.73234376`, 1.8965016000000001`, 2.06723664`,
    2.19692088`, 2.20885056`, 2.21420304`, 2.2199184`, 2.25389304`,
    2.2695422400000003`, 2.42848368`, 2.62902024`, 2.65727952`,
    2.76596208`, 2.95570296`, 3.15574056`, 3.25290168`,
    3.5498735999999997`, 3.8103760799999997`, 3.88707984`,
    4.00737456`, 4.1241312`, 4.34081592`, 4.56303456`, 4.57950024`},
   0.0001];
(*--------------------------------*)
(*set the Monte Carlo sample size *)
mccount = 10^6;
(*--------------------------------*)
(*Sample the pull locations*)
pulllocations = RandomChoice[{0.70, 0.16, 0.14} -> {0, 0, 1}, mccount];
(*Remove all the pull locations where the forces = 0*)
nonzeropulllocations = DeleteCases[pulllocations, 0];
(*Sample the HDMI port orientations*)
portorientations =
  RandomChoice[{0.41206, 0.46231, 0.12563} -> IdentityMatrix[3],
   Length[nonzeropulllocations]];
(*Separate out three lists for the three port orientations with \
nonzero pull forces and then remove the zeroes corresponding to pulls \
on other ports*)
portside = DeleteCases[portorientations[[All, 1]], 0];
portrear = DeleteCases[portorientations[[All, 2]], 0];
portbottom = DeleteCases[portorientations[[All, 3]], 0];
(*Sample the total number of cycles over 5 years for each customer \
with nonzero pulls*)
(*The five year bins are:*)
fiveyearbins = {{0, 0}, {1, 109}, {110, 209}, {210, 409}, {410,
    609}, {610, 809}, {810, 1009}, {1010, 1400}};
(*Assign the relative probabilities for a customer to be in each bin from the survey data*)
userprobabilities = {43, 36, 3, 1, 1, 1, 2, 1};
(*set up eight bins (1,2,3,4,5,6,7,8} for one user to randomly fall \
into*)
oneuser = IdentityMatrix[8];
(*Sample the number of users falling into each five year bin*)
cyclenumbers =
  ParallelTable[
   (*Sample the numbers of users in each bin, for 88 users:*)
   usersperbin = RandomChoice[userprobabilities -> oneuser, 88];
   (*add up how many users fell in each bin {1,2,3,4,5,6,7,8}*)
   usersamples = Total[usersperbin];
   (*Use these numbers to weigh a random choice of a single bin \
number*)
   randombin = RandomChoice[usersamples -> oneuser];
   (*For this random bin number;
   randomly choose a corresponding number of cycles and output the \
result so it goes into the table*)
   RandomInteger[randombin.fiveyearbins]
   (*repeat for all of the nonzero pull cases*)
   ,Length[nonzeropulllocations]];
(*assign each user one of these cycle numbers, deleting all zero \
cycle numbers*)
(*Portside*)
portsideallcycles = cyclenumbers[[1 ;; Length[portside]]];
portsidecycles = DeleteCases[portsideallcycles, 0];
(*Portrear*)
portrearallcycles =
  cyclenumbers[[
   Length[portside] + 1 ;; Length[portside] + Length[portrear]]];
portrearcycles = DeleteCases[portrearallcycles, 0];
(*Portbottom*)
portbottomallcycles =
  cyclenumbers[[
   Length[portside] + Length[portrear] + 1 ;;
    Length[portside] + Length[portrear] + Length[portbottom]]];
portbottomcycles = DeleteCases[portbottomallcycles, 0];
(*Sample the side force distribution parameters*)
sidedist = LogNormalDistribution[\[Mu], \[Sigma]];
sideBootstrap := {\[Mu], \[Sigma]} /.
      FindDistributionParameters[
    RandomChoice[forceside, Length[forceside]], sidedist];
sidesample = sideBootstrap;
sidemu = sidesample[[1]];
sidesigma = sidesample[[2]];
(*Sample the rear force distribution parameters*)
reardist = LogNormalDistribution[\[Mu], \[Sigma]];
rearBootstrap := {\[Mu], \[Sigma]} /.
      FindDistributionParameters[
    RandomChoice[forcerear, Length[forcerear]], reardist];
rearsample = rearBootstrap;
rearmu = rearsample[[1]];
rearsigma = rearsample[[2]];
(*Sample the bottom force distribution parameters*)
bottomdist = LogNormalDistribution[\[Mu], \[Sigma]];
bottomBootstrap := {\[Mu], \[Sigma]} /.
      FindDistributionParameters[
    RandomChoice[forcebottom, Length[forcebottom]], bottomdist];
bottomsample = bottomBootstrap;
bottommu = bottomsample[[1]];
bottomsigma = bottomsample[[2]];
(*Make a list of sequential forces for each nonzero force and nonzero \
cycle*)
(*sideforce*)
sideforcehistories = ParallelTable[
   RandomVariate[LogNormalDistribution[sidemu, sidesigma],
    portsidecycles[[i]]]
   , {i, 1, Length[portsidecycles]}];
(*rearforce*)
rearforcehistories = ParallelTable[
   RandomVariate[LogNormalDistribution[rearmu, rearsigma],
    portrearcycles[[j]]]
   , {j, 1, Length[portrearcycles]}];
(*bottomforce*)
bottomforcehistories = ParallelTable[
   RandomVariate[LogNormalDistribution[bottommu, bottomsigma],
    portbottomcycles[[k]]], {k, 1, Length[portbottomcycles]}];
(*Combine all of the force histories into one list*)
nonzeroforcehistories =
  Join[sideforcehistories, rearforcehistories, bottomforcehistories];
(*Restore all of the zero cycles and zero forces histories*)
numberofzeroes = mccount - Length[nonzeroforcehistories];
allforcehistories =
  Join[nonzeroforcehistories, ParallelTable[{0}, numberofzeroes]];
(*Find the max pull force for each nonzero force history:*)
maxstresses = Map[Max, nonzeroforcehistories];
(*The max event numbers of the nonzero force histories are the eventsamples numbers:*)
maxevents = Map[Length, nonzeroforcehistories];
(*Make a list of {maxevents,maxstresses} for all nonzero force histories:*)
maxeventsandstresses = Transpose[{maxevents, maxstresses}];
(*Count the number of {0,0} elements missing from {maxevents,maxstresses}:*)
numbermissing = mccount - Length[maxeventsandstresses];
(*make that many {0,0} elements*)
zeropairs = ParallelTable[{0, 0}, numbermissing];
(*Append these {0,0} elements to the list of maxeventsandstresses*)
fullmaxeventsandstresses = Join[maxeventsandstresses, zeropairs];
maxplot =
  ListPlot[fullmaxeventsandstresses, PlotRange -> All, Frame -> True,
   PlotStyle -> Red, GridLines -> Full, FrameLabel -> {"x", "y"}];
(*--------------------------------*)
(*Input data, set cycle spec, and set reliability target in %:*)
pts = fullmaxeventsandstresses;
cyclespec = 110;
rtarget = 97.50;
(*--------------------------------*)
(*Carl Woll: Presort the points by y value for speed:*)
yFunction[pts_] :=
 yFunction[Length[pts], Sequence @@ Transpose@SortBy[pts, Last]]
yFunction[len_, xpts_, ypts_][percent_, x_] :=
 Module[{xin, yin}, xin = UnitStep[x - xpts];
  If[Total[xin] < percent len, $Failed,
   Pick[ypts, xin, 1][[Floor[len percent]]]]]
(*The yFunction constructs a yFunction object that can be used to
find the y value for a given percent and x-value:*)
yf = yFunction[pts];
(*yf[target fractional reliability, target cycle number]:*)
stressspec = yf[rtarget/100, cyclespec];
Print[{cyclespec, stressspec}];
(*Calculate the actual reliability in %*)
reliability =
  100.*Count[
     fullmaxeventsandstresses, {u_, v_} /;
      u < cyclespec && v < stressspec]/mccount;
Print[reliability];
(*Envelope of spec box:*)
envelope =
  Plot[yf[reliability/100, x], {x, 0, 1400}, PlotStyle -> Blue];
(*Plot the data and the envelope:*)
Show[maxplot, envelope]
(*--------------------------------*)

A: fraction = .5
n = 1000
pts = RandomReal[{0, 1}, {n, 2}];
xmin = Sort[pts[[All, 1]]][[Ceiling[fraction n]]]
y[x_, n_] :=
 Quiet@Check[ Sort[Select[pts, #[[1]] <= x  &][[All, 2]]][[n]], 0]
Graphics[{Point@
   pts, {FaceForm[None], EdgeForm[Red], Rectangle[ {0, 0}, #]} & /@
   Select[
    Table[ {x, y[x, Ceiling[fraction n]]}, {x,
      Subdivide[xmin, 1, 6]}], #[[2]] > 0 &]}]

A: This is a straight forward, brute force solution. It returns the lower bounds of all the bins that meet your criteria. (Assuming I've read it correctly.)
HeaneysProblem[data_, maxDataValue_, binWidth_, percentage_] :=
  Module[ {binC, R, targetN},
   binC = BinCounts[data, {0, maxDataValue, binWidth},{0, maxDataValue, binWidth}];
   R = Accumulate[Map[Accumulate,binC]];
   targetN = Floor[percentage*Length[data]];
   Position[R, _?((targetN <= # < targetN + 1) &)]*binWidth
 ]

 CheckHeaneysProblem[data_, results_] :=
    Union[Map[CheckHeaneysProblem1[data, #] &, results]]
 CheckHeaneysProblem1[data_, {rx_, ry_}] :=
    Length[Cases[data, {x_, y_} /; x <= rx && y <= ry]]/Length[data]

 RandomReal[{0, 1}, {100, 2}];
 HeaneysProblem[%, 1, 0.01, 1/10];
 ListPlot[{%, %%}]
 CheckHeaneysProblem[%%%, %%]

EDIT: Runs much faster with Henrik Schumacher's suggestion of using "accumulate" instead of summation

A: This generates some data to play with:
n = 1000000;
xa = 0.;
xb = 2.;
ya = 0.;
yb = 1.;
pts = Transpose[{RandomReal[{xa, xb}, n], RandomReal[{ya, yb}, n]}];
percentage = 10.;
threshold = Length[pts] percentage 0.01;

Now I split the whole rectangle into small reactangular bins and count the number of points in each bin with BinCounts:
xresolution = 2000;
yresolution = 1000;
counts = BinCounts[
  pts,
  {xa, xb, (xb - xa)/xresolution},
  {ya, yb, (yb - ya)/yresolution}
 ];

Accumate provides an efficient way to sum up the number of pts in the rectangular region to the lower left of each bin.
accumulatedcounts = Accumulate[Accumulate /@ counts];

Now we substract the threshold and apply UnitStep and Image to obtain a black white image img. (Note that  compared to the original rectangle, the image appears rotated since the first coordinate axis in images points downward). A white pixel in img stands for a bin which has more than the desired percentage of points in its lower left rectangular; a black pixel indicates less than the percentage of points to the lower left. Finally, we detect the points on the border with EdgeDetect and read off the bin indices with Position.
img = Image@UnitStep[accumulatedcounts - threshold]
edges = EdgeDetect@img
idx = Position[ImageData[edges], 1];

Finally, we merely have to extract the upper right x-y-coordinates of the bins. I do it like this:
{i, j} = Transpose[idx];
binupperrightx = Rest[Subdivide[xa, xb, xresolution]];
binupperrighty = Rest[Subdivide[xa, xb, xresolution]];
result = Transpose[{binupperrightx[[i]], binupperrightx[[j]]}];
ListPlot[result, PlotRange -> {{xa, xb}, {ya, yb}}, Frame -> True]

Because we apply rasterization, the method is not exact (we can improve upon that by increasing xresolution and yresolution), but it should suffice for every day applications.

A: Updated with faster method
Here's a function that takes as arguments the points, the percent, and an x-value:
y[pts_, percent_, x_] := Module[{xin, yin},
    xin = UnitStep[x - pts[[All, 1]]];
    If[Total[xin] < percent Length[pts],
        $Failed,

        yin = Pick[pts[[All, 2]], xin, 1];
        yin[[First @ Ordering[yin, {Floor[Length[pts] percent]}]]]
    ]
]

Example showing timing for a million points:
SeedRandom[1]
pts = RandomReal[1, {10^6, 2}] . {{1, 0}, {0, 5}};

y[pts, .3, .8] //AbsoluteTiming
y[pts, .7, .2] //AbsoluteTiming

{0.140796, 1.87733}
{0.027093, $Failed}

Presorting
If we presort the points by y value, we can speed this up considerably. Here is an approach that does this.
yFunction[pts_] := yFunction[Length[pts], Sequence @@ Transpose @ SortBy[pts, Last]]

yFunction[len_, xpts_, ypts_][percent_, x_] := Module[{xin, yin},
    xin = UnitStep[x - xpts];
    If[Total[xin] < percent len,
        $Failed,

        Pick[ypts, xin, 1][[Floor[len percent]]]
    ]
]

The idea is that yFunction constructs a yFunction object that can be used to find the y value for a given percent and x-value. Here is the same example:
yf = yFunction[pts];

yf[.3, .8] //AbsoluteTiming
yf[.7, .2] //AbsoluteTiming

{0.021508, 1.87733}
{0.00715, $Failed}

About 7 times faster.
Visualizations
Visualization of y vs x:
Plot[yf[.3, x], {x, 0, 1}]

Rectangle visualization for a different set of 1000 points:
SeedRandom[2]
pts = RandomReal[1, {1000, 2}] . {{5, 0}, {0, 1}};
yf = yFunction[pts];

Graphics[{
    Green,
    Point[pts],
    FaceForm[None],
    EdgeForm[Red],
    Rectangle[{0, 0}, {#, yf[.2, #]}]& /@ Range[5]
}]


text:
Q: Cannot POST erro express Estou tentando criar um sistema de login, segue meu form:
<form action="/auth" class="login-form" method="POST">

Login

    <input type="text" name="username" id="username" placeholder="Username">

    <input type="password" name="password" id="password" placeholder="Password">

  <input type="submit" class="logbtn" value="Login">

    Não ten uma conta? Sign up

</form>

Meu server.js
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const mysql = require('mysql');
const session = require('express-session');
const bodyParser = require('body-parser');
const path = require("path");

const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);

app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'public'));
app.engine('html',require('ejs').renderFile);
app.set('view engine','html');

app.get('/', (req, res) => {
    res.render('index.html');
});

app.get('/chat', (req, res) => {
    res.render('chat.html');
});

let messages = [];

io.on('connection', socket => {
    console.log('Socket conectado');

    socket.on('sendMessage', data => {
        messages.push(data);
        socket.broadcast.emit('receivedMessage', data);
    });
});

//Login

var connection = mysql.createConnection({
    host:'localhost',
    user: 'root',
    password: '',
    database: 'sanderson'
});

connection.connect(function(error) {
    if(!!error){
        console.log('Erro!')
    }
    else{
        console.log('Conectou :)')
    }
});

var log = express();
log.use(session({
    secret: 'secret',
    resave: true,
    saveUninitialized: true
}));
log.use(bodyParser.urlencoded({extended : true}));
log.use(bodyParser.json());

log.get('/', function(request, response) {
    response.sendFile(path.join(__dirname + '/index.html'));
});

log.post('/auth', function(request, response) {
    var username = request.body.username;
    var password = request.body.password;
    if (username && password) {
        connection.query('SELECT * FROM user WHERE nome = ? AND senha = ?', [username, password], function(error, results, fields) {
            if (results.length > 0) {
                request.session.loggedin = true;
                request.session.username = username;
                response.redirect('public/chat.html');
            } else {
                response.send('Incorrect Username and/or Password!');
                response.redirect('public/test.html');
            }
        });
    } else {
        response.send('Please enter Username and Password!');
        response.redirect('public/test.html');
    }
});

server.listen(3000);

Meu index.html é o formulário, quando clico em enviar esse erro aparece.

A: Em seu html você deve declarar as tags name e placeholder dentro da tag input.
Modificando o seu html temos o seguinte código:
<form action="/auth" class="login-form" method="POST">

Login

      <input type="text" name="username" id="username" placeholder="Username">

      <input type="password" name="password" id="password" placeholder="Password">

    <input type="submit" class="logbtn" value="Login">

      Não ten uma conta? Sign up

  </form>

Repare que a escolha dos nomes dessas variáveis não é aleatória, esses são os nomes que estão declarados em seu módulo app.js, dentro do função post da rota /auth , vc usa os valores dessas variáveis para fazer a consulta no banco de dados. Por isso a declaração desses nomes.
Agora será possível utilizar sua conexão ao banco para verificar os usuário e senha
O código que utilizei em meu express foi o seguinte:
app.js
const express = require('express')
const path = require('path')
var log = express();

log.use(express.urlencoded({extended : true}));
log.use(express.json());

log.get('/', function(request, response) {
    response.sendFile(path.join(__dirname + '/public/index.html'));
});

log.post('/auth', function(request, response) {
    console.log(request.body)
    var username = request.body.username;
    var password = request.body.password;
    if (username && password) {
        connection.query('SELECT * FROM user WHERE nome = ? AND senha = ?', [username, password], function(error, results, fields) {
            if (results.length > 0) {
                request.session.loggedin = true;
                request.session.username = username;
                response.redirect('public/chat.html');
            } else {
                response.send('Incorrect Username and/or Password!');
                response.redirect('public/test.html');
            }
        });
    } else {
        response.send('Please enter Username and Password!');
        response.redirect('public/test.html');
    }
});

log.listen(3000);


text:
Q: Define a function that returns all of the non-trivial splits of a list as a list of pairs I'm new to Haskell and have been given a worksheet question which has me stumped. The question is asking me to define a function that takes a list and returns a list of tuples, each of which contains a sub list of the original list.

I have tried the below. However, as expected, on each recursion the the previous head gets dropped.
splits :: [Int] -> [([Int],[Int])]
splits []
  = [([],[])]
splits (l:ls)
  = ([] ++ [l], ls) : splits ls

Here is the result I get.
[([1],[2,3,4]),([2],[3,4]),([3],[4]),([4],[]),([],[])]

Any advice on how to do this would be appreciated!

A: You only need to prepend the first items in the result of the recursive call with l, so
splits :: [a] -> [([a], [a])]
splits [] = []
splits (l:ls) = ([l], ls) : map f (splits ls)
    where f (x, y) = (l:x, y)

or with first:
import Control.Arrow(first)

splits :: [a] -> [([a], [a])]
splits [] = []
splits (l:ls) = ([l], ls) : map (first (l:)) (splits ls)

A: This also removes the item which has an empty tail :
splits :: [Int] -> [([Int], [Int])]
splits [] = []
splits [x] = []
splits (x : xs) = ([x], xs) : map f (splits xs)
  where
    f (z, y) = (x : z, y)


text:
Q: unable to connect to cache daemon? I am able to push fine, but I am suddenly getting this "fatal" message
$ git push
fatal: unable to connect to cache daemon: Bad file descriptor
Username for 'https://github.com':
Password for 'https://myid@github.com':
fatal: unable to connect to cache daemon: Bad file descriptor
...

Why do I get this message all of the sudden? and what do I do?
I am not sure this might help, but between now and before this problem occurred

*

*I was working on some branch that is not master

*I changed my user.email in git config --global in the middle

*my computer crashed big time because I connected the wrong project connector(that is not for the computer) to it, and I believe somehow some file got corrupted

*After that occurred, when I tried to make a new commit,I was getting the following message : fatal: Failed to resolve HEAD as a valid ref.

*Then I fixed it by modifying HEAD in config to "ref: refs/heads/master"

*After coding and successfully committing the changes locally,  when I tried to push it to the remote server, I got the following error message
$ git push
fatal: unable to connect to cache daemon: Bad file descriptor
Username for 'https://github.com':
Password for 'https://myid0@github.com':
fatal: unable to connect to cache daemon: Bad file descriptor
fatal: loose object 8ce710b1c78658e066cd2309b12b7766d1be4920 (stored in     .git/objects/8c/e710b1c78658e066cd2309b12b7766d1be4920) is corrupt
fatal: The remote end hung up unexpectedly
fatal: The remote end hung up unexpectedly
fatal: write error: Bad file descriptor

*So I backed up all the changes I made, deleted the repo, clone the repo from the github, and made some changes with the backup files, add, commit, and pushed the changes fine...but still that message does not go away :(

A:
This error comes when you try to commit using "sudo".
  so the password saved is for "sudo" user only,

  But when you try to commit as a normal user,
  This error happens, permission denied for normal user
  you can get rid of this error by using above answer Kev Price

A: https://stackoverflow.com/a/14160580
solved this for me:
sudo chown kev ~/.git-credential-cache/socket

replace kev with your user if you don't know your user:
whoami

A: Quick solution
Here is the single command you need to solve the issue.
sudo chown $(whoami) ~/.cache/git/credential/socket

Read the other answers if you want a deeper understanding of what causes this issue.

A: Beware of manipulating ~/.git-credential-cache/socket (as with chown), for it has moved since 2014, as acknowledge by Git 2.13 (Q2 2017)
Adam K Dean also mention in the comments the path ~/.cache/git/credential/, which just needed chowning back to the user.
See commit 612c49e, commit 60759ba (17 Mar 2017), and commit e7f136b (13 Mar 2017) by Devin Lehmacher (lehmacdj).
(Merged by Junio C Hamano -- gitster -- in commit 78cf8ef, 24 Mar 2017)

credential-cache: use XDG_CACHE_HOME for socket

Make git-credential-cache follow the XDG base path specification by
default. This increases consistency with other applications and helps
keep clutter out of users' home directories.

Check the old socket location, ~/.git-credential-cache/, and use
~/.git-credential-cache/socket if that directory exists rather than
forcing users who have used git credential-cache before to migrate to
the new XDG compliant location.

Otherwise use the socket $XDG_CACHE_HOME/git/credential/socket following
XDG base path specification.
Use the subdirectory credential/ in case
other files are cached under $XDG_CACHE_HOME/git/ in the future and to
make the socket's purpose clear.

Note: With Git 2.29 (Q4 2020), a handful of places in in-tree code still relied on being able to execute the git(man) subcommands, especially built-ins, in "git-foo" form, which have been corrected.
See commit c0e190c, commit 7cff3b6, commit 675df19 (26 Aug 2020) by Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit 18aff08, 03 Sep 2020)

credential-cache: use child_process.args

As child_process structure has an embedded strvec args for formulating the command line, let's use it instead of using an out-of-line argv[] whose length needs to be maintained correctly.
Also, when spawning a git subcommand, omit it from the command list and instead use the .git_cmd bit in the child_process structure.

So, no more call to git-credential-cache--daemon, but rather git credential-cache--daemon.

A: Try to set global gitconfig.
git config --global user.name "your username"
git config --global user.email "your email address"

A: It can be due to your first setup as root user, and then you want to use git as another user.You can change the git cache permission:
chown -R user:user_group ~/.cache/git/


text:
Q: Jackson MRBean not working, Cannot construct instance I have this code:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.registerModule(new MrBeanModule());

and this testcase:
SearchResultContainer src = objectMapper.readValue("{}", SearchResultContainer.class);

SearchResultContainer is a POJO interface (that's the whole reason MRBean is used here).
Why does this fail with the following exception?
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.ctc.rets.dto.search.SearchResultContainer` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
 at [Source: (String)"{}"; line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1451)
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1027)
    at com.fasterxml.jackson.databind.deser.AbstractDeserializer.deserialize(AbstractDeserializer.java:265)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4001)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2992)
    at com.ctc.web.client.CustomRestTemplateTest.test1(CustomRestTemplateTest.java:25)

A: Incorrect version of MRBean found in pom.xml.
Fix:
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-mrbean -->
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-mrbean</artifactId>
    <version>2.9.8</version>
</dependency>


text:
Q: Detecting periodic repetitions in the data stream Let's say I have an array of zeros:
a = numpy.zeros(1000)
I then introduce some repetitive 'events':
a[range(0, 1000, 30)] = 1
Question is, how do I detect the 'signal' there? Because it's far from the ideal signal if I do the 'regular' FFT I don't get a clear indication of where my 'true' signal is:
f = abs(numpy.fft.rfft(a))
Is there a method to detect these repetitions with some degree of certainty? Especially if I have few of those mixed in, for example here:
a[range(0, 1000, 30)] = 1
a[range(0, 1000, 110)] = 1
a[range(0, 1000, 48)] = 1

I'd like to get three 'spikes' on the resulting data...

A: Have you considered using autocorrelation?

A: As an analytical technique acf/pacf/ccf are used
to identify periodicity in time-dependent signals, hence the correlogram, the graphical display of acf or pacf, displays self-similarity in a signal as a function of different lags. (So for instance, if you see values on the y axis peak at a lag of 12, and if your date is in months, that's evidence of annual periodicity.)
To calculate and plot 'similarity' versus lag, if you don't want to roll your own, i am not aware of a native Numpy/Scipy option; I also couldn't find one in the 'time series' scikit (one of the libraries in the Scipy 'Scikits', domain-specific modules not included in the standard Scipy distribution) but it's worth checking again. The other option is to install Python bindings to R (RPy2, available on SourceForge) which will allow you to access the relevant R functions, including 'acf' which will calculate and plot the correlogram just by passing in your time series and calling the function.
On the other hand, if you want to identify continuous (unbroken) streams of a given type in your signal, then "run-length encoding" is probably what you want:
import numpy as NP
signal = NP.array([3,3,3,3,3,3,3,3,3,0,0,0,0,0,0,0,0,0,0,7,7,7,7,7,4,4,1,1,1,1,1,1,1])
px, = NP.where(NP.ediff1d(signal) != 0)
px = NP.r_[(0, px+1, [len(signal)])]
# collect the run-lengths for each unique item in the signal
rx = [ (m, n, signal[m]) for (m, n) in zip(px[:-1], px[1:]) ]

# returns [(0, 9, 3), (9, 19, 0), (19, 24, 7), (24, 26, 4), (26, 33, 1)]
# so w/r/t first 3-tuple: '3' occurs continuously in the half-open interval 0 and 9, and so forth


text:
Q: Is it possible to use more quotes than ' and "? I want to have more than two layers of quotes.
This is for an error message using document.write and php's echo function.
<img src="#" onerror="javascript:document.write('<?php echo("An error has occurred.") ?>')"

I expected it to replace the document with "An error has occurred," but it didn't.

A: You shouldn't have javascript: as part of the onerror event.
wrap your statement in htmlentities with the ENT_QUOTE flag to handle embedded html and convert quotes to the appropriate escaped value.
<img src="#" onerror="document.write('<?= htmlentities("An error has occurred.", ENT_QUOTE); ?>')">

Unless you're echoing a php method or variable it's unnecessary to even use php.


text:
Q: How to deploy the war file generated by maven on tomcat using eclipse? I have got a war file generated using Maven and it works perfectly fine when i manually deploy it on the tomcat server.
However, the war file was generated using Maven on eclipse and when i try deploying this on the server using eclipse, it just doesn't act. The tomcat server starts perfectly fine. What I do is : Right click on the Tomcat Server 7.0, then Add/Remove Project and add it to the server.
The problem is when I deploy and publish it on the server and nothing happens after that.
On trying to access it, it says - The required resource is not found

A: Eclipse doesn't deploy the WAR. Instead, it knows how Tomcat works and deploys the exploded WAR.
The next step is to look into the webapps/ folder of Tomcat to make sure Eclipse really has deployed something.
If that looks ok, you need to look into the Tomcat log to see why it doesn't like the deployed web app.
Most of the time, there is old code which is somehow stuck in Tomcat, so Tomcat can't undeploy  the old version. If that's the case, stop Tomcat, delete the app manually and try again.

A: There were certain jars required in specific versions for the application to work. I was usin the maven supported versions. I have got it to work adding them directly in Tomcat's lib folder for time being and the application now works. (Anyways i need to look to get them configured now on the maven)
Also, i guess installing the plugin for m2e - eclipse.org/m2e-wtp helped as well. Thanks @Aaron Digulla for the inputs.


text:
Q: Float error when writing Celsius-Fahrenheit converter (Zelle) I'm currently learning Python from Zelle's book, and wrote the following Celsius to Fahrenheit converter. It works without issue:
print("This program will convert Celsius to Fahrenheit")
c = eval(input("Input the temperature in Celsius: "))
for i in range(10):
    f = c * (9/5) + 32
    print(f)

Zelle asks to later adapt this so that every ten degrees from 0 to 100 Celsius are converted to Fahrenheit, and set on top of one another like columns. I wrote it like this:
print("This program will do 10 temperature conversions.")
c = [0,10,20,30,40,50,60,70,80,90,100]
f = c * (9/5) + 32
for i in range(1):
    print(c)
for i in range(1):
    print(f)

I get the following errors:
1) If I leave it as is, the error states: "line 63, in fourthprogram
    f = c * (9/5) + 32  TypeError: can't multiply sequence by non-int of type 'float'"
2) If I change (9/5) to another number, like 2, the error states: "line 63, in fourthprogram
    f = c * 2 + 32
TypeError: can only concatenate list (not "int") to list"
So, there's a couple of things going on here that I can't quite figure out. The "float" error, according to other answers on Stack Overflow, often relate to variables treated as strings, but it looks like the variables are given a numerical value here. The other error, I tried rewriting the list in the options given by Zelle in Ch 2 and prior, but it's not helping.
How do I deal with this float error, specifically, and other more complex float errors in the future?
Zelle has answers up on his website, but I'd like to know why my code doesn't work as written.
Thank you.

A: Your code doesn't work because you are trying to do mathematical operations on the entire list 'c'. Python requires you to access the elements before operating on them. You have two options:
1) Use a for loop or list comprehension to do elementwise operations on your list. For example:
f = [x * (9/5) + 32 for x in c]

Will give you a list of all ten temperatures converted to fahrenheit.
2) If you'd like to get more advanced, you can use numpy. Numpy is a highly optimized library for doing math, and supports the vectorized operation syntax that seems natural to you. In other words, it automatically applies math operations to every element of the array, so just changing the first two lines of your code to read:
import numpy as np
c = np.array([0,10,20,30,40,50,60,70,80,90,100])

will work.
As an aside, once you've made either of those changes, there's no need for the
for i in range(1):
    print(c)

loops. Just print(c), it will make your code easier to read.


text:
Q: Proving certain polynomials are irreducible over $\mathbb{Z}$ Show that the polynomial $(x-1)(x-2)...(x-n)-1$ is irreducible over $\mathbb{Z}$. [hint: if the polynomial factors consider the values of the factors at $x = 1,2,3....,n$.
Show that the polynomial $(x-1)(x-2)...(x-n)+1$ is irreducible over $\mathbb{Z}$ $\forall n \geq 1, n \neq 4$.
I've been running around in circles on this one for awhile now and can't seem to get anywhere! Some insights would be greatly appreciated! Thanks yall!


text:
Q: Are there strongly-typed collections in Objective-C? I'm new to Mac/iPhone programming and Objective-C.  In C# and Java we have "generics", collection classes whose members can only be of the type declared.  For example, in C#
Dictionary<int, MyCustomObject>
can only contain keys that are integers and values that are of type MyCustomObject.  Does a similar mechanism exist in Objective-C?

A:
This answer is outdated but remains for historical value. As of Xcode 7, Connor's answer from Jun 8 '15 is more accurate.

No, there are no generics in Objective-C unless you want to use C++ templates in your own custom collection classes (which I strongly discourage).
Objective-C has dynamic typing as a feature, which means that the runtime doesn't care about the type of an object since all objects can receive messages. When you add an object to a built-in collection, they are just treated as if they were type id. But don't worry, just send messages to those objects like normal; it will work fine (unless of course one or more of the objects in the collection don't respond to the message you are sending).
Generics are needed in languages such as Java and C# because they are strong, statically typed languages. Totally different ballgame than Objective-C's dynamic typing feature.

A: This was released in Xcode 7 (finally!)
Note that in Objective C code, it's just a compile-time check; there will be no run-time error just for putting the wrong type into a collection or assigning to a typed property.
Declare:
@interface FooClass <T> : NSObject
@property (nonatomic) T prop;
@end

Use:
FooClass<NSString *> *foo = [[FooClass alloc] init];
NSArray<FooClass<NSString *> *> *fooAry = [NSArray array];

Be careful about those *s.

A: There are no generics in Objective-C.
From the Docs

Arrays are ordered collections of objects. Cocoa provides several array classes, NSArray, NSMutableArray (a subclass of NSArray), and NSPointerArray.

A: Apple has added generics to ObjC in XCode 7:
@property NSArray<NSDate *>* dates;
- (NSArray<NSDate *> *)datesBeforeDate:(NSDate *)date;
- (void)addDatesParsedFromTimestamps:(NSArray<NSString *> *)timestamps;

see here:
https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/BuildingCocoaApps/WorkingWithCocoaDataTypes.html#//apple_ref/doc/uid/TP40014216-CH6-ID61

A: Generic NSArrays can be realized by subclassing NSArray, and redefining all provided methods with more restrictive ones. For example,
- (id)objectAtIndex:(NSUInteger)index

would have to be redefined in
@interface NSStringArray : NSArray

as
- (NSString *)objectAtIndex:(NSUInteger)index

for an NSArray to contain only NSStrings.
The created subclass can be used as a drop-in replacement and brings many useful features: compiler warnings, property access, better code creation and -completion in Xcode. All these are compile-time features, there is no need to redefine the actual implementation - NSArray's methods can still be used.
It's possible to automate this and boil it down to only two statements, which brings it close to languages that support generics. I've created an automation with WMGenericCollection, where templates are provided as C Preprocessor Macros.
After importing the header file containing the macro, you can create a generic NSArray with two statements: one for the interface and one for the implementation. You only need to provide the data type you want to store and names for your subclasses. WMGenericCollection provides such templates for NSArray, NSDictionary and NSSet, as well as their mutable counterparts.
An example: List<int> could be realized by a custom class called NumberArray, which is created with the following statement:
WMGENERICARRAY_INTERFACE(NSNumber *, // type of the value class
                         // generated class names
                         NumberArray, MutableNumberArray)

Once you've created NumberArray, you can use it everywhere in your project. It lacks the syntax of <int>, but you can choose your own naming scheme to label these as classes as templates.

A: In Xcode 7, Apple has introduced 'Lightweight Generics' to Objective-C. In Objective-C, they will generate compiler warnings if there is a type mismatch.
NSArray<NSString*>* arr = @[@"str"];

NSString* string = [arr objectAtIndex:0];
NSNumber* number = [arr objectAtIndex:0]; // Warning: Incompatible pointer types initializing 'NSNumber *' with an expression of type 'NSString *'

And in Swift code, they will produce a compiler error:
var str: String = arr[0]
var num: Int = arr[0] //Error 'String' is not convertible to 'Int'

Lightweight Generics are intended to be used with NSArray, NSDictionary and NSSet, but you can also add them to your own classes:
@interface GenericsTest<__covariant T> : NSObject

-(void)genericMethod:(T)object;

@end

@implementation GenericsTest

-(void)genericMethod:(id)object {}

@end

Objective-C will behave like it did before with compiler warnings.
GenericsTest<NSString*>* test = [GenericsTest new];

[test genericMethod:@"string"];
[test genericMethod:@1]; // Warning: Incompatible pointer types sending 'NSNumber *' to parameter of type 'NSString *'

but Swift will ignore the Generic information completely. (No longer true in Swift 3+.)
var test = GenericsTest<String>() //Error: Cannot specialize non-generic type 'GenericsTest'

Aside from than these Foundation collection classes, Objective-C lightweight generics are ignored by Swift. Any other types using lightweight generics are imported into Swift as if they were unparameterized.

Interacting with Objective-C APIs

A: Take a look at:
https://github.com/tomersh/Objective-C-Generics
It appears to be a sort of poor-man's generics, by repurposing the protocol checking mechanism.

A: Now dreams come true - there are Generics in Objective-C since today (thanks, WWDC).
It's not a joke - on official page of Swift:

New syntax features let you write more expressive code while improving consistency across the language. The SDKs have employed new Objective-C features such as generics and nullability annotation to make Swift code even cleaner and safer. Here is just a sampling of Swift 2.0 enhancements.

And image that proofs this:

A: Just want to jump in here. I've written a blog post over here about Generics.
The thing I want to contribute is that Generics can be added to any class, not just the collection classes as Apple indicates.
I've successfully added then to a variety of classes as they work exactly the same as Apple's collections do. ie. compile time checking, code completion, enabling the removal of casts, etc.
Enjoy.

A: No, but to make it clearer you can comment it with the type of object you want to store, I've seen this done a few times when you need to write something in Java 1.4 nowadays) e.g.:
NSMutableArray* /*<TypeA>*/ arrayName = ....

or
NSDictionary* /*<TypeA, TypeB>*/ dictionaryName = ...

A: The Collections classes provided by Apple and GNUStep frameworks are semi-generic in that they assume that they are given objects, some that are sortable and some that respond to certain messages.  For primitives like floats, ints, etc, all the C arrays structure is intact and can be used, and there are special wrapper objects for them for use in the general collection classes (eg NSNumber).
In addition, a Collection class may be sub-classed (or specifically modified via categories) to accept objects of any type, but you have to write all the type-handling code yourself.
Messages may be sent to any object but should return null if it is inappropriate for the object, or the message should be forwarded to an appropriate object. True type errors should be caught at compile-time, not at run-time. At run-time they should be handled or ignored.
Finally, Objc provides run-time reflection facilities to handle tricky cases and message response, specific type, and services can be checked on an object before it is sent a message or put into an inappropriate collection.
Beware that disparate libraries and frameworks adopt different conventions as to how their objects behave when sent messages they do not have code responses for, so RTFM. Other than toy programs and debugging builds, most programs should not have to crash unless they really screw up and try to write bad data to memory or disk, perform illegal operations (eg divide by zero, but you can catch that too), or access off-limits system resources.
The dynamism and run-time of Objective-C allows for things to fail gracefully and should be built in to your code.
(HINT) if yo are having trouble with genericity in your functions, try some specificity. Write the functions over with specific types and let the runtime select (thats why they are called selectors!) the appropriate member-function at run-time.
Example:
    -(id) sort (id) obj;  // too generic. catches all.
     // better
    -(id) sort: (EasilySortableCollection*) esc;
    -(id) sort: (HardToSortCollection*) hsc;
    ...
    [Sorter  sort: MyEasyColl];
    [Sorter  sort: MyHardColl];


text:
Q: how to write this type of fraction value as shown below?
Hot to write this type of fraction Value in java or android code as shown above ? Any idea/suggestion will be appreciated.

A: Do you mean how to display it?
Unicode provides fractions up to eighths (used in finance)
http://tlt.its.psu.edu/suggestions/international/bylanguage/mathchart.html
On the other hand, if your output can render HTML, you can combine "sup" and "sub" tags
1 11/16

1 11/16

A: My idea would be to create a sublcass the relativelayout and add 3 textviews for each number and the '/' as an image.
Another method would be to create a custom view and use the canvas to the draw the fraction.


text:
Q: Echo category name once per id I have a query SELECT id, title, imagename FROM cat JOIN images ON id=id
I want to echo only once title per category and then 3 images. And then the same with next category.
Tables layout:
Cat Table
id title

Images Table
id imagename

The final result should look like this:
Title

Imagename Imagename Imagename

Title

Imagename Imagename Imagename

The query is printed using foreach cycle as object ($this->results as $result ) { echo $result->title; } etc..
Also I'm interested if there are other ways (queries?) of getting the same results.

A: You need to keep track of the current title and only echo a title when it is different from the current one:
$title = '';
// loop
  ...
  if ($result->title !== $title)
  {
    echo $result->title;
    $title = $result->title;
  }
  ...
// end loop

Note that you do need to ORDER BY title in your query as you could get the same title again later on if you don't.

A: You can add a variable like $prevTitle and if the current title matches the previous title, don't echo it. This will ensure only the new titles would be echoed, and only once. Of course, that would mean that your object would have to be sorted/grouped by titles in order not to have results like

title1
title1
title2
title1

because that would echo the title 1 twice.


text:
Q: Getting error while writing a simple trigger I am getting an error as below while saving the trigger:

Error : Compile Error: Invalid identifier ''. Apex identifiers must
  start with an ASCII letter (a-z or A-Z) followed by any number of
  ASCII letters (a-z or A-Z), digits (0 - 9), '$', '_'.

trigger validWorker on Worker__c(before insert, before update){
  for(Worker__c worker:Trigger.new){
   if(worker.Type__c =='Chef' && worker.Percent__c <> 10)
    {
      worker.addError('Percentage must be 10%');
    }
  }
}

A: You are not closing the quote on line worker.addError('Percentage must be 10%);
Try the below code
trigger validWorker on Worker__c(before insert, before update){
  for(Worker__c worker:Trigger.new){
   if(worker.Type__c =='Chef' && worker.Percent__c <> 10)
    {
      worker.addError('Percentage must be 10%');
    }
  }
}

The above code seems to be working for me. Please refer the below link. This might solve your problem.
Apex Identifiers must start with an ASCII Character

A: Derek is correct. For a faster fix, however:

*

*Paste your broken code into http://cloudandfree.com/en/remove_non_ascii.php

*Replace all non-ASCII characters with a symbol not in your file (e.g. $)

*In your editor, replace your code with the results from step 2, then find and replace every $ with an empty space

A: For future reference, this type of issue usually turns out to be caused by invisible characters being included when you copy/paste code. If that's the case, then re-typing the code (not using copy/paste for anything) in question fixes the issue.
Yes, it can be a pain to re-type things, but you'd probably spend as much time (if not more) trying to track down one of the many unprintable UTF-8 characters that could be included.


text:
Q: Specify Helm Chart Name use for upgrade install command I am using Helm 3 and when I run below command in Jenkins pipeline.
  + helm upgrade --install road-dashboard -f values.dev.yaml --namespace dev

I received an below error.

Error: "helm upgrade" requires 2 arguments

Probably I should specify chart name as well.But I have some confusion because of new for using Helm.
1.How should I specify the  chart name. It has to be directory or any chart name that I can specify.My app tree structure as below.
 +-- helm\road-dashboard
    |       +--charts
    |       +-- templates
    |       |   \-- ...
    |       +-- Chart.yaml
    |       +-- values.dev.yaml     # dev override values
    |       +-- values.stage.yaml   # stage override values
    |       +-- values.prod.yaml    # production override values

2.I would like to run helm lint command before deployment.My helm chart directory in Jenkins:/home/ubuntu/workspace/road-dashboard/helm/road-dashboard. So what is the best practice to change directory only for helm lint command and return existing working directory for helm --upgrade install command which should be /home/ubuntu/workspace/road-dashboard. Below is the script that but not sure this is suitable for best practices.
        stage('Deploy to dev'){
        when{
            beforeAgent true
            expression{return env.GIT_BRANCH == "origin/develop"}
        }
        steps{
            dir('/home/ubuntu/workspace/road-dashboard/helm/road-dashboard'){
                sh "helm lint"
            }
            script{
                def namespace = "dev"
                def ENV = "dev"

                withCredentials([file(credentialsId: 'mbtkubeconfig', variable: 'config')]){

                    sh """
                        export KUBECONFIG=\${config}

A: You can get the release and chart name by running the "helm list" command if it is already deployed.
The syntax for helm upgrade is -
helm upgrade [RELEASE] [CHART] [flags]

so in your case
helm upgrade [RELEASE] [CHART] --install -f values.yaml .. ...

Regarding the second question -
I would suggest you stay in the Jenkins job workspace directory and the switch directories as per your need. Any step inside the dir block will use this directory as current and any relative path will use it as the base path.
https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#dir-change-current-directory
Also, defining a separate stage for lint and actual deployment would be a good idea; so you get a clear indication which stage failed in case of failures.


text:
Q: How to validate against an OpenAPI schema with $refs using json-schema-validator One caveat here is that the OpenAPI Schema is not being used for the purposes of validating requests and responses. The OpenAPI schema can't be changed to a regular JSON Schema.
Say we have an OpenAPI schema in the form
TestSchema.json
{
  "components": {
    "schemas": {
      "book": {
        "type": "object",
        "properties": {
          "title": {
            "type": "string"
          },
          "author": {
            "$ref": "#/components/schemas/author"
          }
        }
      },
      "author": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string"
          }
        }
      }
    }
  }
}

Now imagine we have some JSON taking the form of a "book" as defined in the above schema
{
  "title": "LOTR",
  "author": {
    "name": "Tolkien"
  }
}

Using the json-schema-validator library we've written code to perform this validation as follows
public class SchemaValidator {
    private final ObjectMapper mapper = new ObjectMapper();
    private final JsonSchema schema;

    public SchemaValidator(FileReader schemaFile) throws IOException {
        schema = getJsonSchemaFromJsonNode(mapper.readTree(schemaFile));
    }

    public Set<ValidationMessage> validate(String json) throws IOException {
        return schema.validate(mapper.readTree(json));
    }

    private JsonSchema getJsonSchemaFromJsonNode(JsonNode node) {
        return JsonSchemaFactory.getInstance(VersionFlag.V6).getSchema(node);
    }
}

Usage:
@Test
void validate_invalidTitle() throws IOException {
    var schemaValidator = new SchemaValidator(
        new FileReader("src/test/resources/TestSchema.json")
    );
    var json = "{\"title\":5,\"author\":{\"name\":\"Tolkien\"}}";

    assertEquals(
        "$.title: integer found, string expected",
        schemaValidator.validate(json).stream().findAny().orElseThrow().getMessage()
    );
}

Since the OpenAPI schema has two extra nodes, "components" and "schemas" this code doesn't perform validation because we can't do a 1-1 validation between our "book" json and the schema.
A way around this is to re-write the constructor with a .findValue("book")
public SchemaValidator(FileReader schemaFile) throws IOException {
    schema = getJsonSchemaFromJsonNode(mapper.readTree(schemaFile).findValue("book"));
}

But this results in an error of
#/properties/author/$ref: Reference #/components/schemas/author cannot be resolved
As we have now broken the reference path.
One way around this to get the test to pass is to adjust the $ref in the schema to #/author but the schema itself is then invalid.
Am I missing a tool in this library or building the objects incorrectly? What needs to be done to make this validation work?
I dug around in the open-api-validator which ends up using the json-schema-validator library to perform validation but the request/response validation is not a step I need.


text:
Q: cant get 2nd datatable its own css I am trying to get my second datatable to use its own css (for the alternating row color) once i added the {  sClass: "myCustomClass" }, my jquery is not firing anymore.
Css for the demo_table.css
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* DataTables row classes
*/
table.display tr.odd.gradeA {
background-color: #ddffdd;
}

table.display tr.even.gradeA {
background-color: #eeffee;
}

table.display tr.odd.gradeC {
background-color: #ddddff;
}

table.display tr.even.gradeC {
background-color: #eeeeff;
}

table.display tr.odd.gradeX {
background-color: #ffdddd;
}

table.display tr.even.gradeX {
background-color: #ffeeee;
}

table.display tr.odd.gradeU {
background-color: #ddd;
}

table.display tr.even.gradeU {
background-color: #eee;
}

tr.odd {
background-color: #E2E4FF;
}

tr.even {
background-color: white;
}

table.display tr.even.myCustomClass { background-color: #FFFFCC; }
table.display tr.odd.myCustomClass { background-color: #ffeeee; }

Jquery I am using to initialize the datatable, which worked perfectly before adding the sclass in but didnt have any of the css that i added.
    function nestedtable(systemid) {
    var dbselected = $('#dblist').find(":selected").text();

    $('#nested_id').dataTable({
        "sAjaxSource": '/php/connect/nestedsearchtablequery.php',
        "bProcessing": true,
        "bDeferRender": true,
        "bDestroy": true,
        "sAjaxDataProp": "",
        "fnServerParams": function (aoData) {
            aoData.push({ "name": "db", "value": dbselected}),
            aoData.push({ "name": "systemid", "value": systemid });
        },
        "aoColumns": [
            {  sClass: "myCustomClass" },
            { "mData": "eventtime" },
            { "mData": "eventtype" },
            { "mData": "cid_name" },
            { "mData": "cid_num" },
            { "mData": "cid_ani" },
            { "mData": "cid_dnid" },
            { "mData": "exten" },
            { "mData": "context" },
            { "mData": "appname" },
            { "mData": "channame" }, ]
        //"bJQueryUI": true  //This is commented out to remove the smooth datatable style
    });
}

I have two tables #table_id and #nested_id, I am trying to change row colors on #nested_id.
This is the jquery for the #nested_id
 function fnFormatDetails(oTable, nTr, systemid) {

    var sOut =
'
' +
  '
' +
    '
'
                 + '
'
                     + 'Time	'
                     + 'Event	'
                     + 'CNAM	'
                     + 'CNUM	'
                     + 'ANI	'
                     + 'DID	'
                     + 'Exten	'
                     + 'Context	'
                     + 'AppName	'
                     + 'Channel	'
                 + '
'
             + '
'
             + '

'
    '
' +
'
';
    return sOut;
}

This is the html for the #table_id

                     Call Date
                     Recording
                     System
                     CallerID
                     App
                     Destination
                     Disposition
                     Duration

A: I think the problem is in your CSS...  sClass puts the class on every td in a column, not a tr.  So tr.even.myCustomClass is never applied.
It should be more like:
table.display tr.even td.myCustomClass { background-color: #FFFFCC; }
table.display tr.odd td.myCustomClass { background-color: #ffeeee; }

EDIT based on update to OP
You can avoid using sClass all together, and just use CSS specific to your nested table:
Your table in your html is missing class="display".  So you can either add and you CSS is:
table.display#nested_id tr.even { background-color: #FFFFCC; }
table.display#nested_id tr.odd { background-color: #ffeeee; }

Or you can leave it off and your CSS is:
table#nested_id tr.even { background-color: #FFFFCC; }
table#nested_id tr.odd { background-color: #ffeeee; }

Finally, you'll need to add CSS for
table#nested_id tr.even .sorting_1{ /*background-color here*/ }
table#nested_id tr.odd .sorting_1{ /*background-color here*/ }

See this jsfiddle for a working example.


text:
Q: Django 'WSGIRequest' object is not callable I'm working on an app and I'm trying to display all my users but I get this error
TypeError at /everyone/
'WSGIRequest' object is not callable

File "/home/snake/mysite/pet/views.py" in Everyone
  14.   return HttpResponseRedirect(request('world:Profile'))
Exception Type: TypeError at /everyone/
Exception Value: 'WSGIRequest' object is not callable

I did a lookup at my shell prompt and it successfully work but when I implement as a function into my views.py why do I get this error.
everyone = Person.objects.all()
print everyone
< sam > < amy >
My views.py
def Everyone(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect(request('world:Profile'))
    everyone =Person.objects.all()
        return render(request,'everyone.html',{'everyone':everyone})

My models.py
class Person(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=100)
    image = models.FileField(upload_to="images/",blank=True,null=True)

My everyone.html
{% for one in everyone %}
{{one.name}}
{{one.user.username}}
{% endfor %]

A: Here:
...
return HttpResponseRedirect(request('world:Profile'))
...

You're using the request object as a callable, which it isn't. You probably wanted to call the reverse function.

A: return HttpResponseRedirect(request,'world:Profile')
Test remove braces around the 'world:Profile'.