text:
Q: Updating Python Tkinter GUI using .after method I have a listbox that I want to update every minute or so. It pulls XML data, parses it and put it into the list box automatically. I have figured out to use the .after method but upon implementing it outside of the class I run into bug after bug trying to make it run. I believe my main issue is just not calling the application correctly but I could be wrong. Here is some of the relevent code.
This is all outside the main class
def refresher(frame):
    subreddit=Application.entryVar(Application)
    Application.getXML(subreddit)
    frame.after(1000,refresher,frame)

main = tk.Tk()
main.wm_title("Readdit")
# main.geometry("350x400")
app = Application(master=main)
# Begins the applications GUI loop
# app.__init__()
refresher(main)
app.mainloop()

Here is the beginning of the program and this is where it ultimately falls back upon with all the bugs.
class Application(tk.Frame):

    print("what about this?")
    def __init__(self, master=None):
        self.threadTitle = tk.StringVar()
        self.threadAuth = tk.StringVar()
        self.threadPub = tk.StringVar()
        self.threadArtLink = tk.StringVar()
        self.threadLink = tk.StringVar()
        self.threadImg = tk.StringVar()
        self.threadArtLink.set('Click something to display thread info')
        self.photo = Image.open("temp.png")
        self.photo = self.photo.resize((250,250), Image.ANTIALIAS)
        self.threadImage = ImageTk.PhotoImage(self.photo)
        self.errMes = tk.StringVar()
        if not os.path.exists('Pics'):
            os.makedirs('Pics')
        # print('Something')

        # Intializes tkinter gui framework
        tk.Frame.__init__(self, master)
        # Packs widgets needed
        self.grid()
        # Creates the widgets functions
        self.createWidgets()
        # Intializes the man rss.xml
        self.initial()

    def createWidgets(self):
        # Create entrybox and align to grid
        self.send_entry = tk.Entry(self)
        self.send_entry.grid(row=0,column=0)

        # Create button,allign to grid, get xml
        self.change_sub = tk.Button(self,text='Change Subreddit',padx=5, pady=5, command=lambda :self.entryVar())

And here is the full error
Traceback (most recent call last):
  File "S:/Projects/xmlParser.py", line 306, in <module>
    refresher(main)
  File "S:/Projects/xmlParser.py", line 296, in refresher
    subreddit=Application.entryVar(Application)
  File "S:/Projects/xmlParser.py", line 290, in entryVar
    rawInput=self.createWidgets(self).send_entry.get()
  File "S:/Projects/xmlParser.py", line 40, in createWidgets
    self.send_entry = tk.Entry(self)
  File "C:\Python33\lib\tkinter\__init__.py", line 2506, in __init__
    Widget.__init__(self, master, 'entry', cnf, kw)
  File "C:\Python33\lib\tkinter\__init__.py", line 2068, in __init__
    BaseWidget._setup(self, master, cnf)
  File "C:\Python33\lib\tkinter\__init__.py", line 2046, in _setup
    self.tk = master.tk
AttributeError: type object 'Application' has no attribute 'tk'

A: I think you should use your app directly in the function call to refresher:
def refresher(frame):
    frame.getXML()# I Don`t know what do this function, just an example
    frame.after(1000,refresher,frame)

main = tk.Tk()
main.wm_title("Readdit")
# main.geometry("350x400")
app = Application(master=main)
# Begins the applications GUI loop
# app.__init__()
refresher(app) #use app here
app.mainloop()

A: It looks like the problem is here:
Application.entryVar(Application)

Application is a class rather than an object, so my guess is that you should be using an instance of Application both places in that code.


text:
Q: how to call both php function and javascript function for a click of a single button? For the click of a button I have Validate the page through the Javascript and I have compare the data selected in the dropdown list with the database, that too before the page submit to the server.
So I am planning to call two functions (Javascript and php function) for click of a single button.
Is my approach (solution) is right or is there any other ways.
Thanks in advance..

A: You can compare the data selected in the dropdown list with the database through ajax and if matched then you can submit the form.

A: To call the php function on the same page, you will need to work with AJAX, as it is a server-side script.

A: Use the below code, its a jQuery Ajax code.
test.php is the php page where matching will be done with the database.

*

*Receive selectedData as post variable in test.php

*Query ur database with selectedData value to match.

*If match found return "matched" otherwise "not matched".

$.post("test.php",
  {
     selectedData: $("#yourdropdownid option:selected").val()
  },
   function(data) {
     if(data=="matched") {
    // submit the form here
     } else {
    // alert user that seleted value is not in database
     }
   });

redpajama_set_name: RedPajamaStackExchange


text:
Q: pyqt5 QLabel Image setScaledContents(True) don't allow Qpainter updates I want to display an image and put a marker at the current mouse position for every left mouse click.
Below code does the job however, it works only if ("self.imglabel.setScaledContents(True)") is commented. Any reason?
I have to do this job on various images of different resolutions, I read to maintain the proper aspect ratio and display the image appropriately we need to use setScaledContents(True). But why enabling this is not allowing update() (PaintEvent)??
import sys
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QSizePolicy, QMessageBox
from PyQt5.QtGui import QPixmap, QPainter, QPen, QColor, QImage, QPalette

class Menu(QMainWindow):
    def __init__(self):
        super().__init__()
        self.central_widget = QWidget()               # define central widget
        self.setCentralWidget(self.central_widget)
        self.vbox = QVBoxLayout(self.central_widget)
        self.vbox.addWidget(self.imgWidget())
        self.vbox.addWidget(QPushButton("test"))

    def imgWidget(self):
        self.imglabel = QLabel()
        self.imglabel.setScaledContents(True)
        self.image = QImage("calib.jpeg")
        self.imagepix = QPixmap.fromImage(self.image)
        self.imglabel.setPixmap(self.imagepix)
        self.imglabel.mousePressEvent = self.imgMousePress
        return self.imglabel

    def imgMousePress(self, e):
        painter = QPainter(self.imglabel.pixmap())
        pen = QPen()
        pen.setWidth(10)
        pen.setColor(QColor('red'))
        painter.setPen(pen)
        painter.drawPoint(e.x(), e.y())
        painter.end()
        self.imglabel.update()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    mainMenu = Menu()
    mainMenu.show()
    sys.exit(app.exec_())

A: To avoid unnecessary computation for each paintEvent of the QLabel, whenever the scaledContents property is True the scaled image is cached, and all the painting is automatically discarded.
To avoid that, you should create a new instance of QPixmap using the existing one, and then set the new painted pixmap again. Note that if the image is scaled, the widget coordinates won't reflect the actual position on the pixmap, so you need to use a transformation to get the actual point to paint at.
    def imgMousePress(self, e):
        pm = QPixmap(self.imglabel.pixmap())
        painter = QPainter(pm)
        pen = QPen()
        pen.setWidth(10)
        pen.setColor(QColor('red'))
        painter.setPen(pen)
        transform = QTransform().scale(
            pm.width() / self.imglabel.width(),
            pm.height() / self.imglabel.height())
        painter.drawPoint(transform.map(e.pos()))
        painter.end()
        self.imglabel.setPixmap(pm)

Consider that all the "points" will become stretched rectangles if the width/height ratio is not the same of the source image, but this is only a problem of appearance: if you save the pixmap later, they will be squares again, since saving is based on the source pixmap.
If you want to keep their squared shape while displaying instead, you'll need to keep track of the points and overwrite paintEvent to paint them manually on the label.


text:
Q: Mobile apps unable to communicate with API When browsing through the Stack Exchange mobile apps, I get an error message. There seems to be a problem with the API.

It seems https://api.stackexchange.com/ is down so it might be solved soon.


text:
Q: Can we make an array containing pairs? I am new to stl and i came across a question where it is required to store a lot of pairs having same characteristics (like:- (string,int)) together. Can we store pairs in array and if so how? Thanks in advance..

A: You can try something like:
struct demo
{
  string str;
  int i;
};

std::array<demo, 5> arr;  //for fixed size array of 5 elements
std::vector<demo> vec;    //for dynamic size arrays

A: You want ...

to store a lot of pairs having same characteristics

The terminology is a bit wrong. You want to store many pairs of the same type (not "characteristics").
You could define your own struct as answered by Nipun, or use
std::array<std::pair<std::string,int>, 10> arr;

for an array of 10 pairs of strings and ints.
Spend more time on reading a documentation on standard containers and standard utilities. Perhaps you want some other existing thing (e.g. std::set with std::tuple, maybe with your own comparator).
Templates can (and often should) be combined since they are compositional. Be also aware of the rule of five.


text:
Q: Why does the first tSQLt sample test fom Red Gate SQL Test fail on my system? I recently installed the SQL Test plug-in on a virtual machine (VMWare 8) running SSMS for SQL Server 2008 R2.  This is a front end for tSQLt.  I enabled CLR on the server.  I installed the tSQLt sample database.  I hit the Run button.  I expect all the sample tests to pass.  I  observe that all but one pass.
The first test, titled [AcceleratorTests].[test ready for experimentation if 2 particles] failed:  Expected: <1> but was <0>.
I have read the SQL involved and it all looks like it should pass.  As near as I can tell, the code delivered by Red Gate is the same as the code offered by tSQLt for the sample database.  There are a couple new layers of stuff on the machine, now, the SQL Test runner and the tSQLT set of scripts.  I am kind of lost trying to find out where the error is.  Any advice on what I should look at first?
TIA

A: I was on the Red Gate half of the SQL Test/tSQLt team who worked on this project. This test you refer to was actually supposed to fail, and the idea was for you to be directed to a tutorial that would explain how to correct it and how to write your own. The tutorial can be found here:
http://tsqlt.org/after-running-the-examples-smss/
As you found out, the tool didn't direct you to the tutorial! Thanks for drawing this to our attention. We should at the very least put the above URL in the output text of the failing test so that you weren't left in an 'unsatisfactory' state where you've got a failing test with no guidance on what to do next.
Thanks for drawing this to our attention. We'll definitely look at improving this in an upcoming release. Now that you have the link to the tutorial, it would be great if you could post a comment to this answer and let us know whether it made sense to you!

A: The initial install of the sample tests intentionally has a failing test. You can see how to fix it here.


text:
Q: Get the average time of a column using TimeDiff I am trying to compute the average time of process in a service named "ADD CERT"
Some Context:

*

*DateTimeEntered = Time when people started queuing

*DateTImeEnded = Time when people ended their queue.

SELECT AVG(TIMEDIFF(DateTimeEnded, DateTimeEntered))AS AverageTime
FROM tblqueuenumber
WHERE Service = 'ADD CERT'

A: As your format is    HH:MM:SS so i think you need below
  select SEC_TO_TIME(avg(TIME_TO_SEC(DateTimeEnded)-TIME_TO_SEC(DateTimeEntered)))
   FROM tblqueuenumber
    WHERE Service = 'ADD CERT'


text:
Q: What is Kotlin's way to have similar effect as flags enum variable in C# In C#, I can do this.
[Flags]
enum BeerProperty
{
    Bold = 1,
    Refreshing = 2
}

static void Taste(BeerProperty beer)
{
    if (beer == (BeerProperty.Bold | BeerProperty.Refreshing))
    {
        Debug.WriteLine("I can't qutie put my finger on...");
    }
}

