text:
Q: Slider in PyQt4 I am new to PyQt, I am trying to implement slider in PyQt4, but i don't know why code code is not generating any output.
what i want is, create 3 slider to change 3 values dynamically.
Here i am resizing font size of text "hue", "sat", "val".
Is there is any good source to learn slider in PyQt?
here is my code
PyQt4Slider.py
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class Window(QWidget):
def __init__(self):
    super(Window, self).__init__()
    self.setGeometry(50,50,500,300)
    self.setWindowTiltle("HSV")
    self.home()

def home(self):
    #hue = 100
    #sat = 100
    #val = 100
    layout = QVBoxLayout()
    self.l1 = QLabel("hue")
    self.l2 = QLabel("sat")
    self.l3 = QLabel("val")
    self.l1.setAlignment(Qt.AlignCenter)
    self.l2.setAlignment(Qt.AlignCenter)
    self.l3.setAlignment(Qt.AlignCenter)
    layout.addWidget(self.l1)
    layout.addWidget(self.l1)
    layout.addWidget(self.l1)

    self.sl = QSlider(Qt.Horizontal)
    self.s2 = QSlider(Qt.Horizontal)
    self.s3 = QSlider(Qt.Horizontal)

    self.sl.setMinimum(0)
    self.sl.setMaximum(179)
    self.sl.setValue(20)
    self.sl.setTickPosition(QSlider.TicksBelow)
    self.sl.setTickInterval(5)

    self.s2.setMinimum(0)
    self.s2.setMaximum(255)
    self.s2.setValue(100)
    self.s2.setTickPosition(QSlider.TicksBelow)
    self.s2.setTickInterval(5)

    self.s3.setMinimum(0)
    self.s3.setMaximum(255)
    self.s3.setValue(100)
    self.s3.setTickPosition(QSlider.TicksBelow)
    self.s3.setTickInterval(5)

    layout.addWidget(self.s1)
    self.sl.valueChanged.connect(self.valuechange)
    layout.addWidget(self.s2)
    self.s2.valueChanged.connect(self.valuechange)
    layout.addWidget(self.s3)
    self.s3.valueChanged.connect(self.valuechange)

    self.setLayout(layout)

    def valuechange(self):
        sizel1 = self.sl.value()
        self.l1.setFont("Arial",sizel1)
        sizel2 = self.sl.value()
        self.l2.setFont("Arial", sizel2)
        sizel2 = self.sl.value()
        self.l2.setFont("Arial", sizel2)

def main():
    app = QApplication(sys.argv)
    ex = Window()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

here is what i am getting after running code
Ran 0 tests in 0.000s
OK
Process finished with exit code 0
Empty test suite.

A: Most of the problems in your script are caused by typos. Here is a fixed version that should work okay:
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50,50,500,300)
        self.setWindowTitle("HSV")
        self.home()

    def home(self):
        layout = QVBoxLayout()
        self.l1 = QLabel("hue")
        self.l2 = QLabel("sat")
        self.l3 = QLabel("val")
        self.l1.setAlignment(Qt.AlignCenter)
        self.l2.setAlignment(Qt.AlignCenter)
        self.l3.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.l1)
        layout.addWidget(self.l2)
        layout.addWidget(self.l3)

        self.s1 = QSlider(Qt.Horizontal)
        self.s2 = QSlider(Qt.Horizontal)
        self.s3 = QSlider(Qt.Horizontal)

        self.s1.setMinimum(0)
        self.s1.setMaximum(179)
        self.s1.setValue(20)
        self.s1.setTickPosition(QSlider.TicksBelow)
        self.s1.setTickInterval(5)

        self.s2.setMinimum(0)
        self.s2.setMaximum(255)
        self.s2.setValue(100)
        self.s2.setTickPosition(QSlider.TicksBelow)
        self.s2.setTickInterval(5)

        self.s3.setMinimum(0)
        self.s3.setMaximum(255)
        self.s3.setValue(100)
        self.s3.setTickPosition(QSlider.TicksBelow)
        self.s3.setTickInterval(5)

        layout.addWidget(self.s1)
        self.s1.valueChanged.connect(self.valuechange)
        layout.addWidget(self.s2)
        self.s2.valueChanged.connect(self.valuechange)
        layout.addWidget(self.s3)
        self.s3.valueChanged.connect(self.valuechange)

        self.setLayout(layout)

        # set the initial fonts
        self.valuechange()

    def valuechange(self):
        sizel1 = self.s1.value()
        self.l1.setFont(QFont("Arial", sizel1))
        sizel2 = self.s2.value()
        self.l2.setFont(QFont("Arial", sizel2))
        sizel3 = self.s3.value()
        self.l3.setFont(QFont("Arial", sizel3))

def main():
    app = QApplication(sys.argv)
    ex = Window()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


text:
Q: rjson::fromJSON returns only the first item I have a sqlite database file with several columns. One of the columns has a JSON dictionary (with two keys) embedded in it. I want to extract the JSON column to a data frame in R that shows each key in a separate column.
I tried rjson::fromJSON, but it reads only the first item. Is there a trick that I'm missing?
Here's an example that mimics my problem:
> eg <- as.vector(c("{\"3x\": 20, \"6y\": 23}", "{\"3x\": 60, \"6y\": 50}"))
> fromJSON(eg)

$3x
[1] 20
$6y
[1] 23
The desired output is something like:
# a data frame for both variables
  3x 6y
1 20 23
2 60 50

or,
# a data frame for each variable
  3x
1 20
2 60

  6y
1 23
2 50

A: What you are looking for is actually a combination of lapply and some application of rbind or related.
I'll extend your data a little, just to have more than 2 elements.
eg <- c("{\"3x\": 20, \"6y\": 23}",
        "{\"3x\": 60, \"6y\": 50}",
        "{\"3x\": 99, \"6y\": 72}")

library(jsonlite)

Using base R, we can do
do.call(rbind.data.frame, lapply(eg, fromJSON))
#   X3x X6y
# 1  20  23
# 2  60  50
# 3  99  72

You might be tempted to do something like Reduce(rbind, lapply(eg, fromJSON)), but the notable difference is that in the Reduce model, rbind is called "N-1" times, where "N" is the number of elements in eg; this results in a LOT of copying of data, and though it might work alright with small "N", it scales horribly. With the do.call option, rbind is called exactly once.
Notice that the column labels have been R-ized, since data.frame column names should not start with numbers. (It is possible, but generally discouraged.)
If you're confident that all substrings will have exactly the same elements, then you may be good here. If there's a chance that there will be a difference at some point, perhaps
eg <- c(eg, "{\"3x\": 99}")

then you'll notice that the base R solution no longer works by default.
do.call(rbind.data.frame, lapply(eg, fromJSON))
# Error in (function (..., deparse.level = 1, make.row.names = TRUE, stringsAsFactors = default.stringsAsFactors())  :
#   numbers of columns of arguments do not match

There may be techniques to try to normalize the elements such that you can be assured of matches. However, if you're not averse to a tidyverse package:
library(dplyr)
eg2 <- bind_rows(lapply(eg, fromJSON))
eg2
# # A tibble: 4 × 2
#    `3x`  `6y`
#   <int> <int>
# 1    20    23
# 2    60    50
# 3    99    72
# 4    99    NA