static void Main(string[] args)
{
    var tickBeer = BeerProperty.Bold | BeerProperty.Refreshing;
    Taste(tickBeer);
}

In Kotlin, it seems that I cannot "OR" two flags. What is the Kotlin's way to do this? Using a list of enum variables?
enum class BeerProperty(value:Int)
{
    Bold(1),
    Refreshing(2)
}

fun taste(beer:BeerProperty)
{
    if(beer == (BeerProperty.Bold | BeerProperty.Refreshing))
    {
        print("I can't qutie put my finger on...");
    }
}

fun main(args: Array<String>)
{
    val tickBeer = BeerProperty.Bold | BeerProperty.Refreshing;
    taste(tickBeer);
}

Added: Thank you for the answer (which I cannot mark as answer yet, due to time limitation). I modified the code like below and achieved what I wanted.
fun taste(beer: EnumSet<BeerProperty>)
{
    if(beer.contains(BeerProperty.Bold) && beer.contains(BeerProperty.Refreshing))
    {
        print("I can't qutie put my finger on...");
    }
}

fun main(args: Array<String>)
{
    val tickBeer = EnumSet.of(BeerProperty.Bold, BeerProperty.Refreshing);
    taste(tickBeer);
}

A: Indeed, in Kotlin every enum constant is an instance of the class corresponding to the enum, and you can't use 'OR' to combine multiple class instances. If you need to track multiple enum values, the most efficient way to do that is to use the EnumSet class.

A: You can achieve the same result of c# enum flags in this way
enum class TestType(val value: Int)
{
    x(1),
    y(2),
    z(4)
}

fun Int.hasFlag(flag: Int): Boolean
{
    return ((this and flag) == flag)
}

Usage:
val myType = TestType.x.value or TestType.y.value //myType = 3

println(myType.hasFlag(TestType.x.value)) //true

println(myType.hasFlag(TestType.y.value)) //true

println(myType.hasFlag(TestType.z.value)) //false

println(myType.hasFlag(TestType.x.value or TestType.y.value)) //true

println(myType.hasFlag(TestType.x.value or TestType.z.value)) //false

A: Using extension functions
import java.util.*

enum class BeerProperty
{
    BOLD,
    REFRESHING,
    STRONG;

    infix fun and(other: BeerProperty) = BeerProperties.of(this, other)
}

typealias BeerProperties = EnumSet<BeerProperty>

infix fun BeerProperties.allOf(other: BeerProperties) = this.containsAll(other)
infix fun BeerProperties.and(other: BeerProperty) = BeerProperties.of(other, *this.toTypedArray())

fun taste(beer: BeerProperties) {
    if(beer allOf (BeerProperty.BOLD and BeerProperty.REFRESHING and BeerProperty.STRONG)) {
        print("I can't qutie put my finger on...")
    }
}

fun main(args: Array<String>) {
    val tickBeer = BeerProperty.BOLD and BeerProperty.REFRESHING and BeerProperty.STRONG
    taste(tickBeer)
}

I use extension functions to allow properties to be added with and, and allof to check all flags are set.


text:
Q: What reason is there to use null instead of undefined in JavaScript? I've been writing JavaScript for quite a long time now, and I have never had a reason to use null. It seems that undefined is always preferable and serves the same purpose programmatically. What are some practical reasons to use null instead of undefined?

A: At the end of the day, because both null and undefined coerce to the same value (Boolean(undefined) === false && Boolean(null) === false), you can technically use either to get the job done. However, there is right way, IMO.

*

*Leave the usage of undefined to the JavaScript compiler.
undefined is used to describe variables that do not point to a reference. It is something that the JS compiler will take care for you. At compile time the JS engine will set the value of all hoisted variables to undefined. As the engine steps through the code and values becomes available the engine will assign respective values to respective variables. For those variables for whom it did not find values, the variables would continue to maintain a reference to the primitive undefined.

*Only use null if you explicitly want to denote the value of a variable as having "no value".
As @com2gz states: null is used to define something programmatically empty. undefined is meant to say that the reference is not existing. A null value has a defined reference to "nothing". If you are calling a non-existing property of an object, then you will get undefined. If I would make that property intentionally empty, then it must be null so you know that it's on purpose.
TLDR; Don't use the undefined primitive. It's a value that the JS compiler will automatically set for you when you declare variables without assignment or if you try to access properties of objects for which there is no reference. On the other hand, use null if and only if you intentionally want a variable to have "no value".

Sidebar: I, personally, avoid explicitly setting anything to undefined (and I haven't come across such a pattern in the many codebases/third party libs I've interacted with). Also, I rarely use null. The only times I use null is when I want to denote the value of an argument to a function as having no value, i.e.,:
function printArguments(a,b) {
  console.log(a,b);
}

printArguments(null, " hello") // logs: null hello

A: null and undefined are essentially two different values that mean the same thing. The only difference is in the conventions of how you use them in your system. As some have mentioned, some people use null for meaning "no object" where you might sometimes get an object while undefined means that no object was expected (or that there was an error). My problem with that is its completely arbitrary, and totally unnecessary.
That said, there is one major difference - variables that aren't initialized (including function parameters where no argument was passed, among other things) are always undefined.
Which is why in my code I never use null unless something I don't control returns null (regex matching for example). The beauty of this is it simplifies things a lot. I never have to check if x === undefined || x === null, I can just check x === undefined. And if you're in the habit of using == or simply stuff like if(x) ... , stop it.
!x will evaluate to true for an empty string, 0, null, NaN - i.e. things you probably don't want. If you want to write javascript that isn't awful, always use triple equals === and never use null (use undefined instead). It'll make your life way easier.

A: A few have said that it is ok to initialise objects to null. I just wanted to point out that destructuring argument defaults don't work with null. For example:
const test = ({ name } = {}) => {
  console.log(name)
}

test() // logs undefined
test(null) // throws error

This requires performing null checks prior to calling the function which may happen often.

A: A useful property in null that undefined does not qualifies:
> null + 3
3
> undefined + 3
NaN

I use null when I want to 'turn off' a numeric value,
or to initialize some. My last use was manipulating css transform:
const transforms = { perspective : null, rotateX : null };
// if already set, increase, if not, set to x
runTimeFunction((x) => { trasforms.perspective += x; });
// still useful, as setting perspective to 0 is different than turning it off
runTimeFunction2((x) => { transforms.perspective = null; });

// toCss will check for 'null' values and not set then at all
runTimeFunction3(() => { el.style.transform = toCss(transforms); });

Not sure if I should use this property thought...

A: DOM nodes and elements are not undefined, but may be null.

*

*The nextSibling of the last child of an element is null.

*The previousSibling of the first child is null.

*A document.getElementById reference is null if the element does not exist in the document.
But in none of these cases is the value undefined; there just is no node there.

A: Unknown variable: undefined.
Known variable yet no value: null.

*

*You receive an object from a server, server_object.

*You reference server_object.errj. It tells you it's undefined. That means it doesn't know what that is.

*Now you reference server_object.err. It tells you it's null. That means you're referencing a correct variable but it's empty; therefore no error.

The problem is when you declare a variable name without a value (var hello) js declares that as undefined: this variable doesn't exist; whereas programmers mostly mean: "I've not given it a value yet", the definition of null.
So the default behavior of a programmer—declaring a variable without a value as nothing—is at odds with js—declaring it as not existing. And besides, !undefined and !null are both true so most programmers treat them as equivalent.
You could of course ensure you always do var hello = null but most won't litter their code as such to ensure type sanity in a deliberately loosely-typed language, when they and the ! operator treat both undefined and null as equivalent.

A: In JavaScript, the value null represents the intentional absence of any object value. null expresses a lack of identification, indicating that a variable points to no object.
The global undefined property represents the primitive value undefined.
undefined is a primitive value automatically assigned to variables.
undefined is meant to say that the reference is not existing.

A: undefined is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; null is where the thing is known to exist, but it has no value.

A: Everyone has their own way of coding and their own internal semantics, but over the years I have found this to be the most intuitive advice that I give people who ask this question: when in doubt, do what JavaScript does.
Let's say you are working with object properties like options for a jQuery plugin...ask yourself what value JavaScript gives a property that has yet to be defined -- the answer is undefined. So in this context, I would initialize these types of things with 'undefined' to be consistent with JavaScript (for variables, you can do var myVar; instead of var myVar = undefined;).
Now let's say you are doing DOM manipulation...what value does JavaScript assign to non-existent elements? The answer is null. This is the value I would initialize with if you are creating a placeholder variable that will later hold a reference to an element, document fragment, or similar that relates to the DOM.
If you're working with JSON, then a special case needs to be made: for undefined property values, you should either set them to "" or null because a value of undefined is not considered proper JSON format.
With this said, as a previous poster has expressed, if you find that you're initializing stuff with null or undefined more than once in a blue moon, then maybe you should reconsider how you go about coding your app.

A: I don't really have an answer, but according to Nicholas C. Zakas, page 30 of his book "Professional JavaScript for Web Developers":

When defining a variable that is meant
  to later hold an object, it is
  advisable to initialize the variable
  to null as opposed to anything else.
  That way, you can explicitly check for the value null to determine if
  the variable has been filled with an object reference at a later time

A: You might adopt the convention suggested here, but there really is no good reason to. It is not used consistently enough to be meaningful.
In order to make the convention useful, you first must know that the called function follows the convention. Then you have to explicitly test the returned value and decide what to do. If you get undefined, you can assume that some kind of error occurred that the called function knew about. But if an error happened, and the function knew about it, and it is useful to send that out into the wider environment, why not use an error object? i.e. throw an error?
So at the end of the day, the convention is practically useless in anything other than very small programs in simple environments.

A: I completely disagree that usage null or undefined is unnecessary.
undefined is thing which keeping alive whole prototype chaining process.
So compiler only with null can't check if this property just equal to null, or its not defined in endpoint prototype. In other dynamic typed languages(f.e. Python) it throws exception if you want access to not defined property, but for prototype-based languages compiler should also check parent prototypes and here are the place when undefined need most.
Whole meaning of using null is just bind variable or property with object which is singleton and have meaning of emptiness,and also null usage have performance purposes. This 2 code have difference execution time.
var p1 = function(){this.value = 1};
var big_array = new Array(100000000).fill(1).map((x, index)=>{
    p = new p1();
    if(index > 50000000){
       p.x = "some_string";
    }

    return p;
});
big_array.reduce((sum, p)=> sum + p.value, 0)

var p2 = function(){this.value = 1, p.x = null};
var big_array = new Array(100000000).fill(1).map((x, index)=>{
    p = new p2();
    if(index > 50000000){
       p.x = "some_string";
    }

    return p;
});
big_array.reduce((sum, p)=> sum + p.value, 0)

A: I'm working through this exact question right now, and looking at the following philosophy:

*

*Any function that is intended to return a result should return null if it fails to find a result

*Any function that is NOT intended to return a result implicitly returns undefined.

For me, this question is significant because anyone calling a function that returns a result should have no question as to whether to test for undefined vs null.
This answer does not attempt to address:

*

*Property values of null vs undefined

*Variables within your functions being null vs undefined