though you cannot call it as directly with the dollar-method, you can still use [[ or backticks.
eg2$3x
# Error: unexpected numeric constant in "eg2$3"
eg2[["3x"]]
# [1] 20 60 99 99
eg2$`3x`
# [1] 20 60 99 99

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the idiomatic word for processed foods? Ramen instant noodles are a famous dish among college kids, as they are cheap and easy(and fast) to make. However, people say that they are unhealthy, and might cause illnesses in the long run, if consumed regularly.
Say I am a parent, and I have to tell my kids that they can't have instant noodles, because they are harmful for their health. How would I say that.

Ramen noodles are pre-cooked foods.
Ramen noodles are processed foods

What word can I use I place of precooked and processed here?

A: You could say "fast food" as an implication of processed food, "convenience food" or "prepackaged food".
But "processed food" is a phrase that is not that hard to understand, you can just explain simply how it is "changed/processed over and over again".


text:
Q: I renamed the directory "Video's" into "Video_s", to avoid complications in Terminal, but a new problem came up I work with a Lubuntu 22.04 LTS installation on a laptop set for the Duch locale.
Because I experienced a problem when copying a file in Terminal from my "Video's" directory (see this question), I changed the name of that directory to "Video_s", which solved that problem. But a new problem arose.
First: the name "Video's" for the directory/folder in my  user-directory stems from my locale setting, because in the Dutch language the plural of video is video's.
The problem that I encountered after changing the directory name to "Video_s" is illustrated by the attached picture.
When I selected my user folder in the GUI I saw that the folder for Videos still was named "Video's" and when I selected that "Video's" folder I got the error as can be seen in the illustration: "Error when getting information for file "/home/paul/Video's": No such file or directory".

So, I renamed that GUI folder by right-clicking on it and selecting "change bookmark name" (it was in Dutch, but this is the equivalent in English I guess) and I changed "Video's" there also into "Video_s".
Alas, that did not solve it, because when clicking this changed Video_s-folder, I got the same error as before: "Error when getting information for file "/home/paul/Video's": No such file or directory".

As can be seen the content of the directory "Video_s", does not appear while the directory "Video_s" is not empty, as I can assure you.
Now I suppose that the GUI-folder, now named "Video_s" being a bookmark according to the systeem, still points to the old "Video's" directory which does not exist anymore, but I do not know how to change this behavior of that bookmark.
Who can tell me how to do that?


text:
Q: Simultaneously development of iOS and Android app in React-Native I have been searching online for a while trying to find some best practices for simultaneously development of iOS and Android app in React-Native. I was wondering if anyone has any experience with this. Should we have two projects? Have one project with different views? Share the same views for the same components?
Appreciate your time!

A: How you organize your components is a bit of personal preference.
You don't need to organize by platform, however. Just name your components like so:
MyComponent.android.js
MyComponent.ios.js

React Native will automatically pick the right version of the component for each platform.

A: I think it should be one project. Here is my project structure:

*

*/app/common/

*

*commonComponent1.js

*commonComponent2.js

*/app/ios/

*

*iosComponent1.js

*iosComponent2.js

*/app/android/

*

*androidComponent1.js

*androidComponent2.js

React-Native has %70-%80 code sharing for both platforms. Therefore you should one project and reuse common components for ios and android.


text:
Q: Jquery extend() merges anonymous objects but doesn't merge instances of my classes This works fine:
.extend(true, {}, { name: "john doe", age: 20, address: {street:"aaa", number:"bbb"} }, { gender: "M", address: {} })

But when address is a class then the second address overrides the first one instead of merging them.
function Address(data) {
    this.data = data;
}

$.extend(true, {}, { name: "john doe", age: 20, address: new Address({street:"aaa", number:"bbb"}) }, { gender: "M", address: new Address({}) })

Is that a bug or an expected behavior of jQuery? How do I merge two instances of a class?

A: To add to the other answer, you could try to convert it to a plain object, although I'm not sure if this is the right approach, but it should work:
function Person(name) {
  this.name = name;
}

Person.prototype.say = function() {
  return this.name + ' says hello!';
};

var toPlainObject = function(x) {
  var obj = Object.create(null);
  for (var i in x) obj[i] = x[i];
  return obj;
};

// false
// Person {name: 'John', say: function}
$.isPlainObject(new Person('John'));
// true
// Object {name: 'John', say: function}
$.isPlainObject(toPlainObject(new Person('John')));

A: jQuery.extend always copies from right to left. The second overrides the first, and the third overrides the second. Therefore, the property value of address from the third of course overrides the property value of the second. It doesn't merge deeper than that because the property value of address fails the jQuery.isPlainObject() test.
function Address(data) {
    this.data = data;
}

console.log( jQuery.isPlainObject(new Address()) ); // false

if Address instead returned a plain object, this wouldn't happen.
function Address(data) {
    var obj = {};
    obj.data = data;
    return obj;
}

console.log( jQuery.isPlainObject(Address()) ); // false


text:
Q: Add error message to CustomValidator I'm tring to add an error message to a CustomValidator by catching a potentail script attack implementing IHttpHandler im using the below method, but it just seems to kill the page as the page ends up blank, any ideas?
public override void ProcessRequest(HttpContext context)
    {
        try
        {
            base.ProcessRequest(context);
        }
        catch (HttpRequestValidationException ex)
        {
           DisplayCustomMessageInValidationSummary("< or > characters are not allowed");
        }
    }

private void DisplayCustomMessageInValidationSummary(string message)
{

    CustomValidator CustomValidatorCtrl = new CustomValidator();
    CustomValidatorCtrl.IsValid = false;
    CustomValidatorCtrl.ErrorMessage = message;
    this.Page.Controls.Add(CustomValidatorCtrl);

}

Thanks
Darren


text:
Q: Passing argument to enum abstract method I need to give a Factory of search properties (as part of the Strategy OOP principle).
I've written the following enum for the choices:
    public enum CompareChoice {
    ABS {
        public Path compare(Path path1, Path path2) {
            return absCompare(path1, path2);
        }
    },

    TYPE {
        public Path compare(Path path1, Path path2) {
            String type1 = getFileType(path1);
            String type2 = getFileType(path2);
            int compareValue = type1.compareTo(type2);
            if (compareValue == 0) {
                return absCompare(path1, path2);
            }

            if (compareValue > 0) {
                return path1;
            }

            return path2;
        }

    },

    SIZE {
        public Path compare(Path path1, Path path2) throws IOException {
            Long size1 = Files.size(path1);
            Long size2 = Files.size(path2);
            int compareValue = size1.compareTo(size2);
            if (compareValue == 0) {
                return absCompare(path1, path2);
            }

            if (compareValue > 0) {
                return path1;
            }

            return path2;
        }
    };

    public abstract Path compare(Path path1, Path path2) throws IOException;
}

The problem I face is that I need to support reverse sorting (of all three choices).
I thought of passing a boolean argument somehow to these implementations of compare but I have no idea how.
Any ideas of how to implement this well by still using an enum would be very helpful!

A: Since Java 8, java.util.Comparator<T> has a default method reversed() that you can use.
You can make your enum implement Comparator, then you get reverse sort "for free", but that means changing signature of compare to fit the Comparator contract (you'll need to think of another name for the method, in my example I'll name it select;
Taking just one of your enum values to keep it short:
public enum CompareChoice implements Comparator<Path> {

  SIZE {
    @Override
    public int compare(Path path1, Path path2) {
      int r = Long.compare(
        Files.size(path1),
        Files.size(path2)
      );
      if (r == 0) {
        return absCompare(path1, path2);
      }
      else {
        return r;
      }
    }
  };

  // rest of the methods:
  public static Path select(Comparator<? super Path> rule, Path path1, Path path2) {
    return rule.compare(path1, path2) <= 0 ? path1 : path2;
  }
}

So then, when you use the class instance:
CompareChoice choice = CompareChoice.SIZE;

Path path1 = fileOfSize(1, TB);
Path path2 = fileOfSize(3, TB);

Path naturalOrderResult = CompareChoice.select(choice, path1, path2);
Path reversedOrderResult = CompareChoice.select(choice.reversed(), path1, path2);

assert path1 == naturalOrderResult;
assert path2 == reversedOrderResult;

You can look at other default methods in comparator to check out other stuff you also get from implementing Comparator<T>, though most of it might be of not much use to you.
You might also consider refactoring it as a whole, so your CompareChoice might not be a "true" comparator, but instead returns a comparator. That way you get better separation of concerns with comparator implementation:
public enum CompareChoice {
  ABS {
    public Comparator<? extends Path> comparator() {
      return Comparator.comparing(this::absCompare); // whatever absCompare means
    }
  },

  SIZE {
    public Comparator<? extends Path> comparator() {
      return Comparator.comparingLong(Files::size).thenComparing(ABS.comparator());
    }
  };

  public abstract Comparator<? extends Path> comparator();
}


text:
Q: React-Native State Dynamic Color I want to set the tintColor of my png Image dynamic. Currently I try to set the color via the state property and change the value with setState
My code is something like this (Expect that everything works fine above and around the following code snippet):
class dynamicImageColor extends Component{
  constructor(props) {
    super(props);
    this.state = {
      myDynamicColor: '#ffffff'
    }
  }

  changeColor(bool) {
    this.setState({
      myDynamicColor: bool ? '#932727' : '#ffffff';
    })
  }

  render(){
    return(
      <Image source={myPNGImage} style={styles.PNGImageStyle}/>
    )
  }
}

var styles = StyleSheet.create({
  PNGImageStyle: {
    tintColor: this.state.myDynamicColor,
    width: 25,
    height: 25
  }
}

Everything in the code above is working fine if i set the tintColor static. And the function changeColor(bool) is called in some other place which is not relevant and works fine.
My actual problem is that i get the error message:
undefined is not an object(evaluating'this.state.myDynamicColor
I also wanted to see if there are wrong values transported anyhow. But the console showed the right '#ffffff' hex_code format at the myDynamicColor
I dont know further and help would be very nice. Also i would be glad if you show me a better solution :)
Thank you
BR
Jonathan

A: There are a few issues here. First your styles var can't use this because it's not part of the class. Second the value of tintColor would not be automatically updated. render() would always use the same styles variable.
What you want to do is this (notice the square brackets):
render() {
  return (
    <Image source={myPNGImage} style={[styles.PNGImageStyle, {tintColor: this.state.myDynamicColor}]}/>
  );
}

and
var styles = StyleSheet.create({
  PNGImageStyle: {
    width: 25,
    height: 25
  }
  ...
});

A: Pass the props to the component and use them in props of image component like below :
<Image
    style={{
        tintColor: props.color,
        resizeMode: "contain",
        height: 100,
        width: 200
    }}
    source={require(props.imageSrc)}
/>


text:
Q: How can I center text for a label being printed on a Zebra ZXP Series 3 Card? I am printing Cards on a Zebra ZXP Series 3 Card Printer.
I am using their provided SDK from here.
The card is 86mm x 54 mm
Maximum Resolution: 300 dpi
The code for me to produce text to be printed on the card goes a little something like this:
// text to draw details
DrawConfiguration firstnameConfiguration = new DrawConfiguration();

firstnameConfiguration.StringLabelText = "Johnny Appleseed";
firstnameConfiguration.LabelLocation = new Point(1, 350);

// zebra graphics thing
ZBRGraphics graphics = null;
graphics = new ZBRGraphics();

// font style
int fontStyle = FONT_BOLD;

// Draw First Name Text
if (graphics.DrawText(fn.LabelLocation.X, fn.LabelLocation.Y, graphics.AsciiEncoder.GetBytes(fn.StringLabelText), graphics.AsciiEncoder.GetBytes("Arial"), 12, fontStyle, 0x000000, out errorValue) == 0)
{
    errorMessages += "\nPrinting DrawText [First Name] Error: " + errorValue.ToString();
    noErrors = false;
}

then, DrawText looks like this:
public int DrawText(int x, int y, byte[] text, byte[] font, int fontSize, int fontStyle, int textColor, out int errValue)
{
    return ZBRGDIDrawText(x, y, text, font, fontSize, fontStyle, textColor, out errValue);
}

[DllImport("ZBRGraphics.dll", EntryPoint = "ZBRGDIDrawText", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int ZBRGDIDrawText(int x, int y, byte[] text, byte[] font, int fontSize, int fontStyle, int color, out int err);

How can I center text on the Card using their SDK?

The only way I can figure out how to do it now is by "padding" the text with spaces". For example, "     Johnny Appleseed       " will look like this after padding and may kind of look centered, but not really. Is there a generic formula where I can calculate how to center this text on the card based on the card dimensions/dpi?

A: After hours of fighting with the text alignment I finally got a response from Zebra. You have to use the DrawTextEx() method and pass it in the alignment parameter. (Note this method is not provided in the SDK but it does exist in the DLL! You need to add it in your application to get it to work)
3 = left justified
4 = center justified
5 = right justified
Add this code to the ZBRGraphics.cs file
[DllImport("ZBRGraphics.dll", EntryPoint = "ZBRGDIDrawTextEx", CharSet = CharSet.Auto,

    SetLastError = true)]

static extern int ZBRGDIDrawTextEx(int x, int y, int angle, int alignment, byte[] text, byte[] font, int fontSize, int fontStyle, int color, out int err);

public int DrawTextEx(int x, int y, int angle, int alignment, byte[] text, byte[] font, int fontSize, int fontStyle, int color, out int err)

{

    return ZBRGDIDrawTextEx(x, y, angle, alignment, text, font, fontSize, fontStyle, color, out err);

}

Here is how to use it in your application.
How to use it (from the "SDK Manual"):
int x = 0;

int y = 0;

int angle = 0; //0 degrees rotation (no rotation)

int alignment = 4; //center justified

string TextToPrint = "Printed Text";

byte[] text = null;

string FontToUse = "Arial";

byte[] font = null;

int fontSise = 12;

int fontStyle = 1; //bold

int color = 0x0FF0000; //black

int err = 0;

int result = 0;

//use the function:

System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();

text = ascii.GetBytes(TextToPrint);

font = ascii.GetBytes(FontToUse);

result = ZBRGDIDrawTextEx(x, y, angle, alignment, text, font, fontSize,fontStyle, color, out err);


text:
Q: Passenger doesn't seem to be running (Capistrano/Rails/Apache/Ubuntu) Deploying a Rails app using Capistrano to an Ubuntu VM running Apache with Passenger enabled.
I followed this tutorial: https://www.phusionpassenger.com/library/install/apache/install/oss/trusty/ with a few changes given that I'm on 17.04, not 14.04 LTS.
passenger-config validate-install says everything looks fine with both Passenger and Apache. passenger-memory-stats shows both Passenger and Apache processes.
I have sudo apache2ctl restarted several times, with no warnings. But passenger-status, and therefore the passenger-config restart-app that Capistrano runs, reports that Passenger "doesn't seem to be running." So my deploy stops.
There's only one Ruby on the machine, ruby-2.4.1 installed using ruby-install. I have apt-get update and upgraded in case of version mismatches.
Apache logs don't show any errors, certainly none related to Passenger.
Why would Passenger internally disagree, saying that it's both configured properly and there are processes running, but then later saying that it's not running?

A: I needed to customize the instance registry directory, as suggested by Tony Vincent:
/etc/apache2/mods-enabled/passenger.conf on the server:
PassengerInstanceRegistryDir /home/MYUSER/passenger_temp

config/deploy/production.rb in the Rails app:
set :default_env, { 'PASSENGER_INSTANCE_REGISTRY_DIR' => '/home/MYUSER/passenger_temp' }

A: Sorry to harp on this but did you run passenger-config validate-install on the ubuntu server (not osx)? Same for passenger-memory-stats and sudo apache2ctl restart.
Based on /tmp not having a passenger.randomstring dir, it sounds like you are confusing local and remote commands. /tmp is the default location for PassengerInstanceRegistryDirs on Ubuntu so if Passenger is running there should be a dir in /tmp that starts with passenger..


text:
Q: PYSVN: how to set local working folder so I can commit a file? After I get the pysvn client, how can I set the working folder to a specific local working folder belonging to a specific repo?
I'd like to set the working folder so i can then commit changes from there.
I have tried passing in the path to the client but that doesn't work.

A: The simplest way to call pysvn.Client().checkin() is with the absolute path to the working copy top folder. You should then see from svn log that all the changed files where committed.
By using an absolute path you avoid issues with the current working directory and relative paths.
If this does not help post details of the error message you receive, the version of python, the version of pysvn and your operating system.


text:
Q: String Subsequence Matching Given an array of string words, please design a string subsequence matcher.
Implement the SubsequenceMatcher class:

*

*SubsequenceMatcher(string words[]): Initializes the object with a pattern array words, and an empty string s.

*bool addChar(char c): Add a character c to the end of the string s. Return true if at least one string in words is a subsequence of s, false otherwise.

Example:
words = ["abc", "bd", "ace"]
addChar('a') -> false // a
addChar('d') -> false // ad
addChar('b') -> false // adb
addChar('e') -> false // adbe
addChar('c') -> true // adbec, include a subsequence abc

The aim is to minimize the cost of each call to addChar. I find a similar problem leetcode 795, the solution is O(n) for an addChar call, where n is the length of words. Is there a more efficient algorithm?

A: I'm pretty sure the short answer is no, you can't be better than O(n).
Although the simple solution below can be improved:

*

*Have a pointer for each word that points to the first character.

*When addChar is called compare with each pointer (i.e. the character it is pointing to) and if it matches move the pointer one step further. If the end of a word is/was reached return true otherwise false.

Improvements:

*

*Have a variable that tells you if a word was completed and return always true afterwards without doing anything.

*Have a map with next char as key and a list or set with the words and pointers as value. Like this you only have to update the words for the given character and then put them at their new location.

*Preprocess the words and eliminate all the words containing a subsequence of another word.

Here is an alternative algorithm that could be better or worse:

*

*Construct a trie.

*Have a map with the next character as key and a list of trie nodes as value.

*For every edge of the root: put the root in the map (the edge i.e. the character it is pointing to is the key and the root is added to the corresponding list).

*When addChar is called go through the corresponding list and for each node remove it from the list, replace it with the child corresponding to the character and put it in all the lists its pointing to (same as we've done with the root).

*If the end of a word is reached return true (always from then on) otherwise false.


text:
Q: Find last used cell in Excel VBA When I want to find the last used cell value, I use:
Dim LastRow As Long

LastRow = Range("E4:E48").End(xlDown).Row

Debug.Print LastRow

I'm getting the wrong output when I put a single element into a cell. But when I put more than one value into the cell, the output is correct.
What's the reason behind this?

A: I would add to the answer given by Siddarth Rout to say that the CountA call can be skipped by having Find return a Range object, instead of a row number, and then test the returned Range object to see if it is Nothing (blank worksheet).
Also, I would have my version of any LastRow procedure return a zero for a blank worksheet, then I can know it is blank.

A: I wonder that nobody has mentioned this, But the easiest way of getting the last used cell is:
Function GetLastCell(sh as Worksheet) As Range
    GetLastCell = sh.Cells(1,1).SpecialCells(xlLastCell)
End Function

This essentially returns the same cell that you get by Ctrl + End after selecting Cell A1.
A word of caution: Excel keeps track of the most bottom-right cell that was ever used in a worksheet. So if for example you enter something in B3 and something else in H8 and then later on delete the contents of H8, pressing Ctrl + End will still take you to H8 cell. The above function will have the same behavior.

A: Updated at End of 2021
With Excel's new calculation engine and array functionality, and Filter Function, I believe this topic should now be far less contested and that the below options offer the best mix of speed, reliability, and simplicity (which has proven difficult to balance in the past as the numerous posts here illustrate).
Also, I'm defining last used as NOT blank as defined by the isBlank function.
Excel Formula
First, note that the Filter Function makes it much simpler to get a last cell using the below formulas for a specific row or column (in these case Column A or Row 1):
=MAX(FILTER(ROW(A:A),NOT(ISBLANK(A:A))))
=MAX(FILTER(COLUMN(1:1),NOT(ISBLANK(1:1))))

VBA Function For Last Row Specific Range
Using the above function we can convert it into a VBA function, yet make it even faster by limiting the range, while expanding its capabilities by doing multiple columns (thanks to Chris Neilsen for immediate feedback tweeking/suggestions). I also found massive speed improvement by scoping each column to only be a range with a row HIGHER than the previous last row.
Function FindLastRowInRange(someColumns As Range) As Long
Const zFx = "=MAX(FILTER(ROW(????),NOT(ISBLANK(????)),0))"

   Dim tRng As Range, i As Long, tRow As Long, pRng As Range
   With someColumns.Worksheet
      Set tRng = Intersect(someColumns.EntireColumn, .UsedRange)

      For i = 1 To tRng.Columns.Count

         Set pRng = Intersect(tRng.Columns(i), _
         Range(.Rows(FindLastRowInRange + 1), .Rows(.Rows.Count)))

         If Not pRng Is Nothing Then
            tRow = .Evaluate(Replace(zFx, "????", _
               pRng.Address, 1, -1))

            If tRow > FindLastRowInRange Then _
               FindLastRowInRange = tRow

         End If
      Next i
   End With
End Function

VBA Function For Last Row In Worksheet
To consider the entire worksheet (all columns), I would recommend using a different VBA formula that references the prior one, but is a Volatile Function. This ensures that the formula updates with any changes to a worksheet. Obviously, one could combine these two formulas, but I prefer to limit the usage of volatile functions.
Function FindLastRowInSheet(anywhereInSheet As Range) As Long
      Application.Volatile
      FindLastRowInSheet = FindLastRowInRange(anywhereInSheet.Worksheet.UsedRange)
End Function

Advantages Compared To Other Options

*

*Allows for some or ALL rows/columns in worksheet without changing approach.

*No possibility of missing hidden rows as is a risk with xlup

*Ignores formatted/usedrange issues.

*Does not interfere with user's Find settings.

*Uses worksheet functionality which is faster than VBA calcs.

*No counting cells (performance hog).

Hopefully this ends the debate, but if anyone finds weaknesses in this please share.

A: Note: this answer was motivated by this comment. The purpose of UsedRange is different from what is mentioned in the answer above.
As to the correct way of finding the last used cell, one has first to decide what is considered used, and then select a suitable method. I conceive at least three meanings:

*

*Used = non-blank, i.e., having data.

*Used = "... in use, meaning the section that contains data or formatting."
As per official documentation, this is the criterion used by Excel at the time of saving. See also this official documentation.
If one is not aware of this, the criterion may produce unexpected results, but it may also be intentionally exploited (less often, surely), e.g., to highlight or print specific regions, which may eventually have no data.
And, of course, it is desirable as a criterion for the range to use when saving a workbook, lest losing part of one's work.

*Used = "... in use, meaning the section that contains data or formatting" or conditional formatting.
Same as 2., but also including cells that are the target for any Conditional Formatting rule.
How to find the last used cell depends on what you want (your criterion).
For criterion 1, I suggest reading this answer.
Note that UsedRange is cited as unreliable. I think that is misleading (i.e., "unfair" to UsedRange), as UsedRange is simply not meant to report the last cell containing data. So it should not be used in this case, as indicated in that answer. See also this comment.
For criterion 2, UsedRange is the most reliable option, as compared to other options also designed for this use. It even makes it unnecessary to save a workbook to make sure that the last cell is updated.
Ctrl+End will go to a wrong cell prior to saving
("The last cell is not reset until you save the worksheet", from
http://msdn.microsoft.com/en-us/library/aa139976%28v=office.10%29.aspx.
It is an old reference, but in this respect valid).
For criterion 3, I do not know any built-in method.
Criterion 2 does not account for Conditional Formatting. One may have formatted cells, based on formulas, which are not detected by UsedRange or Ctrl+End.
In the figure, the last cell is B3, since formatting was applied explicitly to it. Cells B6:D7 have a format derived from a Conditional Formatting rule, and this is not detected even by UsedRange.
Accounting for this would require some VBA programming.

As to your specific question:
What's the reason behind this?
Your code uses the first cell in your range E4:E48 as a trampoline, for jumping down with End(xlDown).
The "erroneous" output will obtain if there are no non-blank cells in your range other than perhaps the first. Then, you are leaping in the dark, i.e., down the worksheet
(you should note the difference between blank and empty string!).
Note that:

*

*If your range contains non-contiguous non-blank cells, then it will also give a wrong result.

*If there is only one non-blank cell, but it is not the first one, your code will still give you the correct result.

A: NOTE: I intend to make this a "one stop post" where you can use the Correct way to find the last row. This will also cover the best practices to follow when finding the last row. And hence I will keep on updating it whenever I come across a new scenario/information.

Unreliable ways of finding the last row
Some of the most common ways of finding last row which are highly unreliable and hence should never be used.

*

*UsedRange

*xlDown

*CountA

UsedRange should NEVER be used to find the last cell which has data. It is highly unreliable. Try this experiment.
Type something in cell A5. Now when you calculate the last row with any of the methods given below, it will give you 5. Now color the cell A10 red. If you now use the any of the below code, you will still get 5. If you use Usedrange.Rows.Count what do you get? It won't be 5.
Here is a scenario to show how UsedRange works.

xlDown is equally unreliable.
Consider this code
lastrow = Range("A1").End(xlDown).Row

What would happen if there was only one cell (A1) which had data? You will end up reaching the last row in the worksheet! It's like selecting cell A1 and then pressing End key and then pressing Down Arrow key. This will also give you unreliable results if there are blank cells in a range.
CountA is also unreliable because it will give you incorrect result if there are blank cells in between.
And hence one should avoid the use of UsedRange, xlDown and CountA to find the last cell.

Find Last Row in a Column
To find the last Row in Col E use this
With Sheets("Sheet1")
    LastRow = .Range("E" & .Rows.Count).End(xlUp).Row
End With

If you notice that we have a . before Rows.Count. We often chose to ignore that. See THIS question on the possible error that you may get. I always advise using . before Rows.Count and Columns.Count. That question is a classic scenario where the code will fail because the Rows.Count returns 65536 for Excel 2003 and earlier and 1048576 for Excel 2007 and later. Similarly Columns.Count returns 256 and 16384, respectively.
The above fact that Excel 2007+ has 1048576 rows also emphasizes on the fact that we should always declare the variable which will hold the row value as Long instead of Integer else you will get an Overflow error.
Note that this approach will skip any hidden rows. Looking back at my screenshot above for column A, if row 8 were hidden, this approach would return 5 instead of 8.

Find Last Row in a Sheet
To find the Effective last row in the sheet, use this. Notice the use of Application.WorksheetFunction.CountA(.Cells). This is required because if there are no cells with data in the worksheet then .Find will give you Run Time Error 91: Object Variable or With block variable not set
With Sheets("Sheet1")
    If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
        lastrow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Row
    Else
        lastrow = 1
    End If
End With

Find Last Row in a Table (ListObject)
The same principles apply, for example to get the last row in the third column of a table:
Sub FindLastRowInExcelTableColAandB()
Dim lastRow As Long
Dim ws As Worksheet, tbl as ListObject
Set ws = Sheets("Sheet1")  'Modify as needed
'Assuming the name of the table is "Table1", modify as needed
Set tbl = ws.ListObjects("Table1")

With tbl.ListColumns(3).Range
    lastrow = .Find(What:="*", _
                After:=.Cells(1), _
                Lookat:=xlPart, _
                LookIn:=xlFormulas, _
                SearchOrder:=xlByRows, _
                SearchDirection:=xlPrevious, _
                MatchCase:=False).Row
End With

End Sub

A: sub last_filled_cell()
msgbox range("A65536").end(xlup).row
end sub

Here, A65536 is the last cell in the Column A this code was tested on excel 2003.

A: However this question is seeking to find the last row using VBA, I think it would be good to include an array formula for worksheet function  as this gets visited frequently:
{=ADDRESS(MATCH(INDEX(D:D,MAX(IF(D:D<>"",ROW(D:D)-ROW(D1)+1)),1),D:D,0),COLUMN(D:D))}

You need to enter the formula without brackets and then hit Shift + Ctrl + Enter to make it an array formula.
This will give you address of last used cell in the column D.

Thanks to pgsystemtester, this will give you the row number of last used cell:
{=MATCH(INDEX(D:D,MAX(IF(D:D<>"",ROW(D:D)-ROW(D1)+1)),1),D:D,0)}

A: I created this one-stop function for determining the last row, column and cell, be it for data, formatted (grouped/commented/hidden) cells or conditional formatting.
Sub LastCellMsg()
    Dim strResult As String
    Dim lngDataRow As Long
    Dim lngDataCol As Long
    Dim strDataCell As String
    Dim strDataFormatRow As String
    Dim lngDataFormatCol As Long
    Dim strDataFormatCell As String
    Dim oFormatCond As FormatCondition
    Dim lngTempRow As Long
    Dim lngTempCol As Long
    Dim lngCFRow As Long
    Dim lngCFCol As Long
    Dim strCFCell As String
    Dim lngOverallRow As Long
    Dim lngOverallCol As Long
    Dim strOverallCell As String

    With ActiveSheet

        If .ListObjects.Count > 0 Then
            MsgBox "Cannot return reliable results, as there is at least one table in the worksheet."
            Exit Sub
        End If

        strResult = "Workbook name: " & .Parent.Name & vbCrLf
        strResult = strResult & "Sheet name: " & .Name & vbCrLf

        'DATA:
        'last data row
        If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
            lngDataRow = .Cells.Find(What:="*", _
             After:=.Range("A1"), _
             Lookat:=xlPart, _
             LookIn:=xlFormulas, _
             SearchOrder:=xlByRows, _
             SearchDirection:=xlPrevious, _
             MatchCase:=False).Row
        Else
            lngDataRow = 1
        End If
        'strResult = strResult & "Last data row: " & lngDataRow & vbCrLf

        'last data column
        If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
            lngDataCol = .Cells.Find(What:="*", _
             After:=.Range("A1"), _
             Lookat:=xlPart, _
             LookIn:=xlFormulas, _
             SearchOrder:=xlByColumns, _
             SearchDirection:=xlPrevious, _
             MatchCase:=False).Column
        Else
            lngDataCol = 1
        End If
        'strResult = strResult & "Last data column: " & lngDataCol & vbCrLf

        'last data cell
        strDataCell = Replace(Cells(lngDataRow, lngDataCol).Address, "$", vbNullString)
        strResult = strResult & "Last data cell: " & strDataCell & vbCrLf

        'FORMATS:
        'last data/formatted/grouped/commented/hidden row
        strDataFormatRow = StrReverse(Split(StrReverse(.UsedRange.Address), "$")(0))
        'strResult = strResult & "Last data/formatted row: " & strDataFormatRow & vbCrLf

        'last data/formatted/grouped/commented/hidden column
        lngDataFormatCol = Range(StrReverse(Split(StrReverse(.UsedRange.Address), "$")(1)) & "1").Column
        'strResult = strResult & "Last data/formatted column: " & lngDataFormatCol & vbCrLf

        'last data/formatted/grouped/commented/hidden cell
        strDataFormatCell = Replace(Cells(strDataFormatRow, lngDataFormatCol).Address, "$", vbNullString)
        strResult = strResult & "Last data/formatted cell: " & strDataFormatCell & vbCrLf

        'CONDITIONAL FORMATS:
        For Each oFormatCond In .Cells.FormatConditions

            'last conditionally-formatted row
            lngTempRow = CLng(StrReverse(Split(StrReverse(oFormatCond.AppliesTo.Address), "$")(0)))
            If lngTempRow > lngCFRow Then lngCFRow = lngTempRow

            'last conditionally-formatted column
            lngTempCol = Range(StrReverse(Split(StrReverse(oFormatCond.AppliesTo.Address), "$")(1)) & "1").Column
            If lngTempCol > lngCFCol Then lngCFCol = lngTempCol
        Next
        'no results are returned for Conditional Format if there is no such
        If lngCFRow <> 0 Then
            'strResult = strResult & "Last cond-formatted row: " & lngCFRow & vbCrLf
            'strResult = strResult & "Last cond-formatted column: " & lngCFCol & vbCrLf

            'last conditionally-formatted cell
            strCFCell = Replace(Cells(lngCFRow, lngCFCol).Address, "$", vbNullString)
            strResult = strResult & "Last cond-formatted cell: " & strCFCell & vbCrLf
        End If

        'OVERALL:
        lngOverallRow = Application.WorksheetFunction.Max(lngDataRow, strDataFormatRow, lngCFRow)
        'strResult = strResult & "Last overall row: " & lngOverallRow & vbCrLf
        lngOverallCol = Application.WorksheetFunction.Max(lngDataCol, lngDataFormatCol, lngCFCol)
        'strResult = strResult & "Last overall column: " & lngOverallCol & vbCrLf
        strOverallCell = Replace(.Cells(lngOverallRow, lngOverallCol).Address, "$", vbNullString)
        strResult = strResult & "Last overall cell: " & strOverallCell & vbCrLf

        MsgBox strResult
        Debug.Print strResult

    End With

End Sub

Results look like this:

For more detailed results, some lines in the code can be uncommented:

One limitation exists - if there are tables in the sheet, results can become unreliable, so I decided to avoid running the code in this case:
If .ListObjects.Count > 0 Then
    MsgBox "Cannot return reliable results, as there is at least one table in the worksheet."
    Exit Sub
End If

A: I was looking for a way to mimic the CTRL+Shift+End, so dotNET solution is great, except with my Excel 2010 I need to add a set if I want to avoid an error:
Function GetLastCell(sh As Worksheet) As Range
  Set GetLastCell = sh.Cells(1, 1).SpecialCells(xlLastCell)
End Function

and how to check this for yourself:
Sub test()
  Dim ws As Worksheet, r As Range
  Set ws = ActiveWorkbook.Sheets("Sheet1")
  Set r = GetLastCell(ws)
  MsgBox r.Column & "-" & r.Row
End Sub

A: One important note to keep in mind when using the solution ...
LastRow = ws.Cells.Find(What:="*", After:=ws.range("a1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

... is to ensure that your LastRow variable is of Long type:
Dim LastRow as Long

Otherwise you will end up getting OVERFLOW errors in certain situations in .XLSX workbooks
This is my encapsulated function that I drop in to various code uses.
Private Function FindLastRow(ws As Worksheet) As Long
    ' --------------------------------------------------------------------------------
    ' Find the last used Row on a Worksheet
    ' --------------------------------------------------------------------------------
    If WorksheetFunction.CountA(ws.Cells) > 0 Then
        ' Search for any entry, by searching backwards by Rows.
        FindLastRow = ws.Cells.Find(What:="*", After:=ws.range("a1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    End If
End Function

A: Since the original question is about problems with finding the last cell, in this answer I will list the various ways you can get unexpected results; see my answer to "How can I find last row that contains data in the Excel sheet with a macro?" for my take on solving this.
I'll start by expanding on the answer by sancho.s and the comment by GlennFromIowa, adding even more detail:

[...] one has first to decide what is considered used. I see at least 6 meanings. Cell has:

*

*1) data, i.e., a formula, possibly resulting in a blank value;

*2) a value, i.e., a non-blank formula or constant;

*3) formatting;

*4) conditional formatting;

*5) a shape (including Comment) overlapping the cell;

*6) involvement in a Table (List Object).

  Which combination do you want to test for? Some (such as Tables) may be more difficult to test for, and some may be rare (such as a shape outside of data range),  but others may vary based on the situation (e.g., formulas with blank values).

Other things you might want to consider:

*

*A) Can there be hidden rows (e.g. autofilter), blank cells or blank rows?

*B) What kind of performance is acceptable?

*C) Can the VBA macro affect the workbook or the application settings in any way?

With that in mind, let's see how the common ways of getting the "last cell" can produce unexpected results:

*

*The .End(xlDown) code from the question will break most easily (e.g. with a single non-empty cell or when there are blank cells in between) for the reasons explained in the answer by Siddharth Rout here (search for "xlDown is equally unreliable.")

*Any solution based on Counting (CountA or Cells*.Count) or .CurrentRegion will also break in presence of blank cells or rows

*A solution involving .End(xlUp) to search backwards from the end of a column will, just as CTRL+UP, look for data (formulas producing a blank value are considered "data") in visible rows (so using it with autofilter enabled might produce incorrect results ⚠). You have to take care to avoid the standard pitfalls (for details I'll again refer to the answer by Siddharth Rout here, look for the "Find Last Row in a Column" section), such as hard-coding the last row (Range("A65536").End(xlUp)) instead of relying on sht.Rows.Count.

*.SpecialCells(xlLastCell) is equivalent to CTRL+END, returning the bottom-most and right-most cell of the "used range", so all caveats that apply to relying on the "used range", apply to this method as well. In addition, the "used range" is only reset when saving the workbook and when accessing worksheet.UsedRange, so xlLastCell might produce stale results⚠ with unsaved modifications (e.g. after some rows were deleted). See the nearby answer by dotNET.

*sht.UsedRange (described in detail in the answer by sancho.s here) considers both data and formatting (though not conditional formatting) and resets the "used range" of the worksheet, which may or may not be what you want.Note that a common mistake is to use .UsedRange.Rows.Count⚠, which returns the number of rows in the used range, not the last row number (they will be different if the first few rows are blank), for details see newguy's answer to How can I find last row that contains data in the Excel sheet with a macro?

*.Find allows you to find the last row with any data (including formulas) or a non-blank value in any column. You can choose whether you're interested in formulas or values, but the catch is that it resets the defaults in the Excel's Find dialog ⚠, which can be highly confusing to your users. It also needs to be used carefully, see the answer by Siddharth Rout here (section "Find Last Row in a Sheet")

*More explicit solutions that check individual Cells' in a loop are generally slower than re-using an Excel function (although can still be performant), but let you specify exactly what you want to find. See my solution based on UsedRange and VBA arrays to find the last cell with data in the given column -- it handles hidden rows, filters, blanks, does not modify the Find defaults and is quite performant.

Whatever solution you pick, be careful

*

*to use Long instead of Integer to store the row numbers (to avoid getting Overflow with more than 65k rows) and

*to always specify the worksheet you're working with (i.e. Dim ws As Worksheet ... ws.Range(...) instead of Range(...))

*when using .Value (which is a Variant) avoid implicit casts like .Value <> "" as they will fail if the cell contains an error value.

A: Sub lastRow()

    Dim i As Long
        i = Cells(Rows.Count, 1).End(xlUp).Row
            MsgBox i

End Sub

sub LastRow()

'Paste & for better understanding of the working use F8 Key to run the code .

dim WS as worksheet
dim i as long

set ws = thisworkbook("SheetName")

ws.activate

ws.range("a1").select

ws.range("a1048576").select

activecell.end(xlup).select

i= activecell.row

msgbox "My Last Row Is " & i

End sub

A: For the last 3+ years these are the functions that I am using for finding last row and last column per defined column(for row) and row(for column):
Last Column:
Function lastCol(Optional wsName As String, Optional rowToCheck As Long = 1) As Long

    Dim ws  As Worksheet

    If wsName = vbNullString Then
        Set ws = ActiveSheet
    Else
        Set ws = Worksheets(wsName)
    End If

    lastCol = ws.Cells(rowToCheck, ws.Columns.Count).End(xlToLeft).Column

End Function

Last Row:
Function lastRow(Optional wsName As String, Optional columnToCheck As Long = 1) As Long

    Dim ws As Worksheet

    If wsName = vbNullString Then
        Set ws = ActiveSheet
    Else
        Set ws = Worksheets(wsName)
    End If

    lastRow = ws.Cells(ws.Rows.Count, columnToCheck).End(xlUp).Row

End Function

For the case of the OP, this is the way to get the last row in column E:
Debug.Print lastRow(columnToCheck:=Range("E4:E48").Column)
Last Row, counting empty rows with data:
Here we may use the well-known Excel formulas, which give us the last row of a worksheet in Excel, without involving VBA - =IFERROR(LOOKUP(2,1/(NOT(ISBLANK(A:A))),ROW(A:A)),0)
In order to put this in VBA and not to write anything in Excel, using the parameters for the latter functions, something like this could be in mind:
Public Function LastRowWithHidden(Optional wsName As String, Optional columnToCheck As Long = 1) As Long

    Dim ws As Worksheet

    If wsName = vbNullString Then
        Set ws = ActiveSheet
    Else
        Set ws = Worksheets(wsName)
    End If

    Dim letters As String
    letters = ColLettersGenerator(columnToCheck)
    LastRowWithHidden = ws.Evaluate("=IFERROR(LOOKUP(2,1/(NOT(ISBLANK(" & letters & "))),ROW(" & letters & " )),0)")

End Function

Function ColLettersGenerator(col As Long) As String

    Dim result As Variant
    result = Split(Cells(1, col).Address(True, False), "$")
    ColLettersGenerator = result(0) & ":" & result(0)

End Function

A: Last Row in a regular range or a Table (ListObject)

*

*Finding the last row requires using different methods if the range is a regular range or table (List Object).

*Finding the last row in tables requires specifying additional parameters (table name , the column relative position to the first tables column).

I created this universal function for last row, regardless of range type. Just give it any cell reference whatsoever and it will return the last row.
No hassle having to knew range characteristics, especially if your ranges are some times a regular range and sometimes a ListObject.
Using a regular range method on a table might return wrong results.
Sure you can plan ahead of time and use the right method each time, but why bother if you can utilizes a universal function ?

Sub RunMyLastRow()
Dim Result As Long
Result = MyLastRow(Worksheets(1).Range("A1"))
End Sub

    Function MyLastRow(RefrenceRange As Range) As Long
    Dim WS As Worksheet
    Dim TableName As String
    Dim ColNumber As Long
    Dim LastRow As Long
    Dim FirstColumnTable As Long
    Dim ColNumberTable As Long
    Set WS = RefrenceRange.Worksheet
    TableName = GetTableName(RefrenceRange)
    ColNumber = RefrenceRange.Column

    ''If the table (ListObject) does not start in column "A" we need to calculate the
    ''first Column table and how many Columns from its beginning the Column is located.
    If TableName <> vbNullString Then
     FirstColumnTable = WS.ListObjects(TableName).ListColumns(1).Range.Column
     ColNumberTable = ColNumber - FirstColumnTable + 1
    End If

    If TableName = vbNullString Then
    LastRow = WS.Cells(WS.Rows.Count, ColNumber).End(xlUp).Row
    Else
    LastRow = WS.ListObjects(TableName).ListColumns(ColNumberTable).Range.Find( _
               What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    End If
    MyLastRow = LastRow
    End Function

    ''Get Table Name by Cell Range
    Function GetTableName(RefrenceRange As Range) As String
        If RefrenceRange.ListObject Is Nothing Then
            GetTableName = vbNullString
        Else
            GetTableName = RefrenceRange.ListObject.Name
        End If
    End Function


text:
Q: How do I install Unix system V? I got my hands on a copy of Unix system V. I downloaded a software to write img files to floppy disks. But when I try to boot from the floppy on my old 128MB ram computer it says disk image failure.  How do I install Unix and is it even possible?

A: Unix System V is from 1983. There is a pretty good chance that the disk image you have is not even for Intel x86 architectures and won't work at all on your system or emulator, let alone other hardware driver incompatibilities. Maybe if you used one of the alternate qemu architectures. But most likely you'd need to get your hands on compatible hardware that still works. There are some youtube videos where people boot these old systems and explorer them a bit.

A: You can find a complete tutorial of how installing AT&T System V/386 (SYSVR4 v 2.1) in Bochs on the www.linuxquestions.org forum. Some paticipants of the forum claim to run it under qemu, VirtualBox and even on an bare bone Pentium 3.
Even if studying System V is a form of computer archeology, it  could still have some historical and technical interest.


text:
Q: OLRE's vs. Beta Binomial Model for Overdispersed Mixed Effect logistic regression with proportion data? this is a long post, as I wanted to be sure to provide all relevant information regarding my data, model, the methods that I have tried so far, and my diagnostic plots. If there are ways I should simplify, please let me know and I will edit for brevity.
I am using lme4::glmer() to fit a binomial generalized linear mixed model with a dependent variable that is proportional rather than binary. My response variable ranges from 0 to 1, with many 0's and a good number of  1's as well (see distribution below).

Data Information:
Briefly, these data represent behavioral observations from 14 individuals. Each individual was observed at 5 minute intervals for multiple days, with observations averaged over 2 hour periods. The response variable is the proportion of observations in each 2 hour period that the individual being observed was performing a behavior of interest, while the predictor variables are treatment (a factor with 2 levels) and temperature (average temperature for that 2 hour period, scaled using the scale function to help with model convergence). The overall goal is to determine whether an experimental treatment influences the relationship between temperature and the proportion time spent performing of the behavior of interest.
Initial Model and Diagnostics:
M1 <- glmer(BehaviorProp ~ TemperatureS * Treatment + (TemperatureS | Individual),
            data = birds, family = binomial(), weights = BehaviorCount)

I am using the DHARMa package to perform model diagnostics (see below). The diagnostic plots for this initial model indicate that the residuals are not uniformly distributed, that I have many outliers, overdispersion, and zero inflation. Given that logistic regression does not assume normally distributed residuals and that 0's are an expected response, I am not sure if I need to be worried about the residual Q-Q plot or the zero inflation plot (if this is incorrect, please let me know!). However, I am concerned about the over dispersion.

My overall question is: What would be the best way to model my data to take care of the overdispersion? Below, I have outlined the methods that I have tried so far (beta-binomial model with zero inflation, binomial model with OLRE). The diagnostic plots for the model with OLRE (included below) look much better than those for the beta-binomial model with zero inflation (also included below); however, I am not sure how much to rely on these plots for comparison, given that the DHARMa package may not be able to appropriately simulate residuals from the beta-binomial model. I am also not sure if, in using an OLRE rather than beta-binomial, I would be falling into the pitfalls outlined in this model by Xavier Harrison.
Being a relative beginner to statistics, I am not sure which of the two methods makes sense for my data. Since I didn't know which method to use, I have done for both. Model specification and diagnostic plots are below:
Observation Level Random Effect Model:
M_olre <- glmer(BehaviorProp ~ TemperatureS * Treatment + (TemperatureS | Individual)
                    + (1 | index), data = birds, family = binomial(),
                weights = BehaviorCount)

This seems to have solved the problem of overdispersion, and the outlier and zero-inflation plots look much better as well. The QQ plot still doesn't look great, but again I'm not sure if I need to pay attention to that, given that uniformly distributed residuals are not necessarily expected in binary models.

Beta Binomial Model:
M_BetaBinom <- glmmTMB(BehaviorProp ~ TemperatureS * CoverType + (TemperatureS | Individual),
                       data=birds, family=beta_family(),
                       weights = PantingCount, ziformula = ~.)

In order for this model to work, I had to change all of the '1' values in my response variable to 0.999. The diagnostics for this model look much worse than those for the OLRE model, but as stated above, I am not sure how much I can trust these because I don't know how well the DHARMa package works on this type of mode. When generating the DHARMa graphs, I received the following warnings:

Model family was recognized or set as continuous, but duplicate values
  were detected in the response. Consider if you are fitting an
  appropriate model. Duplicate non-integer values found in the
  simulation. If this is because you are fitting a non-inter valued
  discrete response model, note that DHARMa does not perform appropriate
  randomization for such cases.

Overall, I am wondering:
Which of these methods make more sense for my data? Is there another method that I have not yet considered that may work better?
I would also gladly accept any input regarding the structure of my models. Do my RE's make sense? Is the ziformula in my beta-binomial model properly specified?
All input is greatly appreciated.


text:
Q: How to convert a string or data into QR Code in Node Js I need to convert user data into a QR Code and show it in the web browser what is the best way to generate QR Code in node js and show it in user browser

A: I think you should look at qrcode library
This is an exemple of basic usage :
var QRCode = require('qrcode')

QRCode.toDataURL('I am a pony!', function (err, url) {
  console.log(url)
});

Hope it helps.

A: You can use this url in image tag like this ->
Example of app.js or index.js file
var QRCode = require('qrcode');
app.get('/', function (req, res) {
 QRCode.toDataURL('I am a pony!', function (err, url) {
  console.log(url)
  res.render('index', {qr: url});
  });
});

In your template: (i am using ejs as my template engine)
<img src="<%= qr %>">

after this you will get qrcode image instead of qrcode data.
i hope this would help you


text:
Q: How does sending an argument that's casted to a pointer to a function that accepts pointer work? Shouldn't I send the ADDRESS of the argument? I understand the way print1 function works, but how come when calling print2 function I don't need to pass the address of the argument but rather I just need to cast it to void pointer? I don't understand how the output is correct. What does it mean when I say (void*)20? And then what does the whole "int n = (int)param inside the print2 function does?
#include <stdio.h>
#include <stdlib.h>

void print1(void* param)
{
    int n = *((int*)param);
    printf("You sent: %d\n", n);
}

void print2(void* param)
{
    int n = (int)param;
    printf("You sent: %d\n", n);
}

int main()
{
    int number = 10;
    print1(&number);

    print2((void*)20);

    return 0;
}

A: (void *)20 converts 20 to a pointer. Per C 2018 6.3.2.3 5, the result is implementation-defined.
print2((void*)20); sends that pointer to print2.
In print2, int n = (int)param; converts that pointer back to int. Per C 2018 6.3.2.3 6, the result is implementation-defined. A common result is that the original integer is restored, provided it has not run afoul of limitations or complications in the addressing mechanism used in the C implementation.
printf("You sent: %d\n", n); sends this restored int to printf.


text:
Q: Unit testing a snake game I need help with a test method to see if the snake is/or isn't moving in the right direction, aka "==/!=".
I also need to check if the snake has food on the console or not.
I've tried to call the "starter class" that I have almost all the code in. But I can't try to predict where it will go correctly and assert from there.
How should I go about doing so?  [Only need tips!]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace Snake
{
    /// <summary>
    /// Start class, everything goes from here.
    /// </summary>
   public class Starter : InterF
    {
        public static object Key { get; private set; }

        static void Main(string[] args)
        {

            Console.ForegroundColor = ConsoleColor.Green;
            bool loopC = true;
            while (loopC)
            {
                string mystring = null; Console.WriteLine("Welcome to Snake.\nPress S+Enter to start or press Q+Enter to exit.");
                mystring = Console.ReadLine();
                switch (mystring)
                {
                    case "Q":
                        Environment.Exit(0);
                        break;
                    case "S":
                        Console.WriteLine("Starting game!");
                        System.Threading.Thread.Sleep(4000);
                        loopC = false;
                        break;
                    default:
                        Console.WriteLine("Invalid Entry.. Try again.");
                        break;
                }

            }

            //Call for GameSense if
            //they want to play.
            GameSense();

        }

        /// <summary>
        /// Game object!
        /// </summary>
        public static void GameSense()

        {
            //Game console height/width.
            Console.WindowHeight = 30;
            Console.WindowWidth = 70;
            int screenwidth = Console.WindowWidth;
            int screenheight = Console.WindowHeight;
            Random randomnummer = new Random();
            //Lenght of tail == current score.
            int score = 2;
            int gameover = 0;
            //Gather positions from pixel class.
            pixel positions = new pixel();
            positions.xpos = screenwidth / 2;
            positions.ypos = screenheight / 2;
            positions.Black = ConsoleColor.Red;
            string movement = "RIGHT";
            //Position manegment.
            List<int> xpos = new List<int>();
            List<int> ypos = new List<int>();
            int berryx = randomnummer.Next(0, screenwidth);
            int berryy = randomnummer.Next(0, screenheight);
            //Time manegment.
            DateTime time1 = DateTime.Now;
            DateTime time2 = DateTime.Now;
            string buttonpressed = "no";

            //Draw world from GameWorld.cs.
            GameWorld.DrawBorder(screenwidth, screenheight);

            while (true)
            {
                GameWorld.ClearConsole(screenwidth, screenheight);
                if (positions.xpos == screenwidth - 1 || positions.xpos == 0 || positions.ypos == screenheight - 1 || positions.ypos == 0)
                {
                    gameover = 1;
                }

                Console.ForegroundColor = ConsoleColor.Green;
                if (berryx == positions.xpos && berryy == positions.ypos)
                {
                    score++;
                    berryx = randomnummer.Next(1, screenwidth - 2);
                    berryy = randomnummer.Next(1, screenheight - 2);
                }
                for (int i = 0; i < xpos.Count(); i++)
                {
                    Console.SetCursorPosition(xpos[i], ypos[i]);
                    Console.Write("*");
                    if (xpos[i] == positions.xpos && ypos[i] == positions.ypos)
                    {
                        gameover = 1;
                    }
                }
                if (gameover == 1)
                {
                    break;
                }
                Console.SetCursorPosition(positions.xpos, positions.ypos);
                Console.ForegroundColor = positions.Black;
                Console.Write("*");
                //Food color & position.
                Console.SetCursorPosition(berryx, berryy);
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write("*");
                Console.CursorVisible = false;
                time1 = DateTime.Now;
                buttonpressed = "no";
                while (true)
                {
                    time2 = DateTime.Now;
                    if (time2.Subtract(time1).TotalMilliseconds > 500) { break; }
                    if (Console.KeyAvailable)
                    {
                        ConsoleKeyInfo info = Console.ReadKey(true);

                        if (info.Key.Equals(ConsoleKey.UpArrow) && movement != "DOWN" && buttonpressed == "no")
                        {
                            movement = "UP";
                            buttonpressed = "yes";
                        }
                        if (info.Key.Equals(ConsoleKey.DownArrow) && movement != "UP" && buttonpressed == "no")
                        {
                            movement = "DOWN";
                            buttonpressed = "yes";
                        }
                        if (info.Key.Equals(ConsoleKey.LeftArrow) && movement != "RIGHT" && buttonpressed == "no")
                        {
                            movement = "LEFT";
                            buttonpressed = "yes";
                        }
                        if (info.Key.Equals(ConsoleKey.RightArrow) && movement != "LEFT" && buttonpressed == "no")
                        {
                            movement = "RIGHT";
                            buttonpressed = "yes";
                        }
                    }
                }
                xpos.Add(positions.xpos);
                ypos.Add(positions.ypos);
                switch (movement)
                {
                    case "UP":
                        positions.ypos--;
                        break;
                    case "DOWN":
                        positions.ypos++;
                        break;
                    case "LEFT":
                        positions.xpos--;
                        break;
                    case "RIGHT":
                        positions.xpos++;
                        break;
                }
                if (xpos.Count() > score)
                {
                    xpos.RemoveAt(0);
                    ypos.RemoveAt(0);
                }
            }
            Console.SetCursorPosition(screenwidth / 5, screenheight / 2);
            Console.WriteLine("Game over, Score: " + score);
            Console.SetCursorPosition(screenwidth / 5, screenheight / 2 + 1);
            System.Threading.Thread.Sleep(1000);
            restart();

        }

        /// <summary>
        /// Restarter.
        /// </summary>
        public static void restart()
        {

            string Over = null; Console.WriteLine("\nWould you like to start over? Y/N");
            bool O = true;

            while (O)
            {
                Over = Console.ReadLine();
                switch (Over)
                {
                    case "Y":
                        Console.WriteLine("\nRestarting!");
                        System.Threading.Thread.Sleep(2000);
                        break;
                    case "N":
                        Console.WriteLine("\nThank you for playing!");
                        Environment.Exit(0);
                        break;
                    default:
                        Console.WriteLine("Invalid Entry.. Try again.");
                        break;
                }
            }

        }
        /// <summary>
        /// Set/get pixel position.
        /// </summary>
        class pixel
        {
            public int xpos { get; set; }
            public int ypos { get; set; }
            public ConsoleColor Black { get; set; }
        }
    }
}

using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using Snake;
using System;
using System.Collections.Generic;
using System.Text;

namespace Snake.Tests
{
    [TestClass()]
    public class StarterTests
    {
        [TestMethod()]
        public void test()
        {

        }

    }
}

A: The difficulty you're experiencing is caused mostly because one giant function is basically untestable.
So, you need to split your code. What follows is a list of the things you should consider:

*

*instead of a giant static function, you could create a class GameSense with a Run method. In your main you would do new GameSense.Run(). In the constructor of the class you would put the initialization, and the state of the game (AFAICT, the various variables declared on top of GameSense).

*you should split the body of GameSense by purpose: ReadInput(), UpdatePosition(movement), DrawBerry, CheckGameOver, etc

You should limit the usage non-testing friendly things to only the body of the Run method or in the ReadInput method. Then your tests should proceed like this:
// classes should have an uppercase initial. please rename "pixel" to "Pixel"!

// this is the setup
var pos = new pixel();
pos.xpos = 10;
pos.ypos = 10;

// this is the operation:
UpdatePosition(pos, "UP");

// check the results
Assert.That(pos.xpos, Is.EqualTo(10));
Assert.That(pos.ypos, Is.EqualTo(9));

If it seems mundane, it's because tests usually are :D


text:
Q: BarChart is not showing data I'm using Charts JS in Laravel 5 to show a Bar Chart, the data is passing to the view correctly, but the chart doesn't shows me the bars, So, I printed in a alert the content of the Data, with:
alert(JSON.stringify(areaChartData, null, 4));

I get this:
{
    "labels": [
        "Asistencia",
        "Inasistencia"
    ],
    "datasets": [
        {
            "label": "Asistencia",
            "fillColor": "rgba(210, 214, 222, 1)",
            "strokeColor": "rgba(210, 214, 222, 1)",
            "pointColor": "rgba(210, 214, 222, 1)",
            "pointStrokeColor": "#c1c7d1",
            "pointHighlightFill": "#fff",
            "pointHighlightStroke": "rgba(220,220,220,1)",
            "data": 67
        },
        {
            "label": "Inasistencia",
            "fillColor": "rgba(60,141,188,0.9)",
            "strokeColor": "rgba(60,141,188,0.8)",
            "pointColor": "#3b8bba",
            "pointStrokeColor": "rgba(60,141,188,1)",
            "pointHighlightFill": "#fff",
            "pointHighlightStroke": "rgba(60,141,188,1)",
            "data": 33
        }
    ]
}

That's mean that the data is loading preety well. The code of the BarChart is:
var areaChartData = {
                    labels: ["Asistencia", "Inasistencia"],
                    datasets:[
                        {
                            label: "Asistencia",
                            fillColor: "rgba(210, 214, 222, 1)",
                            strokeColor: "rgba(210, 214, 222, 1)",
                            pointColor: "rgba(210, 214, 222, 1)",
                            pointStrokeColor: "#c1c7d1",
                            pointHighlightFill: "#fff",
                            pointHighlightStroke: "rgba(220,220,220,1)",
                            data:{!!json_encode($Incidentes->asistencia)!!}
                        },
                        {
                            label: "Inasistencia",
                            fillColor: "rgba(60,141,188,0.9)",
                            strokeColor: "rgba(60,141,188,0.8)",
                            pointColor: "#3b8bba",
                            pointStrokeColor: "rgba(60,141,188,1)",
                            pointHighlightFill: "#fff",
                            pointHighlightStroke: "rgba(60,141,188,1)",
                            data:{!!json_encode($Incidentes->inasistencia)!!}
                        }
                    ]
                };

                //- BAR CHART -
                //-------------
                var barChartCanvas = $("#barChart").get(0).getContext("2d");
                var barChart = new Chart(barChartCanvas);
                var barChartData = areaChartData;
                barChartData.datasets[1].fillColor = "#00a65a";
                barChartData.datasets[1].strokeColor = "#00a65a";
                barChartData.datasets[1].pointColor = "#00a65a";
                var barChartOptions = {
                    //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
                    scaleBeginAtZero: true,
                    //Boolean - Whether grid lines are shown across the chart
                    scaleShowGridLines: true,
                    //String - Colour of the grid lines
                    scaleGridLineColor: "rgba(0,0,0,.05)",
                    //Number - Width of the grid lines
                    scaleGridLineWidth: 1,
                    //Boolean - Whether to show horizontal lines (except X axis)
                    scaleShowHorizontalLines: true,
                    //Boolean - Whether to show vertical lines (except Y axis)
                    scaleShowVerticalLines: true,
                    //Boolean - If there is a stroke on each bar
                    barShowStroke: true,
                    //Number - Pixel width of the bar stroke
                    barStrokeWidth: 2,
                    //Number - Spacing between each of the X value sets
                    barValueSpacing: 5,
                    //Number - Spacing between data sets within X values
                    barDatasetSpacing: 1,
                    //String - A legend template
                    legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%>
<span style=\"background-color:<%=datasets[i].fillColor%>\"><%if(datasets[i].label){%><%=datasets[i].label%><%}%>
<%}%>
",
                    //Boolean - whether to make the chart responsive
                    responsive: true,
                    maintainAspectRatio: false
                };
                barChartOptions.datasetFill = false;
                barChart.Bar(barChartData, barChartOptions);

Before, I had an array of data of example and the graph was loading fine, so what is happening here, why it doesn't show?

A: Fixed! the thing is that the values sent from the backend are only one and not an array, so it was missing []


text:
Q: How come such different methods result in the same number, $e$? I guess the proof of the identity
$$
\sum_{n = 0}^{\infty} \frac{1}{n!} \equiv \lim_{x \to \infty} \left(1 + \frac{1}{x}\right)^x
$$
explains the connection between such different calculations. How is it done?

A: This identity, in isolation, is certainly confusing. It becomes less so once you know that it is just a special case of a more general identity
$$\sum_{n \ge 0} \frac{x^n}{n!} = \lim_{n \to \infty} \left( 1 + \frac{x}{n} \right)^n.$$
Why does this hold? Well, let's call the function on the left $e^x$. Then by inspection, $\frac{d}{dx} e^x = e^x$. General theory tells you that the solution to $y' = y$ is unique provided you fix the value of $y(0)$ (and this is also physically intuitive), and here $e^0 = 1$ by inspection, so that tells you that $e^x$ is the unique function satisfying $e^0 = 1$ and $\frac{d}{dx} e^x = e^x$.

Chandru1's deleted answer reminded me that the proof of this is actually completely elementary. Suppose $f$ is a function which satisfies $f'(x) = f(x)$. Then
$$\frac{d}{dx} \left( e^{-x} f(x) \right) = e^{-x} f'(x) - e^{-x} f(x) = 0$$
hence $e^{-x} f(x) = C_f$ for some constant $C_f$. Substituting $f(x) = e^x$ gives $e^{-x} e^x = C$, and substituting $x = 0$ gives $e^{-x} e^x = 1$. Now it follows that $f(x) = C_f e^x$.

Why does the function on the RHS also satisfy this property? Let's call this function $\exp(x)$. Then
$$\exp(cx) = \lim_{n \to \infty} \left( 1 + \frac{cx}{n} \right)^n = \lim_{m \to \infty} \left( 1 + \frac{x}{m} \right)^{mc} = \exp(x)^c$$
where $m = \frac{n}{c}$. Setting $c = 1 + \frac{y}{x}$, this gives
$$\exp(x + y) = \exp(x)^{1 + \frac{y}{x}} = \exp(x) \exp(x)^{ \frac{y}{x} } = \exp(x) \exp(y)$$
from which it follows that
$$\frac{d}{dx} \exp(x) = \lim_{h \to 0} \frac{\exp(x) \exp(h) - \exp(x)}{h} = \exp(x) \lim_{h \to 0} \frac{\exp(h) - 1}{h}$$
so it follows that $\exp(x)$ satisfies $\exp(0) = 1$ and $\frac{d}{dx} \exp(x) = \exp(x)$, which means it must equal $e^x$ - at least, as soon as we know that
$$\lim_{h \to 0} \frac{\exp(h) - 1}{h} = 1.$$
But
$$\exp(h) = \lim_{n \to \infty} \left( 1 + \frac{h}{n} \right)^n = \lim_{n \to \infty} \left( 1 + {n \choose 1} \frac{h}{n} + {n \choose 2} \frac{h^2}{n^2} + ... \right) = \lim_{n \to \infty} \left( 1 + h + R(h, n) \right)$$
where $|R(h, n)| \le \sum_{k \ge 2} |h|^k = O(|h|^2)$ by the ratio test, from which the conclusion follows.

That last step, by the way, is an echo of the standard proof, where one expands
$$\left( 1 + \frac{x}{n} \right)^n = \sum_{k=0}^n {n \choose k} \frac{x^k}{n^k}$$
and uses the fact that $\frac{1}{n^k} {n \choose k} \to \frac{1}{k!}$ as $n \to \infty$. While this is fairly hands-on, in my opinion it obscures an underlying principle behind this problem, which is that $e^x$ is a very special function and all of the equivalent ways of defining it are based on one of its special properties.
One really nice way to interpret the above identity is that it is precisely what you get by applying Euler's method to the ODE $y' = y$ with initial conditions $y(0) = 1$.

A: Another way of viewing $e^{x}$, is if suppose $f : \mathbb{R} \to \mathbb{R}$ is a differentiable function which satisfies $f'(x) = f(x)$ for all $x \in \mathbb{R}$, then $f(x) = e^{x} + C$. To see this we have $f'(x) = f(x) \Longrightarrow e^{-x}f'(x) = e^{-x} f(x) \Longrightarrow e^{x} \cdot [f'(x) - f(x)]= 0 \Longrightarrow \frac{\rm d}{\rm dx } \Bigl[e^{-x}f(x)\Bigr]=0$ which says that $e^{-x} f(x) = C$. Hence $f(x) = Ce^{x}$.


text:
Q: Como hago para pedir los datos separados " " y agregarlos en un vector Buenos noches tengo un problema y es como hago para pedir los datos separados " " y agregarlos en un vector, intente esto
    ArrayList<Receta> recetario = new ArrayList<>();
    public int n;
    System.out.println("Cantos ingredientes va a agregar");
    n = Integer.parseInt(sc.nextLine());
    String [] ingredientesApoyo = new String [n];
    System.out.println("Ingrese los ingredientes separados por (&)");
    String [] texto2 = sc.nextLine().split("&");
    for (int i = 0; i < n; i++) {
        ingredientesApoyo[i] = texto2[i];
    }

n es el tamaño del vector
   class Receta {[![introducir la descripción de la imagen aquí][1]][1]
   private String ingredientes[] = new String[n];
   public void setIngredientes(String[] ingredientes) {
    this.ingredientes = ingredientes;
     }
  }

A: Casi tienes todo listo, para la asignación sería así:
ingredientesApoyo[i] = texto2[i];

Y  el arreglo ingredientesApoyo debe crearse después de pedir el valor de n.
El código quedaría así:
public int n;
System.out.println("Cantos ingredientes va a agregar");
n = Integer.parseInt(sc.nextLine());
String [] ingredientesApoyo = new String [n];
System.out.println("Ingrese los ingredientes separados por (&)");
String [] texto2 = sc.nextLine().split("&");
for (int i = 0; i < n; i++) {
    ingredientesApoyo[i] = texto2[i];
}

Para pasarlo por un método:
Receta receta = new Receta();
receta.setIngredientes(ingredientesApoyo);
Y en la clase Receta no hace falta inicializar el arreglo ingredientes:
class Receta {
   private String ingredientes[];
   public void setIngredientes(String[] ingredientes) {
    this.ingredientes = ingredientes;
     }
  }


text:
Q: Will stress testing a QA instance on the same SQL Server as the Live Intance affect performance of that Live instance? I am doing some stress testing on a QA instance which is installed on the same SQL Server instance on Azure, as the Live instance. I have been changing it between, via "scale", between "Web", "S1" and "S2".  It has occurred to me that I might be negatively affecting the live DB instance's performance. Am I correct? Perhaps what I should do is create a QA SQL Server instance and then test on this seperate to Live?
Thoughts?

A: If they are separate databases, even if they are on the same logical server, they are still on separate nodes with dedicated computing power (unless you are using Web/Business, which is shared). This is true for all the current tiers (Basic, Standard, Premium).
If you are using Elastic Pools than you would have sharing of DTU usage between your databases but you can specify how much each database can use.

A: It could impact if it is a WEB / BUSINESS database. Also web / business are depricated and will be retired soon. However it shouldn't be the case with BASIC / STANDARD / PREMIUM tiers. I would recommend upgrading server to V12 and perform the tests so that you get the latest code running and need not repeat them once you upgrade.


text:
Q: If $x_n\ge 0$ for each $n\in\Bbb N$ and $\sum_{n\in\Bbb N}x_n=0$ then $x_n=0$ for each $n\in\Bbb N$ necessarly. Let be $(x_n)_{n\in\Bbb N}$ a not negative sequence of real number and we suppose that
$$
\sum_{n\in\Bbb N}x_n=0
$$
So if the last identity holds then it must be
$$
x_n=0
$$
for any $n\in\Bbb N$ necessarly? Indeed by standard analysis result I only know that the limit of a not negative sequence is not negative too. So could someone help me, please?

A: If $(x_n)_{n\in\Bbb N}$ is not negative then
$$
0\le x_n\le\sum_{n\in\Bbb N}x_n=0
$$
for each $n\in\Bbb N$ so that
$$
x_n=0
$$
for each $n\in\Bbb N$.


text:
Q: how can i get the lang html attribute in webpack configuration     const lang = "the lang html attribute value";

    var languages = {
        "fr": require("./languages/fr.json"),
        "en": require("./languages/en.json")
    };

    var configuration = Object.keys(languages).map(function(language) {
        const loadedLang = (lang.indexOf("fr") > -1) ? "fr" : "en";
        return {
            name: loadedLang,
            entry: './assets/js/main.js',
            output: {
                filename: 'bundle.js',
                path: path.resolve(__dirname, 'assets/js/dist')
            },
            plugins: [
                new I18nPlugin(
                    languages[loadedLang]
                )
            ]
        }
    });

So I am trying to get the <html lang="en-US"> lang attribute and I know that I have no access to the DOM from the webpack config file.
My question is:
Does someone have an idea about how to do this or how to have access to the local storage from webpack?
PS:
I tried a node-localstorage package but it doesn't do the job I want

A: An answer to your question would be to load the file with the fs api and then use an regex to extract your language:
const fs = require('fs');
const content = fs.readFileSync('PATH_TO_INDEX.HTML', options: { encoding: 'utf8' });
const lang = content.match(/<html lang="(.*)"/)[1];

But I would recommend to do it the "webpack" way:
Create a separate folder for every language, that contains the index.html and the js file specific to each language language.
For this, add the following:
output: {
 path: path.resolve(__dirname, `assets/js/dist/${language}/`)
},
plugins: [
 new HtmlWebpackPlugin({
   template: 'PATH_TO_YOUR_TEMPLATE',
   lang: language,
   title: 'your page title',
 })
]

Please don't forget to install the html-webpack-plugin and require it at the top of your config.
And create a new file index.html with the following content:
<!DOCTYPE html>
<html lang="<%= htmlWebpackPlugin.options.lang %>">
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
  </body>
</html>

So now for every language a separate index.html with the right language and the right js file for that language is created in every language folder.
So not the html file dictates the language set, but the webpack config.


text:
Q: Google Cloud function invoking AWS Lambda function causes "Error: The role defined for the function cannot be assumed by Lambda." I am trying to invoke an AWS lambda function myFunc from my google cloud function function1. Testing function1 returns
Error: function crashed. Details:
The role defined for the function cannot be assumed by Lambda.

my google function's index.js
let AWS = require('aws-sdk')

AWS.config.update({
  accessKeyId: 'key',
  secretAccessKey: 'secret',
  region: 'region'
})

let lambda = new AWS.Lambda();

exports.helloWorld = async(event) => {
  let params = {
    FunctionName: 'myFunc',
    InvocationType: 'RequestResponse',
    Payload: '{"foo": "bar"}
  }

  return await lambda.invoke(params, function(e,d) {
    if (e){throw e}
    else {return data.Payload}
  }).promise()
}

my lambda function has a basic role (arn:aws:iam::account_number:role/myFunc-role-uu29d) with AWSLambdaBasicExecutionRole managed policy and custom policy for DynamoDB read/write access.
My Trust Relationship looks like this
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}


text:
Q: Moving an inteface from excel to asp.net I have an Excel spreadsheet that is used to collect data from a user, and is used to populate our database. I need to produce an asp.net page that can be used to collect this data instead.
I'm having some difficulty coming up with the best way to get this data, the current spreadsheet is used to allow the user to define a number of packages, and sub tasks to these packages, they can have an unlimited  number of packages, so the spreadsheet looks a bit like this:
Package 1   |               |                 |           |
------------------------------------------------------------
Task 1      | 12/06/2010    | 15/09/2010      | 10        |
Task 2      | 18/07/2010    | 19/09/2010      | 12        |
Task 3      | 19/06/2010    | 15/09/2010      | 14        |

Package 1   |               |                 |           |
------------------------------------------------------------
Task 1      | 12/06/2010    | 15/09/2010      | 10        |
Task 2      | 18/07/2010    | 19/09/2010      | 12        |
Task 3      | 19/06/2010    | 15/09/2010      | 14        |

The spread sheet has space for 40 packages, and a macro to add more blank packages should they need more.
So I'm trying to come up with the best interface for this data in an asp.net page, to allow the user to create any number of packages, and associate any number of tasks with these pacakges. This data needs to be saved to a database once they are done, so I need to be aware of what tasks link to what packages.
I've contemplated using gridviews, or list views to store this data on the page, but it all seems a bit unwieldy. I'd also considered just having some tables on the page and using some javascript to keep adding to these tables, but this will make submiting this data to the db quite difficult.  I'd like to find a way to do this so its simple for the user, so any suggestions, or links to examples where it has been done would be much appreciated.

A: Check this out; I think it might be what you are looking for: http://mattberseth2.com/demo/Default.aspx?Name=Bulk+Inserting+Data+with+the+ListView+Control&Filter=All
Though, are you okay with the free form layout, or are you looking for a more specialized layout?

A: Stating the obvious, there are a lot of different possibilities. Off the top of my head you might consider:

*

*Create a web UserControl (ASCX) that encapsulates the interface for a single package & set of associated tasks. I imaging you would use something like a GridView (or other databound control) to record the tasks. It might also contain the logic for saving just that package/tasks.

*Perhaps use AJAX to improve perceived response and usability on the page. If you use the ASP.NET AJAX Control Toolkit you can wrap each ASCX in an update panel so only that package is saved. Give each ASCX it's own save button.

*Put a "New package" type button/link on the page that dynamically loads a new ASCX on the page (again, AJAX can assist). Or, when the last new package control is filled in and saved, it automatically loads adds a new ASCX to the page.


text:
Q: Student T CDF - How to read the hypergeometric function formula? I am trying to program out a couple of statistical formulas with python. I am not concerned with efficiency or the fact that there already are tools to calculate the values, but I am doing it to increase my understanding of statistics.
I tried setting up the Student T CDF, but I have no clue how to even start programming this.
On wikipedia it states the studentt cdf as follows:
$$
\frac{1}{2}+x\Gamma\left(\frac{\nu+1}{2}\right)\cdot\frac{_2F_1\left(\frac{1}{2},\frac{\nu+1}{2},\frac{3}{2},-\frac{x^2}{\nu}\right)}{\sqrt{\pi\nu}\Gamma\left(\frac{\nu}{2}\right)}
$$
It is noted that 2F1 is the Hypergeometric Function I have no idea what it does, how it works or what it looks like. I can't figure out how to program this function or even read it, since there must be something mysterious about the 2F1 notion that I don't understand. I tried reading up on the topic but I can only find very thick and old books that make me feel very stupid. The wikipedia link does not really help me, since I don't understand it. I don't have a good understanding of function theory and have never encountered gamma, beta and so on.
My desire might be too reductive and limited: I think of a function as something that calculates a value for a given input, so f(x) = 2x can pre easily programmed and will return 2 for f(1), 4 for f(2) and so on. So my question is:
How do I even read this formula?
Update
I am sorry to admit it, but I am really dependent on your patience here. I have really big problems understanding the formula's "code" to begin with. I feel that until I do, I will have no use for your answers - so please help me on a lower level, as if you were explaining it to your grandma.
2F1 - what is the 2 for, what is the F for, what is the 1 for?
Where does the (q)n come from? 2F1(a,b;c;z)? Why are a and b separated with a comma, not a semicolon? How is 2F1 different from 3F8, or is there even such a thing? This is all hieroglyphs to me.
How do I read it? My question is more based on a reading issue than on a logical or a lack of understanding. I feel like translating chinese without a dictionary!

A: If I understand you correctly you basically would like to get what
$$
_2F_1
$$
means. Basically, this is a so-called hypergeometric function. There are lots of them and they take the form:
$$
_pF_q
$$
Hence your example with p = 2 and q = 1 isn't the hypergeometric function, it's a hypergeometric one. This means that there may also be:
$$
_3F_8
$$
which just means p = 3 and q = 8.
In general, hypergeometric functions are defined as
$$
_pF_q(a_1, ..., a_p; b_1, ..., b_q; z) = \sum_{k=0}^\infty\prod_{i=1}^p {\Gamma(k+a_i) \over \Gamma(a_i)}\prod_{j=1}^q {\Gamma(b_j) \over \Gamma(k + b_j)}{z^k \over k!}
$$
so you get your formula for p = 2 and q = 1 by just inserting them into the appropriate places:
$$
_2F_1(a_1, a_2; b_1; z) = \sum_{k=0}^\infty\prod_{i=1}^2 {\Gamma(k+a_i) \over \Gamma(a_i)}\prod_{j=1}^1 {\Gamma(b_j) \over \Gamma(k + b_j)}{z^k \over k!}
$$
Please note that you now have two times a, but only one time b (due to the choice of p and q). To visually group the a variables and separate them from the single b and the single z, you use semicolons instead of commas. It's just a visual clue.
The next step is to simplify the formula by removing unneccessary parts (such as the products). The result is the formula already mentioned by Julius in his answer.
The Gamma function, last but not least, is basically the same as the factorial function, but with its argument decreased by one. Hence
$$
\Gamma(n) = (n - 1)!
$$
Does that answer your question, or at least helps with some understanding?

A: Getting the Student T CDF by numerical integration of the PDf works for me. But instead of using Simpson's Rule, I used a slice width of .0001 for t from -10 to +10. Also if you're looking for an algorithm for the CDF of the Normal curve, just make v a big number, like 1000. T now becomes z. I got 1.000000 for -6 to +6.


text:
Q: Random item from listbox every 0,8 second i have a code that you see below. Can you tell me how to optimize that? Because sometimes when I click random picker (this code shows random items every 0.8 sec, like 'roll the wheel') it isn't showing f.e. 20 items, like I defined... I just want to make this script work by that: I click a button and it is rolling the positions from a listbox, and showing items that aren't
Dim rnd As New Random
Dim rndIndex As Integer = rnd.Next(10, 20)

For ill As Integer = 0 To rndIndex
    Dim rnd As New Random
    Dim randomIndex As Integer = rnd.Next(0, lCount)
    If Not Label1.Text = ListBox1.Items(randomIndex) Then
        Label1.Text = ListBox1.Items(randomIndex)
        Delay(0.08)
    Else
        rndIndex = rndIndex + 1
    End If
Next

That doesn't work, because sometimes I see only 6-8 different items. It could be like that: I've got 10 numbers (0-9), and it puts the following numbers into label every 0,8 secs: 1, 5, 7, 4, 3, 1, 5, 8, 6, 3, 0, 3, 1, 5.

A: I'm not 100% sure I should do this but there's so many things wrong with your code that it will be rather arduous to be bring it up to scratch by steps.  Basically, here's how I would display a random item from a ListBox in a Label every 0.8 seconds without ever repeating the same item twice in a row:
Private ReadOnly rng As New Random

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'This is done in code here for clarity but you'd normally do this in the designer.
    Timer1.Interval = 800
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    'Get all the items from the ListBox.
    Dim items = ListBox1.Items.Cast(Of String)().ToList()

    'Remove the currently displayed item.
    items.Remove(Label1.Text)

    'Get a random item from the remainder and display it.
    Label1.Text = items(rng.Next(items.Count))
End Sub

As I said in my comment, no loop. The Timer component is specifically intended to be used when you want to perform an action regularly.  Notice also that the currently-displayed item is taken out of the equation before the random number is even generated, so there's never a problem with repeats.
EDIT:
Here is modified code based on what I think I missed the first time:
Private ReadOnly rng As New Random
Private tickCount As Integer

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'This is done in code here for clarity but you'd normally do this in the designer.
    Timer1.Interval = 800
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    tickCount = rng.Next(10, 20)
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    tickCount -= 1

    If tickCount = 0 Then
        Timer1.Stop()
    End If

    'Get all the items from the ListBox.
    Dim items = ListBox1.Items.Cast(Of String)().ToList()

    'Remove the currently displayed item.
    items.Remove(Label1.Text)

    'Get a random item from the remainder and display it.
    Label1.Text = items(rng.Next(items.Count))
End Sub

I also made a slight modification to the original code because the last line was getting the item at a random index from ListBox1.Items instead of items.