In my opinion, variables are your own business and not a part of your API, and properties in any OO system are defined and therefore should be defined with value different from what they would be if not defined (null for defined, undefined is what you get when accessing something that is not in your object).

A: Here's a reason: var undefined = 1  is legal javascript, but var null = 1 is a syntax error. The difference is that null is a language keyword, while undefined is, for some reason, not.
If your code relies on comparisons to undefined as if it's a keyword (if (foo == undefined) -- a very easy mistake to make) that only works because nobody has defined a variable with that name. All that code is vulnerable to someone accidentally or maliciously defining a global variable with that name. Of course, we all know that accidentally defining a global variable is totally impossible in javascript...

A: Just wanna add that with usage of certain javascript libraries, null and undefined can have unintended consequences.
For example, lodash's get function, which accepts a default value as a 3rd argument:
const user = {
  address: {
    block: null,
    unit: undefined,
  }
}
console.log(_.get(user, 'address.block', 'Default Value')) // prints null
console.log(_.get(user, 'address.unit', 'Default Value')) // prints 'Default Value'
console.log(_.get(user, 'address.postalCode', 'Default Value')) // prints 'Default Value'

Another example: If you use defaultProps in React, if a property is passed null, default props are not used because null is interpreted as a defined value.
e.g.
class MyComponent extends React.Component {
   static defaultProps = {
      callback: () => {console.log('COMPONENT MOUNTED')},
   }
   componentDidMount() {
      this.props.callback();
   }
}
//in some other component
<MyComponent />   // Console WILL print "COMPONENT MOUNTED"
<MyComponent callback={null}/>   // Console will NOT print "COMPONENT MOUNTED"
<MyComponent callback={undefined}/>   // Console WILL print "COMPONENT MOUNTED"

A: There are already some good answers here but not the one that I was looking for.  null and undefined both "technically" do the same thing in terms of both being falsy, but when I read through code and I see a "null" then I'm expecting that it's a user defined null, something was explicitly set to contain no value, if I read through code and see "undefined" then I assume that it's code that was never initialized or assigned by anything.  In this way code can communicate to you whether something was caused by uninitialized stuff or null values.  Because of that you really shouldn't assign "undefined" manually to something otherwise it messes with the way you (or another developer) can read code.  If another developer sees "undefined" they're not going to intuitively assume it's you who made it undefined, they're going to assume it's not been initialized when in fact it was.  For me this is the biggest deal, when I read code I want to see what it's telling me, I don't want to guess and figure out if stuff has "actually" been initialized.
Not even to mention that using them in typescript means two different things.  Using:
interface Example {
    name?: string
}

Means that name can be undefined or a string, but it can't be null.  If you want it null you have to explicitly use:
interface Example {
  name: string | null
}

And even then you'll be forced to initialize it at least with "null".
That's of course only true if you're using "strictNullChecks": true in tsconfig.json.

A: Based on a recent breakage we ran into, the example below shows why I prefer to use undefined over null, unless there is a specific reason to do otherwise:
function myfunc (myArg) {
    if (typeof myArg === 'string') {
        console.log('a', myArg);
    } else if (typeof abc === 'object') {
        console.log('b', myArg);
        if (myArg.id) {
           console.log('myArg has an id');
        } else {
           console.log('myArg has an id');
        }
    } else {
        console.log('no value');
    }
}

The following values will play nicely:
'abc'
{}
undefined
{ id: 'xyz' }

On the other hand the assumption of null and undefined being equivalent here breaks the code. The reason being is that null is of type of object, where as undefined is of type undefined. So here the code breaks because you can't test for a member on null.
I have seen a large number of cases with code of similar appearance, where null is just asking for problems:
if (typeof myvar === 'string') {
  console.log(myvar);
} else if (typeof myvar === 'object') {
  console.log(myvar.id);
}

The fix here would be to explicitly test for null:
if (typeof myvar === 'string') {
  console.log(myvar);
} else if (myvar !== null && typeof myvar === 'object') {
  console.log(myvar.id);
}

My attitude is to code for the weaknesses of a language and the typical behaviours of programmers of that language, hence the philosophy here of going with 'undefined' bey default.

A: To write simple code you need to keep complexity and variation down. When a variable or a property on an object does not have a value it is undefined , and for a value to be null you need to assign it a null value.

A: Undeclared vs Null
null is both an Object "type" and one of the 7 unique primitive value types called null
undefined is both a global scope property and type called undefined and one of the 7 unique primitive value types called undefined (window.undefined) .
It is the primitive types we use as values we are interested in.
In the case of null, as a value type it means an empty value has been assigned to a variable, but the variable type (Number, String, etc) is still defined. It just has no value. That is what null means. It means a variable has an empty value but it is still a value. It also reinitializes the variable with some kind of value, but is not undefined as a type.
undefined is a special case. When you declare a variable (or use a missing value not yet declared) it is of type undefined, as the browser does not know what type of data has been assigned to it yet. If the variable is declared but not assigned a value is is assigned the primitive calue undefined by default prior to assigning a value, and implies the variable does not exist or exists but has no value assigned.
Like null, undefined is also a primitive value type. But unlike null it means the variable does not exist, where null means the value does not exist. That is why its always better to check if the variable exists and has been assigned a variable using undefined before checking if the value is null or empty. undefined implies no variable or object exists in the compilation at all. The variable has either not been declared or declared with a missing value so not initialized. So checking for undefined is a very good way to avoid many types of errors in JavaScript and supersedes null.
That is why I would not rely on "truthy" checks for true/false with null and undefined, even though they will both return a false response, as undefined implies an additional step for missing feature, object, or variable, not just a true/false check. It implies something more. If you have a missing undeclared variable, truthy statements will trigger an ERROR!
Let's look at undefined first:
        //var check1;// variable doesnt even exist so not assigned to "undefined"
        var check2;// variable declared but not initialized so assigned "undefined"
        var check3 = 'hello world';// variable has a value so not undefined

        console.log('What is undefined?');

        //console.log(check1 === undefined);// ERROR! check1 does not exist yet so not assigned undefined!
        console.log(check2 === undefined);// True
        console.log(check3 === undefined);// False
        console.log(typeof check1 === 'undefined');// True - stops the ERROR!
        console.log(typeof check2 === 'undefined');// True
        console.log(typeof check3 === 'undefined');// False

As you can see undeclared variables, or declared but not initialized, both are assigned a type of undefined. Notice declared variables that are not initialized are assigned a value of undefined, the primitive value type but variables that do not exist are undefined types.
null has nothing to do with missing variables or variables not yet assigned values, as null is still a value. So anything with a null is already declared and initialized. Also notice a variable assigned a null value is actually an object type unlike undefined types. For example...
        var check4 = null;
        var check5 = 'hello world';

        console.log('What is null?');

        console.log(check4 === undefined);// False
        console.log(check5 === undefined);// False
        console.log(typeof check4 === 'undefined');// False
        console.log(typeof check5 === 'undefined');// False
        console.log(typeof check4);// return 'object'
        console.log(typeof check5);// return 'string'

As you can see each act differently and yet both are primitive values you can assign any variable. Just understand they represent different states of variables and objects.


text:
Q: Angular Reactive forms - FormArray - Cannot find control with path error on first load Seeing some Cannot find control with path errors when trying to use a simple Reactive Form and FormArray.
Component.ts
ngOnInit() {
this.newForm = this.fb.group({
  currencyExchangex: this.fb.array(
      [this.fb.group({
        rateNumeric: null
      })],

  )
})

}
Component.html
    <div [formGroup]="newForm">
     <div class="col-md-2" formArrayName="currencyExchangex"
       *ngFor="let item of newForm.controls.currencyExchangex.value; let i = index;">
         <ng-container [formGroupName]="i" >
            <input class="form-control"
             id="rateNumericIdx"
             type="number"
             formControlName="rateNumeric"/>
         </ng-container>
     </div>
    </div>

When I first show this component i get the following errors on Chrome Dev tools:
ERROR Error: Cannot find control with path: 'currencyExchangex -> 0'

and
ERROR Error: Cannot find control with path: 'currencyExchangex -> 0 -> rateNumeric'

However this error is not displayed if I click out and back to the page showing this component.  Have done lots of debugging (breakpoints and (pre) newForm.value | json (/pre)) and form and relevant controls exist before this error is shown.
Don't like seeing errors so would appreciate any advice to fix it. This was on Angular 8 and also updated to Angular 9.

A: I just started getting this error after updating Chrome to 80.0.3987.100. I think there may also be a chrome bug going on here. My code worked fine in version 79.


text:
Q: jQuery Live for drop box selection (change) I'm having a problem getting content loaded into a document to fire jQuery scripts.
I have the following code
$(".jquery-selectbox").change(function(e) {
                url = this.options[this.selectedIndex].value;
                $('#pane2').fadeOut(500, function () {
                    $('#pane2').fadeIn(500);
                    $("#pane2").load(url, '', reinitialiseScrollPane2);
                });
});

that should cause a drop box to load a link based on the value selected. The drop down box is loaded into the page on document ready via jQuery's .load. It has a class of '.jquery-selectbox'
I tried to follow the jQuery documentation on .live based on 'change' but it wouldn't work for me, even after updating to 1.4.2. What should I do to make this work?
Thanks!

A: Try this -
$(".jquery-selectbox").live('change',function(e) {
                var url = $(this).val();
                $('#pane2').fadeOut(500, function () {
                    $('#pane2').fadeIn(500);
                    $("#pane2").load(url, '', reinitialiseScrollPane2);
                });
});


text:
Q: PHP Post Empty Upon Request I can't work out why this isn't working. I'm sure it's probably something small but I keep scratching my head. Below are my HTML and PHP.
form.html
<form action="result" method="post">
   <input type="text" class="form-control" name="hello">
   <input type="submit" class="btn btn-primary" value="Submit">
</form>

result.php (.htaccess is set to allow without .PHP and I receive the same issue when including .PHP in the action)
<?php

  if($_SERVER['REQUEST_METHOD'] == 'POST')
  {
     echo "POST<br>";
  }

  print_r($_POST);

?>

Submitting the form sends you to result.php and POST is displayed, but $_POST is empty.
EDIT: .htaccess
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)/$ $1 [NE,R=302,L]

Cheers in advance.

A: With the help of @mickmackusa and @CBroe it was determined that the issue was with the .htaccess file.
It was redirecting instead of rewriting when removing the .PHP extension. The solution was to instead change the .htaccess to the following:
RewriteEngine On
RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

Thanks everyone for your help.


text:
Q: How to add quotes or a comma to strings in a RDD? How to add quotes or a comma to a string in a Scala RDD? I have a RDD that has one line of string from a text file with no quotes.  I have this scala code that gets me the line of text from the file:
val textFile = sc.textFile("ISS_LOG_FILE.TXT")

val newRDD = textFile.filter(line => line.contains("56.34.2.299")

I am looking to add a quote, like ", at the start and end of the line of text in the RDD.  So, it would be like:

"Administrators need to start the server with the IP address of
  56.34.2.299."

How do I append a character like a quote to string inside a RDD?
Thanks

A: You can format with triple quotes:
map(line => s""""$line"""")

or concatenate with escaped quotes
map(line => "\"" + line +  "\"")


text:
Q: Exclude rows surpassing threshold value I have a dataset df
  field_pointpath                       assetclass_code value
C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT      6KSFS_6KSF   50
C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT      6KSFS_6KSF   60
C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT      6KSFS_6KSF   65
C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT      6KSFS_6KSF   43
C_THDxL_0154x6KSFS_A03xaP_ACT                  6KSFS    70
C_THDxL_0154x6KSFS_A03xaP_ACT                  6KSFS    55
C_THDxL_0154x6KSFS_A03xaP_ACT                  6KSFS    43
C_THDxL_0154x6KSFS_A03xaP_ACT                  6KSFS    11
C_THDxL_0154x6KSFS_B03x6KSF_11xaP_ACT     6KSFS_6KSF    67
C_THDxL_0154x6KSFS_B03x6KSF_11xaP_ACT     6KSFS_6KSF    36
C_THDxL_0154x6KSFS_B03x6KSF_11xaP_ACT     6KSFS_6KSF    39
C_THDxL_0154x6KSFS_B03x6KSF_11xaP_ACT     6KSFS_6KSF    33
C_THDxL_0154x6KSFS_B03x6KSF_11xaP_ACT     6KSFS_6KSF    20
C_THDxL_0154x6KSFS_B03xaP_ACT                  6KSFS    21
C_THDxL_0154x6KSFS_B03xaP_ACT                  6KSFS    22
C_THDxL_0154x6KSFS_B03xaP_ACT                  6KSFS    17
C_THDxL_0154x6KSFS_B03xaP_ACT                  6KSFS    30

I want to filter out values for specific field_pointpath
for example:

*

*C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT

*C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT
which has a character A should not have value greater than 60:
Similarly,

*

*C_THDxL_0154x6KSFS_B03x6KSF_11xaP_ACT,

*C_THDxL_0154x6KSFS_B03x6KSF_11xaP_ACT
which has a character B should not have value greater than 30
Thus output should be
                    field_pointpath    assetclass_code  value
C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT   6KSFS_6KSF       50
C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT   6KSFS_6KSF       60
C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT   6KSFS_6KSF       43
C_THDxL_0154x6KSFS_A03xaP_ACT              6KSFS         55
C_THDxL_0154x6KSFS_A03xaP_ACT              6KSFS         43
C_THDxL_0154x6KSFS_A03xaP_ACT              6KSFS         11
C_THDxL_0154x6KSFS_B03x6KSF_11xaP_ACT   6KSFS_6KSF       20
C_THDxL_0154x6KSFS_B03xaP_ACT              6KSFS         21
C_THDxL_0154x6KSFS_B03xaP_ACT              6KSFS         22
C_THDxL_0154x6KSFS_B03xaP_ACT              6KSFS         17
C_THDxL_0154x6KSFS_B03xaP_ACT              6KSFS         30

A: You can use regular expression to filter on field_pointpath. I am assuming that you are looking for entries where there is _A or _B followed by 2 digits. Then you combine that with the filter on value:
ind <- (grepl("\\_A[0-9]{2}", df$field_pointpath) & df$value > 60) |
       (grepl("\\_B[0-9]{2}", df$field_pointpath) & df$value > 30)
df[!ind, ]

#                          field_pointpath assetclass_code value
# 1  C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT      6KSFS_6KSF    50
# 2  C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT      6KSFS_6KSF    60
# 4  C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT      6KSFS_6KSF    43
# 6          C_THDxL_0154x6KSFS_A03xaP_ACT           6KSFS    55
# 7          C_THDxL_0154x6KSFS_A03xaP_ACT           6KSFS    43
# 8          C_THDxL_0154x6KSFS_A03xaP_ACT           6KSFS    11
# 13 C_THDxL_0154x6KSFS_B03x6KSF_11xaP_ACT      6KSFS_6KSF    20
# 14         C_THDxL_0154x6KSFS_B03xaP_ACT           6KSFS    21
# 15         C_THDxL_0154x6KSFS_B03xaP_ACT           6KSFS    22
# 16         C_THDxL_0154x6KSFS_B03xaP_ACT           6KSFS    17
# 17         C_THDxL_0154x6KSFS_B03xaP_ACT           6KSFS    30

A:     df[(substr(df$field_pointpath, 20,20)=="A" & df$value <= 60) |
         (substr(df$field_pointpath, 20,20)=="B" & df$value <= 30),]

1  C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT      6KSFS_6KSF    50
2  C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT      6KSFS_6KSF    60
4  C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT      6KSFS_6KSF    43
6          C_THDxL_0154x6KSFS_A03xaP_ACT           6KSFS    55
7          C_THDxL_0154x6KSFS_A03xaP_ACT           6KSFS    43
8          C_THDxL_0154x6KSFS_A03xaP_ACT           6KSFS    11
13 C_THDxL_0154x6KSFS_B03x6KSF_11xaP_ACT      6KSFS_6KSF    20
14         C_THDxL_0154x6KSFS_B03xaP_ACT           6KSFS    21
15         C_THDxL_0154x6KSFS_B03xaP_ACT           6KSFS    22
16         C_THDxL_0154x6KSFS_B03xaP_ACT           6KSFS    17
17         C_THDxL_0154x6KSFS_B03xaP_ACT           6KSFS    30

A: You could use the following code:
# your data, with 2 lines appended that will not be selected
my_df  <- read.table(header = TRUE,
text = "field_pointpath                       assetclass_code value
C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT      6KSFS_6KSF   50
C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT      6KSFS_6KSF   60
C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT      6KSFS_6KSF   65
C_THDxL_0154x6KSFS_A03x6KSF_11xaP_ACT      6KSFS_6KSF   43
C_THDxL_0154x6KSFS_A03xaP_ACT                  6KSFS    70
C_THDxL_0154x6KSFS_A03xaP_ACT                  6KSFS    55
C_THDxL_0154x6KSFS_A03xaP_ACT                  6KSFS    43
C_THDxL_0154x6KSFS_A03xaP_ACT                  6KSFS    11
C_THDxL_0154x6KSFS_B03x6KSF_11xaP_ACT     6KSFS_6KSF    67
C_THDxL_0154x6KSFS_B03x6KSF_11xaP_ACT     6KSFS_6KSF    36
C_THDxL_0154x6KSFS_B03x6KSF_11xaP_ACT     6KSFS_6KSF    39
C_THDxL_0154x6KSFS_B03x6KSF_11xaP_ACT     6KSFS_6KSF    33
C_THDxL_0154x6KSFS_B03x6KSF_11xaP_ACT     6KSFS_6KSF    20
C_THDxL_0154x6KSFS_B03xaP_ACT                  6KSFS    21
C_THDxL_0154x6KSFS_B03xaP_ACT                  6KSFS    22
C_THDxL_0154x6KSFS_B03xaP_ACT                  6KSFS    17
C_THDxL_0154x6KSFS_B03xaP_ACT                  6KSFS    30
C_THDxL_0154x6KSFS_C03xaP_ACT                  6KSFS    30 ## added
C_THDxL_0154x6KSFS_D03xaP_ACT                  6KSFS    30 ## added
")

library(stringr)
    my_df2 <- my_df[ (str_detect( my_df$field_pointpath, "_A03") & my_df$value <= 30)
| ( str_detect(my_df$field_pointpath, "_B03")  & my_df$value <= 60 ), ]

Please, let me know whether this is what you wanted.


text:
Q: Pasar Array que está dentro de un JSON como parámetro a una función ¡Hola a todos!
Tengo el siguiente Array dentro de un archivo JSON independiente:
[
    ["Triangulo", "Cuadrado","Rojo", "Caramelo"],
    ["Circulo", "Zeta","Casco", "Móvil"],
    ["Calcetines", "Cuadrado","Rectángulo", "Aro"]
]

Obtengo dicho JSON en mi archivo principal de JS con la siguiente función:
    let fetchQuestions = () => {

        fetch('./src/scenes/questions.json')
        .then(resp => resp.json())
        .then(data => console.log(data))
        .catch(err => console.error(err))
    }

   fetchQuestions();

Y lo que quiero lograr es poder elegir cualquier índice de dicho JSON para pasarlo como parámetro a una función.
Para que quede más claro, si dicho Array que está dentro del JSON lo tuviese en mi archivo principal JS, simplemente haría lo siguiente:
    let miArray = [
     ["a","b","c"],
     ["a1","b1","c1"]
    ];

funcionEjemplo(...miArray[0]);

En este caso estaría tomando como parámetro el primer índice del array (["a","b","c"]).
Y quiero poder hacer esto mismo pero con fetchQuestions();. Quiero extraer el valor que me otorga dicha función y poder asignar el índice del Array que yo quiera a funcionEjemplo();, tal como mostré en el ejemplo anterior.
¡Gracias de antemano!

A: Como ya te habrás dado cuenta, fetch devuelve una promesa, por lo que para poder trabajar con los resultados de la función fetchQuestions() tienes que trabajar con async/await. He cambiado la url para el fetch (aunque no pude encontrar alguna API que me devuelva array de arrays) pero en principio debería funcionarte para tu caso específico.
Dada la naturaleza de await, este debe incluirse en una función async, de ahí que la función mainFn() sea asíncrona. En dicha función esperamos a que fetchQuestions() nos traiga los datos, y una vez que ya los tenemos podemos pasar alguno de los resultados a la función sampleFn() que como observarás, es una función normal, dado que ya hemos esperado por los resultados previamente. Ya en sampleFn() puedes trabajar con el resultado como si fuera una variable que ya existía previamente en tu código.

const fetchQuestions = async () => {
  return await fetch('https://jsonplaceholder.typicode.com/users')
    .then(resp => resp.json())
    .catch(err => console.error(err))
}

const sampleFn = (array) => {
  console.log(array);
}

const mainFn = async () => {
  // Obtener todos los resultados
  const questions = await fetchQuestions();

  // Pasar solo uno de ellos
  sampleFn(questions[0]);
}

mainFn();

Nota: No hago uso del operador spread porque como ya te comenté, no encontré una API que me devolviera array de arrays, lo que devuelve es una array de objetos, pero sin problemas debería funcionar con las modificaciones que harás para tu caso.


text:
Q: Start, pause, resume and replay an embedded video I experiment with an example from https://www.overleaf.com/latex/examples/using-media9-to-include-videos-files/yvdwwvpknjkk to embed a video using the media9 package:
\documentclass{article}
\usepackage{graphicx}
\usepackage{media9}
\begin{document}
    % using a .mp4; downloaded from https://www.youtube.com/watch?v=-9iXD2-hbJM
    \includemedia[width=0.6\linewidth,height=0.6\linewidth,activate=pageopen,
    passcontext,
    transparent,
    addresource=penguins.mp4,
    flashvars={source=penguins.mp4}]
    {\includegraphics[width=0.6\linewidth]{example-image-a}}{VPlayer.swf}
\end{document}

The video works with the okular viewer, not evince. Acrobat Reader throws a 3D parsing error.
However, the video plays only once upon opening the document. I have no ability to replay, pause and resume the video. Also clicking the video with the mouse as explained in Media9 package: pause video without mediabutton does not work.
How to implement these additional functionalities?


text:
Q: Is it possible to use 2 different examples table in Cucumber/Cuke4Duke Is it possible to somehow construct a Scenario which uses two different Example tables in different steps? Something like this:
Given I log in
When I view a page
Then I should see <goodText>
Examples:
|goodText|
|abc|
And I should not see <badText>
Examples:
|badText|
|xyz|

The scenario above doesn't work, also in reality there would be more rows to each table.

A: It looks like you're confusing tables with scenario examples. You can mix them, but from your example I'm not sure what you're trying to achieve. Why not just write:
Given I log in
When I view a page
Then I should see "abc"
But I should not see "xyz"

or if you wanted to check for multiple strings:
Given I log in
When I view a page
Then I should see the following text:
  | abc |
  | def |
But I should not see the following text:
  | xyz |
  | uvw |

A: You say that in reality there would be many more rows to the table; but of course a table can also have many columns.
Would this not work for you?
Given I log in
When I view a page
Then I should see <goodText>
But I should not see <badText>
Examples:
|goodText| badText |
|abc     | xyz     |


text:
Q: HorizontalScrollView overscroll & parent view I have a HorizontalScrollView that user can scroll to read a number of TextViews.
This is placed inside a ViewPager.
So, if user scrolls the entire HorizontalScrollView instead of showing the overscroll, I want that the entire page (inside ViewPager) start scrolling...
Any idea?
<HorizontalScrollView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:scrollbars="none"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    >

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/tagLine"
    >
    </LinearLayout>

</HorizontalScrollView>

LinearLayout is filled at runtime with TextView
This layout is inflated by a Fragment used by a ViewPager


text:
Q: Having problems with Javascript variable scope This was working for me before, but without having changed anything, it seems to have broke. I'm declaring a variable outside of a code block, and then reassigning the value in a loop. The value prints correctly within the loop, but I get an empty string when I print outside the block.
var cnaKey = ""; // Instantiating this variable outside the code block below

var cnaRef = rootRef.child("Activities/"+selectedPatient+"/"+selectedDate);
    cnaRef.once('value', function(cnaSnap){
        cnaSnap.forEach(function(cnaChild) {
            cnaKey = cnaChild.key;
            console.log(cnaKey); // This is printing the correct value
        });
      });

console.log(cnaKey) // Printing an empty string


text:
Q: Chromecast warning loadMedia autoplay is deprecated On my playSelectedItemRemotely method I get a warning message:
 - (void)playSelectedItemRemotely {
    GCKCastSession* castSession = [GCKCastContext sharedInstance].sessionManager.currentCastSession;
    if (castSession) {
        // WARNING ON LINE BELOW
        [castSession.remoteMediaClient loadMedia:[self buildMediaInformation] autoplay:YES];
    } else {
        NSLog(@"No cast session!");
    }
}

says:

'loadMedia:autoplay:' is deprecated: Use loadMedia:withOptions:

how to fix that?

A: Like warning message said, you can use loadMedia:withOptions method like below:
- (void)playSelectedItemRemotely {
    GCKCastSession* castSession = [GCKCastContext sharedInstance].sessionManager.currentCastSession;
    if (castSession) {
        GCKMediaLoadOptions *options = [GCKMediaLoadOptions init];
        [castSession.remoteMediaClient loadMedia:[self buildMediaInformation] withOptions:options];
    } else {
        BILog(@"No cast session!");
    }
}

here are the options that you can use:

*

*(BOOL) autoplay Whether playback should start immediately.

  The default value is YES.

*

*(NSTimeInterval) playPosition The initial playback position.

  The default value is kGCKInvalidTimeInterval, which indicates a
  default playback position.

*

*(float) playbackRate The playback rate.

  The default value is 1.

*

*(NSArray*) activeTrackIDs An array of integers specifying the active tracks.

  The default value is nil.

*

*(id) customData Custom application-specific data to pass along with the request.

  Must either be an object that can be serialized to JSON using
  NSJSONSerialization, or nil.

*

*(NSString*) credentials

  The user credentials for the media item being loaded.

*

*(NSString*) credentialsType

  The type of user credentials specified in
  GCKMediaLoadOptions::credentials.

please also check the documentation.


text:
Q: SwiftUI PDF Kit not filling available view space I have a SwuftUI view that has both a Nav bar and Tab bar.  I have a PDF viewer that loads a PDF via URL.  When the PDF is displayed in the view it starts below the Navbar which is desired but it doesn't fill down to the top of the Tab Bar despite the pdf being multiple pages long.  I know I could use .frame() and make the view full height then subtract height of both bars, but that seems so ineffecient.

There must be a simpler way to do this, calculating the height up fixed UI elements just to make the view fit correctly seems very inefficient.  Is there a way to do this that I'm missing?
PDFViewer.swift
import SwiftUI
import PDFKit

struct PDFViewer: View {
    var url: URL

    var body: some View {
        PDFKitRepresentedView(url)
            .navigationTitle("Payslip")
            .navigationBarTitleDisplayMode(.inline)
    }
}

struct PDFKitRepresentedView: UIViewRepresentable {
    let url: URL
    init(_ url: URL) {
        self.url = url
    }

    func makeUIView(context: UIViewRepresentableContext<PDFKitRepresentedView>) -> PDFKitRepresentedView.UIViewType {
        let pdfView = PDFView()
        pdfView.document = PDFDocument(url: self.url)
        pdfView.autoScales = true
        return pdfView
    }

    func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PDFKitRepresentedView>) {

    }
}

ContentView.swift
struct ContentView: View {
    @State var userIsAuthenticated: Bool = false

    init(auth: State<Bool>) {
        navAppearance.configureWithOpaqueBackground()
        navAppearance.backgroundColor = UIColor(Color("MyBlue"))
        navAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
        navAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]

        UINavigationBar.appearance().standardAppearance = navAppearance
        UINavigationBar.appearance().scrollEdgeAppearance = navAppearance

        self._userIsAuthenticated = auth
    }

    var body: some View {
        if userIsAuthenticated {
            TabView {
                NavigationView {
                    RosterView(auth: $userIsAuthenticated)
                }
                .navigationViewStyle(StackNavigationViewStyle())
                .tabItem { Label("My Roster", systemImage: "calendar") }

                NavigationView {
                    PayView(auth: $userIsAuthenticated)
                }
                .tabItem { Label("My Pay", systemImage: "dollarsign.circle") }

                NavigationView {
                    LeaveView(auth: $userIsAuthenticated)
                }
                .tabItem { Label("My Leave", systemImage: "airplane.circle") }

                NavigationView {
                    MessagesView(auth: $userIsAuthenticated)
                }
                .tabItem { Label("Messages", systemImage: "bubble.left.and.bubble.right") }
            }
            .foregroundColor(.white)
            .accentColor(.white)
            .onAppear(perform: {
                UITabBar.appearance().isTranslucent = false
                UITabBar.appearance().barTintColor = UIColor(named: "MyBlue")
                UITabBar.appearance().unselectedItemTintColor = UIColor.lightText
                UITabBar.appearance().tintColor = UIColor.white
            })
        } else {
            AuthView(auth: $userIsAuthenticated)
        }
    }
}

A: There is something wrong in another part of your code. If I test your code in the following way, the frame of the PDFViewer is correct.
struct ContentView: View {
    private var url: URL {
        guard let localURL = Bundle.main.url(forResource: "A Sample PDF",
                                             withExtension: "pdf")
        else {
            fatalError()
        }
        return localURL
    }

    var body: some View {
        TabView {
            NavigationView {
                PDFViewer(url: self.url)
            }
            .tabItem {
                VStack {
                    Image(systemName: "folder")
                    Text("Test")
                }
            }
        }
    }
}


text:
Q: Enterprise grade file sharing Can anybody suggest any web based application ( enterprise grade) that will allow my internal users to share files with the outside world. Maybe something like yousendit, but I want to be able to host it in my network. It doesn't have to be opensource as long as it runs on a linux platform.

A: Check out AjaXplorer.  Dead bang simple for end users, nothing more than LAMP to run.

A: FTP

A: One word: WebDAV (if you really want it to be web based, else you can try scp/sftp with private key and forced commands)

A: I'd look at either Accellion or Allardsoft File Transfer, very broadly similar but vastly different pricing.
Both are VM's so they don't strictly fit your "Must run on Linux" criteria, but they do "just work" and are focussed on sending and receiving files.
One key thing as well, they are both "self service", no setting up FTP users or having pissed users calling because no-one was there in IT when they needed to send a 5gb file at the last minute on a Friday.

A: Lotus Quickr can do that. The bad news is: you either have to run Lotus Domino, or an IBM WebSphere/DB2 as a back-end datastore.

A: The Turnkey Linux File Server uses eXtplorer. Works well.


text:
Q: Opposite of trim in Python I've started learning Python and I was wondering if there is a way to do the opposite of trim() in Python. For example I have string:
  "Need some help around here" and I want it to become " Need some help around here "?

A: No, strip() removes all the space in the head and tail.
But you can
' %s ' % 'Need some help around here'


text:
Q: Why doesn't this emberjs template update? I'm learning emberjs and I've done a pretty simple example. The HTML template is:
<script type="text/x-handlebars">
    Hello <b>{{App.appOwner}}</b>
</script>

And then the javascript is:
App = Ember.Application.create({
  appOwner : 'Erik'
});

App.appOwner = 'Tom';

Which does pretty much what you expect. The emberjs.com documentation says templates are auto-updating -- so I added this:
$(document).click(function() {
  console.log('HERE!');
  App.appOwner = 'Alphonse';
});

Which quite unexpectedly failed. I had added the console.log just to make sure the click handler was being called, which it was. Why doesn't it update?

A: You need to use .set() mutator method, because javascript doesn't have facilities to intercept the direct properties changes:
App.set('appOwner', 'Alphonse');


text:
Q: Excel Date Manipulation Function I have an excel table that contains start times and end times and the added hours. Here is what it looks like
***********************************
* Start Time ** End Time ** Hours *
***********************************
***********************************
* 8:00 AM    ** 3:30 PM  ** 7:30  *
***********************************
* 7:30 AM    ** 4:00 PM  ** 8:30  *
***********************************

The Hours column contains this function:
=TEXT(C3-B3,"h:mm")

I need a function that can add up the hours column to find total hours. Every function I have tried has not worked. Thanks in advance!

A: Rather than setting Column D (I guess that's what it is) to be TEXT() of the value you want, just set it to the value, C3-B3, and format it as h:mm.  The add them as usual, and format the total as [h]:mm.  h:mm will display hours modulo 24; [h]:mm will allow the hours part to be ≥ 24 (and to be displayed as such).


text:
Q: Python, how to setup hooks for tracing I/O Events My app downloads files, creates files as final/intermediate data. I would like to setup a hook (outside the app), to alert/log whenever my app does any I/O events - like writing a file, deleting a file, downloading a file from the file server. I use the urllib to retrieve fits files from the data servers.

A: If you know where the file will be downloaded to, one solution could be to use inotify.  In particular, pyinotify seems interesting.  I don't know if CentOS has a recent enough version of the Linux kernel for this to work though.

A: If you want a list of your process file operations, you can use FileMon or ProcMon from SysInternals.
Edit: for Linux, you can use strace.


text:
Q: why java8 streams consumer andThen method? I am new to Java 8, just want to ask what is the difference in performance between the two code snippets below.
I know both work, but I am wondering why the Java team created Consumer::andThen method when I can use the normal approach.
List<String> list = Arrays.asList("aaa","cccc","bbbb");
List<String> list2 = new ArrayList<>();

//Approach 1
list.stream().forEach(x -> {
            list2.add(x);
            System.out.println(x);
        });

//Approach 2
Consumer<String> c1 = s -> list2.add(s);
Consumer<String> c2 = s -> System.out.println(s);

list.stream().forEach(c1.andThen(c2));

IMO, approach1 is better, why approach2 again? If both are same, then why andThen() method is created? I guess there must be reason they've created.
In other words, when exactly is the andThen() method really helpful?

A: Just as a side note, there is another approach possible:
Approach 3
list.stream()
        .peek(System.out::println)
        .forEach(list2::add);

or even better:
List<String> list2 = list.stream()
        .peek(System.out::println)
        .collect(Collectors.toList());

Performance-wise all the approaches are comparable, but the last one is the most "functional". The problem with the previous ones is the insertion into the second list inside the stream. This is a side-effect, which is considered a bad practice. From this perspective, the approach with the two consumers is the worst in my opinion, since the side effect is the most hidden.

A: I agree that is makes less sense to create a separate Consumer<String> instance for each statement just for the sake of using andThen.
However, if you already have two Consumer<String> instances (c1 and c2), and you need to execute both, you could either write:
list.forEach(x -> {
        c1.accept(x);
        c2.accept(x);
    });

or
list.forEach(c1.andThen(c2));

In this case, the latter is clearly cleaner.
EDIT:
I'd like to expand on the case when you create your own Consumers (i.e. not re-using pre-existing ones). When you assign a lambda expression to a Consumer variable, you can use that Consumer instance in multiple places instead of duplicating the lambda expression. That is true for any functional interface.
Once you decide to use a Consumer variable, the decision of whether to have a single Consumer implementing complex logic or 2 simpler Consumers, each implementing part of the logic, depends on whether there is a need to be able to execute just part of the logic in some cases (or changing the order in which parts of the logic are executed).
Having c1 and c2 allows you either of the following options:
list.forEach(c1);
list.forEach(c2);
list.forEach(c1.andThen(c2));
list.forEach(c2.andThen(c1));

If you had a single consumer that does the logic of both c1 and c2, you have less flexibility.

A: The most obvious use case seems to the ability to combine your consumers as you wish while making each one of them re-usable. It does just make the code cleaner and more "functional ready".
It will not be much useful if you don't need to re-use the same consumer logic elsewhere.


text:
Q: Convert Twitter Timestamp? ive got the user created date timestamp using twitter API "created_timestamp": "1437815864820" but the timestamp is different from php time() format which is 1602426884.
and when i convert the twitter timestamp to date using date('m/d/Y', 1437815864820) it shows 12/09/41628 when it supposed between Agustus 2009 (my twitter created date).
ive searched around and unfortunately i cant find the solution for this, some says that it was 64bit format or something im not sure.
my goal is to check if the created timestamp is smaller than current timestamp, which mean that the user account was created before the specific timestamp
if( $created_timestamp < time() ){
//continue
}

A: Well I assume that the Timestamps are in milliseconds. In that case you need to convert them into seconds to be able to parse them.
echo date("m/d/Y", $created_timestamp / 1000);


text:
Q: Custom ArrayAdapter
I am creating an app in which I can search for files and delete it.

    searchstring = receivedmsg.getString("mysearch");
    tv.setText("Search Results for " + searchstring);

    searchForFileNameContainingSubstring(searchstring);

    //ListAdapter myadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, resList);
    //lv.setAdapter(myadapter);

    CustomAdapter adapter = new CustomAdapter(DataFetcher.this, android.R.layout.simple_list_item_1 , resList);
    lv.setAdapter(adapter);

Searched results are showing in listview. How can I add checkboxes in listview?

Already searched on google but it's not working. How can I achieve that?

A: Create custom layout with any name you want:
for example:
single_item_list.xml
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="6dip" >

        <CheckBox
            android:id="@+id/checkBox1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:text="CheckBox" />

        <TextView
            android:id="@+id/code"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/checkBox1"
            android:layout_alignBottom="@+id/checkBox1"
            android:layout_toRightOf="@+id/checkBox1"
            android:text="TextView" />

    </RelativeLayout>

Now in your customAdapter:
CustomAdapter adapter = new CustomAdapter(DataFetcher.this, R.layout.single_item_list , resList);

and handle functionalities in customAdapter


text:
Q: Calculate:$\int_{0}^{\infty}\frac{\ln x}{(x+1)^{3}}\mathrm{d}x$ with contour integration Calculate: $$\int_{0}^{\infty}\frac{\ln x}{(x+1)^{3}}\mathrm{d}x$$
My try:
Keyhole integration:
$\displaystyle \frac{\pi i\ln R\cdot e}{(Re^{\theta i}+1)^{3}}\rightarrow 0$ (we take $r$ as large as we want)
and here is the confusion :
around the circle the residue is $0$:
as $\displaystyle \frac{x\ln x}{(1+x)^{3}}\rightarrow0$ when we approach to $0$. Therefore, the residue is $0$, and the whole integration of the keyhole is $0$. which leads that the result is $0$.
but if we take the pole in the keyhole, $x=-1$ this is $3$rd order pole, and its residue is $\displaystyle \left. -\frac{1}{x^{2}}\right|_{x=-1}=-1$ meaning that the whole integral is $-2\pi i$ which means that that the result should be $-\pi i$.
Both of the results are incorrect. Can you spot my mistakes?

A: I agree with Mr Pink's comments and want to use them to expand the OP's intuition.  Often, when you are presented with an ugly looking definite rather than indefinite integral, your first instinct is to not look for a closed form antiderivative.  I regard this as a healthy instinct.
However, at the same time, if you look at this particular integration problem, you should notice that:
(1) $\frac{1}{(x+1)^3}$ can be routinely integrated.
(2) $\ln(x)$ can be routinely differentiated.
Therefore, it is reasonable that if you try integration by parts, the result should be routinely manageable.  So in this case, what the OP did wrong was (arguably) let the fact that the problem is a definite integral lead him down the wrong path.

A: $$J = \int_0^\infty \frac{ \log x \, dx} {(1+x)^3}.$$
Consider $$\oint_C \frac{(\log z)^2 \, dz}{(1+z)^3}$$ around a suitable keyhole contour $C$ that starts at $\epsilon$ goes to $R$, a large (almost) circle of radius $R$, back (below the branch cut) to $\epsilon$ and then clockwise around the origin.
There is a third order pole inside at $z_0 = -1$.  The residue there is $$\text{Residue}_{z=-1} \left[\frac{ (\log z)^2}{(1+z)^3}\right] = 1-i\pi.$$
$$\begin{aligned}
\oint_C \frac{(\log z)^2 \, dz}{(1+z)^3} &=
\int_\epsilon^\infty \frac{(\log x)^2 \, dx}{(1+x)^3} -\int_\epsilon^\infty \frac{(\log x+2i\pi)^2 \, dx}{(1+x)^3}+\int_0^{2\pi} \frac{(\log (Re^{i\theta}))^2 \, Rie^{i\theta} }{(1+Re^{i\theta})^3}\, d\theta
-~\int_0^{2\pi} \frac{(\log (\epsilon e^{i\theta}))^2 \, \epsilon i \, e^{i\theta} }{(1+\epsilon e^{i\theta})^3}\, d\theta
\end{aligned} $$
Let $R\to\infty$ and $\epsilon\to 0$.  The integrals along the "circles" go to zero.
Also, $$\displaystyle \int_0^\infty \frac{dx}{(1+x)^3}=\int_1^\infty \frac{dp}{p^3} = \left. -\frac{p^{-2}}{2} \right|_1^\infty = \frac{1}{2}.$$
So, we have
$$-4i\pi J + 4\pi^2 \left( \frac{1}{2}\right) = 2\pi i (1-i\pi).$$
$$J=-\frac{1}{2}$$

A: The slow & steady way (without contour integration) is integration by parts, then partial fractions, to find an antiderivative; then, taking limits to evaluate the improper integrals.
Integration by parts:
\begin{align*}
\text{Let } u = \ln(x), &\text{ and } dv = (x+1)^{-3}; \\
\text{Then } du = x^{-1}, &\text{ and } v = -(x+1)^{-2}/2. \
\end{align*}
We get $$\int \frac{\ln(x)}{(x+1)^3} dx = \frac{-\ln(x)}{2(x+1)^2} - \int \frac{-dx}{2x(x+1)^2} = \frac{-\ln(x)}{2(x+1)^2} + \int \frac{dx}{2x(x+1)^2}.$$
Partial fractions:
$$\int \frac{dx}{2x(x+1)^2} = \int \left[ \frac{A}{x} + \frac{B}{x+1} + \frac{C}{(x+1)^2} \right]dx,$$
and clearing denominators, we find $$1 = 2A(x+1)^2 + 2Bx(x+1) + 2Cx.$$ Plugging in $x = 0$ gives us $A = 1/2$, plugging in $x = -1$ gives us $C = -1/2$, and plugging in the numerical values of $A, C,$ we find $$1 = (x+1)^2 + 2Bx(x+1) - x = x^2 + x + 1 + 2Bx^2 + 2Bx,$$ which implies $B = -1/2$ as well. So $$\int \frac{dx}{2x(x+1)^2} = \int \left[ \frac{1}{2x} - \frac{1}{2(x+1)} - \frac{1}{2(x+1)^2} \right]dx = \frac{1}{2} \left[\ln(x) - \ln(x+1) + \frac{1}{x+1} \right],$$ therefore
\begin{align*}
\int \frac{\ln(x)}{(x+1)^3} dx &= \frac{1}{2} \left [\frac{-\ln(x)}{(x+1)^2} + \ln(x) - \ln(x+1) + \frac{1}{x+1} \right] \\
 &= \frac{1}{2} \left [\frac{-\ln(x)}{(x+1)^2} + \ln \left(\frac{x}{x+1}\right) + \frac{1}{x+1} \right] + C. \
\end{align*}
Improper integrals:
We evaluate
\begin{align*}
\int_0^\infty \frac{\ln(x)}{(x+1)^3} dx &= \lim_{a \rightarrow 0^+} \left( \lim_{N \rightarrow \infty} \int_a^N \frac{\ln(x)}{(x+1)^3} dx \right) \\
 &= \frac{1}{2} \lim_{a \rightarrow 0^+} \left( \lim_{N \rightarrow \infty} \left [\frac{-\ln(x)}{(x+1)^2} + \ln \left(\frac{x}{x+1}\right) + \frac{1}{x+1} \right]_a^N \right) \\
&= \frac{1}{2} \lim_{a \rightarrow 0^+} \left [\frac{\ln(a)}{(a+1)^2} - \ln \left(\frac{a}{a+1}\right) - \frac{1}{a+1} \right] \\
&= \frac{-1}{2} + \frac{1}{2} \lim_{a \rightarrow 0^+} \left [\frac{\ln(a)}{(a+1)^2} - \ln \left(\frac{a}{a+1}\right) \right] \\
&= \frac{-1}{2} + \frac{1}{2} \lim_{a \rightarrow 0^+} \left [\frac{\ln(a)}{(a+1)^2} - \ln(a) + \ln(a+1) \right] \\
&= \frac{-1}{2} + \frac{1}{2} \lim_{a \rightarrow 0^+} \left [\frac{\ln(a)}{(a+1)^2} - \ln(a) \right], \\
\end{align*}
and by L'Hopital's Rule,
\begin{align*}
\lim_{a \rightarrow 0^+} \ln(a) \left[ \frac{1}{(a+1)^2} - 1  \right] &= \left( \lim_{a \rightarrow 0^+} \frac{1}{(a+1)^2} \right) \lim_{a \rightarrow 0^+} \left[ \frac{\ln(a)}{1/(-2a - a^2)} \right] \\
 &= 1 * \lim_{a \rightarrow 0^+} \frac{1/a * (-2a - a^2)^2}{-(-2 - 2a)} \\
 &= 0, \
\end{align*}
and we finally get $$\int_0^\infty \frac{\ln(x)}{(x+1)^3} dx = \frac{-1}{2} + \frac{1}{2} (0) = \frac{-1}{2}.$$

A: Also OP, the "obvious" contour won't give you the answer you want. Let's try to evaluate $\int_0^\infty \frac{\ln(x) dx}{(x+1)^3}$ using the pictured contour $\gamma$, traversed in the counterclockwise direction:

Pick the branch of $\ln(z)$ inside this contour which satisfies $\ln(-1) = \pi i$. As we let $R \to \infty$ and $\epsilon \to 0$, the two circular pieces of the contour vanish, and we get
\begin{align*}
\oint_\gamma \frac{\ln(z) dz}{(z+1)^3} &= -\int_0^\infty \frac{\ln(x) dx}{(x+1)^3} + \int_0^\infty \frac{\ln(x) + 2\pi i}{(x+1)^3} dx \\
 &= \int_0^\infty \frac{2 \pi i}{(x+1)^3} dx, \
\end{align*}
so that the integral we wanted to evaluate actually cancelled out entirely! So even if you found the residue at $z = -1$ correctly, you wouldn't be able to compute $\int_0^\infty \frac{\ln(x) dx}{(x+1)^3}$ using this contour.


text:
Q: UINavigationController and pushing an openGL UIView = never ending loops I am trying to push an opengl UIView to my navigation controller like this
GraphViewController *gvc = [[GraphViewController alloc] initWithTicker:[listOfItems objectAtIndex:indexPath.row]];
[self.navigationController pushViewController:gvc animated:YES];
[gvc release];

The initWithTicker method looks like this
-(id) initWithTicker:(NSString*)ticker{
self = [super initWithNibName:nil bundle:nil];
if (self) {
    self.title = ticker;
    EAGLView *eagl = [[EAGLView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    eagl.animationInterval = 1.0 / 60.0;
    [eagl startAnimation];
    self.view = eagl;
}
return self;

}
When I go back and forward in my UINavigationController, the drawView method (in EAGLView) keeps looping. Furthermore, if I pushViewController again, the first one does not stop and a new one is created! I've tried making this an instance variable so only one is created and it has the same effect. I would be grateful if anyone has insight as to why this is happening
sergio Suggestion:
-(id) initWithTicker:(NSString*)ticker{
   self = [super initWithNibName:nil bundle:nil];
   if (self) {
      self.title = ticker;
   }
   return self;
}
// Implement loadView to create a view hierarchy programmatically, without using a nib.

- (void)loadView {
    eagl = [[EAGLView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = eagl;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    eagl.animationInterval = 1.0 / 60.0;
    [eagl startAnimation];
    [super viewDidLoad];

}

same behaviour.
---This is how I fixed my drawView looping problem--
-(void)viewDidAppear:(BOOL)animated {
    [eagl startAnimation];
    [super viewDidAppear:animated];
}

-(void)viewDidDisappear:(BOOL)animated {
    [eagl stopAnimation];
    [super viewDidDisappear:animated];

}

--Craigs solution --
if(graphView == nil){
        graphView = [[GraphViewController alloc] initWithTicker:[listOfItems objectAtIndex:indexPath.row]];
    }else{
        [graphView release];
        graphView = [[GraphViewController alloc] initWithTicker:[listOfItems objectAtIndex:indexPath.row]];
    }

A: Would you try executing this code of yours:
EAGLView *eagl = [[EAGLView alloc] initWithFrame:[UIScreen mainScreen].bounds];
eagl.animationInterval = 1.0 / 60.0;
[eagl startAnimation];
self.view = eagl;

inside of loadView? I am not sure about why your view is behaving like you say, but that is the place where you are supposed to build your UI... so it might make a difference...
Furthermore, I would call [eagl startAnimation]; only in viewDidLoad...
Hope it helps...

A: Are you creating a new GraphViewController every time you want to push one onto your navigation stack? If so, it doesn't really matter how you're handling the creation of your EAGLView instance variable, since you're never going to be interacting with that view controller again anyway.
For example:

*

*User taps something, a new GraphViewController is pushed on the stack

*User goes back, this view controller continues to run

*Return to 1. and repeat (thus creating a SECOND GraphViewController, and then a third, and then a fourth... etc.)

What you should probably be doing is maintaining your GraphViewController as an instance variable, and only creating it once. This will ensure that you're in turn only creating one EAGLView.
if (_graphViewController == nil) {
    _graphViewController = [[GraphViewController alloc] initWithTicker:[listOfItems objectAtIndex:indexPath.row]];
}
[self.navigationController pushViewController:_graphViewController animated:YES];

Then, be sure to release the view controller in your dealloc method if you're going to be maintaining it as an ivar.


text:
Q: Deformation of an elliptical ring How will it deform when I compress an elliptical ring along its long axis? For simplicity we could consider that the ring is homogeneous, elastic, has no internal stress at the beginning, and its cross section is small enough compared to its radius.
I think I should be able to find the normal stress and shear stress on any cross section if the ring were rigid. I feel that the next step should be establishing the relationship between stress and strain, but I don't know exactly what to do.

A: Follow these steps:

*

*Draw a nice free body diagram

*Find  the internal moment inside the ring $$M(\theta) = M_A + F b \sin \theta$$

*Find the total strain energy $U$ when the ring deforms under the force $F$ $$ U = \int \frac{ M^2 }{2 E I} \, {\rm d}s = \int \frac{ (M_A + F b \sin \theta)^2 }{2 E I} \sqrt{a^2 - (a^2-b^2)\cos^2 \theta} \, {\rm d}\theta$$ where $M_A$ is the unknown reaction moment at point A, $E$ is the elastic modulus and $I$ is area moment of the section.

*Find the reaction moment by solving $$ \frac{{\rm d} U}{{\rm d}M_A} = 0 $$ for $$M_A \approx \frac{F a (5 \epsilon^2-12)}{6 \pi} $$ with the eccentricity parameter $\epsilon^2 = 1- \left(\frac{b}{a}\right)^2$. The expressions can only be calculated for small values of $\epsilon$ because $U(\epsilon)$ contains elliptical integrals.

*Get the total strain energy (approximation) $$ U \approx \frac{F^2 a^3}{E I} \left( \frac{208-27 \pi^2}{192 \pi} \epsilon^2 + \frac{\pi^2-8}{8\pi} \right)$$

*Calculate the deflection from $U = \int F {\rm d} \delta$ or $$\delta = \frac{{\rm d}U}{{\rm d}F} \approx \frac{2 F a^3}{E I}\left( \frac{208-27 \pi^2}{192 \pi} \epsilon^2 + \frac{\pi^2-8}{8\pi} \right)$$

*The internal stress comes from the bending $$ \sigma(\theta) = \frac{|M| y}{I} \approx \frac{y ( F a \left(  \frac{2}{\pi}-\frac{5 \epsilon^2}{6\pi} \right) + F b \sin \theta)}{I}$$ where $y$ is the half width of the section.

*Maximum stress is at $\theta=\frac{\pi}{2}$ with $$\sigma_{max}  \approx \frac{F\, y}{I} \left( \frac{b (6 \pi+13)}{6 \pi} - \frac{b^3}{6 \pi a^2} \right)$$
The above is only valid for small values of eccentricity, like $\epsilon < 0.5$. I estimate the approximation error at 10% for $\epsilon=0.78$ and 2% for $\epsilon=0.58$
For further details on this method see Roark formulas for Stress, Chapter 9 (p267).


text:
Q: SQL query to linq to SQL query I have the following query in SQL :
SELECT TOP 1 *
FROM sessions
ORDER BY start_time

How should I code it instead in LINQ-to-SQL

A: Use OrderBy for the ordering, and First or possibly FirstOrDefault for the equivalent of TOP 1:
var session = db.Sessions.OrderBy(x => x.StartTime).FirstOrDefault();
if (session != null)
{
    // Use the session
}
else
{
    // There weren't any sessions
}

You could use a query expression for the first part, but it seems pretty pointless - it would end up being more long-winded than using "dot notation", so I'd stick to that.

A: (from i in dc.sessions
orderby i.start_time).Take(1);

or
dc.sessions.OrderBy(x => x.start_time).Take(1);

A: Here's an example:
NorthwindDataContext db = new NorthwindDataContext();

var shippers = from shipper in db.Shippers
                       orderby shipper.CompanyName
                       select shipper;

return shippers.First();

However, using the syntax recommended by Jon Skeet above is probably most appropriate for your simple use case.


text:
Q: (UE4 Assimp) Issues loading mtl texture at runtime I'm using Assimp to import 3d Obj at runtime with Unreal Engine.
I try to import textures thanks to the mtl file, I can get the name texture file, but my problem is, how to use it to import the texture in a UTexture2D and put it in a MID ?
if (scene->HasMaterials())
    {
        for (unsigned int m = 0; m < scene->mNumMaterials; ++m)
        {
            aiMaterial* material = scene->mMaterials[m];
            aiString materialName;
            aiReturn ret;

            ret = material->Get(AI_MATKEY_NAME, materialName);
            if (ret != AI_SUCCESS) materialName = "";

            //Diffuse maps
            int numTextures = material->GetTextureCount(aiTextureType_DIFFUSE);
            aiString textureName;

            if (numTextures > 0)
            {

                ret = material->Get(AI_MATKEY_TEXTURE(aiTextureType_DIFFUSE, 0), textureName);

                std::string textureType = "diffuse_";
                std::string textureFileName = textureType + textureName.data;//Name Texture file
            }
        }
    }

Thank you.

A: I hope I can answer your question to some extent based on what you've provided.
From what I understand in your question is that you have access to the filename (this has to be the full path) that holds your texture and want to import it as a UTexture2D. I haven't worked with importing in C++ before, but I'm assuming it's just as simple to do as in blueprints. In blueprints there's an existing node that does exactly that. Take a look: Import File as Texture 2D
Now you have to remember that importing it as such will not actually create a permanent material for you that you can reference even after resetting your game. This will just import it at runtime for the duration of your game, and delete all references to it after you exit game.
As for putting it in an MID, I'm unsure what an MID is. Do you mean DMI (Dynamic Material Instance)? If not, please clarify and hopefully I'll be of further help. If you do mean DMI, then that's also quite simple, although unfortunately I haven't worked with that in C++ either. However I'll run you through the blueprint and hopefully you can interpret that in C++ yourself.
To create a DMI, you need to have already created a material that holds the parameters that you want to then change when creating the DMI. For a very basic example, here's one I'll use for the purpose of demonstration:  As you can see, I've created a material with a TextureObjectParameter. Name this parameter what you wish, it's important to give it a relevant name as this is what you will refer to when modifying your DMI (in this example case I'm naming it "color").
Next, when you want to create a DMI of this material, this is how it's done in blueprints:  In this picture, just for your example, I import my texture first, then I create a DMI of class TestMaterial, and I modify whichever parameter that I have created in the original material class to what I want it to be (in this example case the parameter to change is "color" and I want it to be changed to the texture I just imported). You can modify as many parameters as you want, but remember these parameters have to exist in the first place in your original material class. Remember though, DMIs also exist just in runtime and all references to them will be deleted after you exit your game, so use them carefully!
I really hope I understood your question properly and I'm very sorry for not being able to provide actual C++ help. Best of luck going forward with your game development though!


text:
Q: Partial rendering performance with parameter in rails I have a collection and want to iterate and render a partial:
<% @programs.each do |program| %>
  <%= render "program", link: program_path(program) %>
<% end %>

For each rendering, I will pass a parameter called link. And it varies based on different situation.

*

*program_path(program)

*admin_program_path(program)

*program.external_link
However, it will spend a huge time to render every partial, so it's a N+1 problem. I also tried to render collections but I don't know how to pass the parameter.
Does anyone know a better way to do it? Or shall I give up partial and put those code to every page which rendering the partial?
Cheers

A: You could use:
<%= render @programs %>

And create:
views/programs/_programs.html.erb

Then you choose the link with a condition in the partial.


text:
Q: Database doesn't get created I am creating a database like this :
SQLiteDatabase db = openOrCreateDatabase("mydata.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
                    try
                    {
                    db.execSQL("CREATE TABLE IF NOT EXISTS vars (id INTEGER PRIMARY KEY ASC, varname,varvalue);");
                    db.execSQL("INSERT INTO vars (varname,varvalue) VALUES (\"user\",\"" + username + "\");");
                    Log.w("Test", "Am executat sql");

                    }
                    catch (SQLiteException e)
                    {
                        Log.w("Exceptie", "Acum or niciodata");
                    }

When i restart my program and i want to open it like this :
  SQLiteDatabase objDb = null;
        try
        {
            objDb =  SQLiteDatabase.openDatabase("mydata.db", null, SQLiteDatabase.OPEN_READWRITE);

        }
        catch(SQLiteException e)
        {
            //addShortcut();//setShortCut(getApplicationContext(),"GpsRo");
            //setContentView(R.layout.main);
            Log.w("Exceptie", e.getMessage());
            showForm = true;
        }

I get an exception : unable to open database file...
What am i doing wrong ?

A: Your table creation query doesn't look good. Do it as below:
"CREATE TABLE IF NOT EXISTS vars
(id INTEGER PRIMARY KEY AUTOINCREMENT,
varname TEXT,
varvalue TEXT);"

A: As i can see you are inserting data For varName and varValues not for id.Here id is a primary key ( that means it cannot be null and duplicate).So you must enter value for that you cannot left it blank and also you can go for AUTOINCREMENT.
Try something like this :
db.execSQL("CREATE TABLE IF NOT EXISTS vars (id INTEGER PRIMARY KEY AUTOINCREMENT ASC, varname,varvalue);");

A: Your database is in the wrong place:
"mydata.db" means your Databasefile is in root: (Path: /mydata.db). Your App can't write in the root folder.
Try context.getFilesDir() + "/mydata.db" instead.
In one Command:
SQLiteDatabase db = openOrCreateDatabase(context.getFilesDir()"/mydata.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);

A: to open your data base you need to declare something like this:
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private final Context mCtx;

mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();

to make your Database writable
My suggestion is to go through  http://developer.android.com/resources/tutorials/notepad/index.html
to learn more about SQLiteDataBases, there you will find a class called notesDbAdapter that you can use as a base, there you'll find a open() class that open the Data Base.
in other case to use the method openDataBase() you need to find the path of your DB on the device, and actualize  mydata.db to the full path of the DB.


text:
Q: CF - How do i access a .gif in my Resources folder I have added a simple .gif file into Resources folder in my project.
Now i have created a user control with pictureBox.
How can i add the .gif to pictureBox.Image = new Bitmap (path).
What is the path in this case?
thanx !

A: I think you can do it in the following way:
// Create a MemoryStream from the .gif file resource
MemoryStream ms = new MemoryStream(YourApplicationName.Properties.Resources.GifFileName);

// Instantiate a new Bitmap using the created MemoryStream
pictureBox.Image = new Bitmap(ms);

Not completely sure if this works (cannot test it at the moment) but it should point you in the right direction.


text:
Q: Why can't I double my sample to decrease the variance of the estimator in the OLS? I'm preparing an exam in econometrics, and I have some trouble answering one question.
It writes:
"One of your graduate students, working on a joint empirical project with you, comes to you and says : "You'll be happy professor : our estimations lacked precision, so I did the estimation again after having duplicated the sample so that its size is now 2N. Clever idea, as the estimated variance of my OLS estimator on this sample is now much lower !" What do you answer ?"
It seems obvious that doubling artificially the size of the sample is stupid, but I have trouble finding why. Could you help me with this?


text:
Q: How does the photon detector in this video work? In this video:
https://www.youtube.com/watch?v=A9tKncAdlHQ
How does this photon detector at 6:58 work, mechanically speaking? Is this basically just like a camera, that beeps when it is hit by light?
But how can it trace the path of the photon if the photon does not hit it and instead hits the screen - does it register electric radiation, or EM radiation, emitted by the photon, and thus can track a photon from the "side"?
At 8:03 he notes that the result changes if you unplug the detector. I am assuming that this is explained by some sort of observer effect, but what is that observer effect exactly - what is changing physically when you unplug the detector? Is the detector just like a camera or does it, itself, emit radiation?
I also don't know how literally to take his use of the term "unplug", maybe he means physical removal of the detector...?
Also, is there video anywhere online of the experiment being performed with this specific photon detector type mentioned in the video?
If any of my understanding is wrong, please correct me.


text:
Q: Regex to match sentence with particular pattern I want to extract certain sentences from a bunch of sentences. These sentences have a particular pattern but my regex fails when it encounters and alphanumeric string: See below example test string
"""Dear User,
Slow movt is at placeA ( Ohio | Missourri ) : placeB all d way to placeC is a no go area. wetin dey happen ooo. cc ( 2014-11-19 06:30 PM ) //passes my regex
Slow movt is at PlaceD ( Denver | Houston ) : .3 50pm. placeE&gt &gt ketu b2b //t.co/a7wmlxo6eu ( 2014-11-19 03:51 PM ).//fails my regex but passes if I remove alphanumerals
Average blah blah blah  (a|b) //t.co/a7nmloo6eu ( 2014-11-13 03:16 PM ).// passes my regex if no alphanumerals
yours sincerely
TL"""

This is what I have come up with in my Regex:
((Slow|Average|Fast)\D+).(\(\s?\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}\s[AP]M\s\)\.)

Any help rendered is highly appreciated. Please note I need to extract all matches, so the perfect solution for my above string will yield 3 matches excluding the "Hi User" and "Your sincerely TL" from the matches.

A: \D+ only matches non-digits, so it fails on 1pm.
Can you simply match "anything"?
((Slow|Average|Fast).*)(\(\s?\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}\s[AP]M\s\)\.)

Test it live on regex101.com.

A: Based on your currently stated requirements
((Slow|Average|Fast).+)(\(\s?\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}\s[AP]M\s\)\.?)

does work: RegEx101.
If you have more restrictions to meet, please, comment.


text:
Q: Proof that $ SO_n $ is maximal in $ SU_n $ $ SO_n $ is maximal among the proper connected closed subgroups of $ SU_n $ (at least this is true for small $ n $). What is a conceptual proof of this fact? Equivalently what is a proof that $ \mathfrak{so}_n $ is maximal in $ \mathfrak{su}_n $?
Can we perhaps make a general argument that for any irreducible symmetric space $ G/K $ it is the case that $ K $ is a maximal closed connected subgroup of $ G $?


text:
Q: Attempting to create new Android Application with adt tools in Eclipse. R.Java missing, even after clean and rebuid; Having a problem creating my new android application. I create the new project and I get the error that R cannot be resolved to a variable. I don't import (as I seen not to do on other threads similar to this). I clean and rebuild but R.Java never appears in gen. I've tried a few things but to no avail. Might this be a problem with the version of ADT tools I downloaded or is there something else wrong?
EDIT: This is on windows

A: Your project fails to generate R file only when your project fails to build. 99% this is due to an error in your XMLs.
Double check your recently changed XMLs for errors.

A: Check your xml file ,solve the error,Restart project and perform cleaning again. If that doesn't help then follow following steps:-
1. Delete the project.
2. Create New project.

That will resolve the issue

A: I have just worked through this problem, so I can provide the answer that worked on my system, which is Ubuntu 12.10 64 bit. I found that the following three libraries needed to be installed: libncurses5:i385, libstdc++6:i386, and lib32z1.
The first two libraries are required to run adb. You can test if they are needed by going into /tools or /platform-tools and running adb. If you get an error saying the adb file is not present, but in fact, you can see that it is present, then one part of the problem is that you need these two libraries: libncurses5:i386, and libstdc++6:i386. You can install them with
sudo apt-get install libncurses5:i386 and
sudo apt-get install libstdc++6:i386.
That will get adb working. But I found that this wasn't enough. To automatically generate the R.java file when creating a new project you also need a third library: lib32z1. It can be installed with
sudo apt-get install lib32z1.
That worked on my system, I've listed the guides that I found helpful in a blogpost. If you're building on a different platform it would be helpful if you would clarify the platform that you are developing on.


text:
Q: Как происходит конвертация объектов fstream(ifstream/ofstream) в bool Мне не особо понятно, каким образом объекты классов fstream/ofstream/ifstream конвертируются в bool. Все, что я нашел, это то, что конвертация происходит путем каста к void* и при достижении конца файла мы получаем 0(false). Теперь вопросы:как вообще происходит конвертация? Что мы получаем, как результат каста (адрес на что?)? Что мы получаем, если файл не удается открыть? Можно ли выражения if(!file) использовать как полноценный заменитель file.is_open()?
Я так понимаю, что каст проверяет флаги состояния и, если не goobit, то возвращается false.
Пример кода:
#include <iostream>
#include <fstream>

int main() {
    std::ifstream file("someFile.txt");

    if(!file) {
        std::cout << "It\'s fine\n";
    }
    else {
        std::cout << "End\n";
    }
}

A: Нашел на англоязычном StackOverflow:вот здесь. is_open() проверяет, открыт ли файл и игнорирует все выставленные флаги и готовность файла к вводу/выводу. Каст к bool, в первую очередь, опирается на флаги. Поэтому, если вы сделаете так std::ifstream file, то is_open() выдаст false, а (file) - true.
Дополнено:
Ответ найден Здесь