text:
Q: Upgrading git with brew gives: No such file or directory - /usr/local/Cellar/git? I am attempting to upgrade git. I am running into a variation of what seems to be common pathing problem with upgrading git and the git version that comes installed with Xcode. I'm new to git, and fairly new to programming in general. Please keep that in mind, thanks.
I'm running OSX 10.9.5 and have Xcode 6.1.1.
I followed the instructions here: blog post.
When I run brew doctor I get a bunch of warnings:

Please note that these warnings are just used to help the Homebrew maintainers with debugging if you file an issue. If everything you use
    Homebrew for is working fine: please don't worry and just ignore them.
    Thanks!

Warning: Python is installed at /Library/Frameworks/Python.framework
Homebrew only supports building against the System-provided Python or
  a brewed Python. In particular, Pythons installed to /Library can
  interfere with other software installs.
Warning: Unbrewed dylibs were found in /usr/local/lib. If you didn't
  put them there on purpose they could cause problems when building
  Homebrew formulae, and may need to be deleted.
Unexpected dylibs:
      /usr/local/lib/libtcl8.6.dylib
      /usr/local/lib/libtk8.6.dylib
Warning: Unbrewed header files were found in /usr/local/include. If
  you didn't put them there on purpose they could cause problems when
  building Homebrew formulae, and may need to be deleted.
Unexpected header files:
      /usr/local/include/fakemysql.h
      /usr/local/include/fakepq.h
      /usr/local/include/fakesql.h
      /usr/local/include/itcl.h
      /usr/local/include/itcl2TclOO.h
      /usr/local/include/itclDecls.h
      /usr/local/include/itclInt.h
      /usr/local/include/itclIntDecls.h
      /usr/local/include/itclMigrate2TclCore.h
      /usr/local/include/itclTclIntStubsFcn.h
      /usr/local/include/mysqlStubs.h
      /usr/local/include/odbcStubs.h
      /usr/local/include/pqStubs.h
      /usr/local/include/tcl.h
      /usr/local/include/tclDecls.h
      /usr/local/include/tclOO.h
      /usr/local/include/tclOODecls.h
      /usr/local/include/tclPlatDecls.h
      /usr/local/include/tclThread.h
      /usr/local/include/tclTomMath.h
      /usr/local/include/tclTomMathDecls.h
      /usr/local/include/tdbc.h
      /usr/local/include/tdbcDecls.h
      /usr/local/include/tdbcInt.h
      /usr/local/include/tk.h
      /usr/local/include/tkDecls.h
      /usr/local/include/tkPlatDecls.h
Warning: Unbrewed .pc files were found in /usr/local/lib/pkgconfig. If
  you didn't put them there on purpose they could cause problems when
  building Homebrew formulae, and may need to be deleted.
Unexpected .pc files:
      /usr/local/lib/pkgconfig/tcl.pc
      /usr/local/lib/pkgconfig/tk.pc
Warning: Unbrewed static libraries were found in /usr/local/lib. If
  you didn't put them there on purpose they could cause problems when
  building Homebrew formulae, and may need to be deleted.
Unexpected static libraries:
      /usr/local/lib/libtclstub8.6.a
      /usr/local/lib/libtkstub8.6.a
Warning: /usr/bin occurs before /usr/local/bin This means that
  system-provided programs will be used instead of those provided by
  Homebrew. The following tools exist at both paths:
2to3
easy_install
easy_install-2.7
gcc-4.2

Consider setting your PATH so that /usr/local/bin occurs before
  /usr/bin. Here is a one-liner:
      echo export PATH='/usr/local/bin:$PATH' >> ~/.bash_profile

At first I ignored these errors as per the brew message at the beginning, but when I run brew upgrade git I get the following:
Error: No such file or directory - /usr/local/Cellar/git

After Googling the problem I found people had solved a similar problem (same error different path specified) by editing their bash.profile, so I ran the echo command
echo export PATH='/usr/local/bin:$PATH' >> ~/.bash_profile
I also tried
echo export PATH='/usr/local/Cellar/git:$PATH' >> ~/.bash_profile

and tried manually adding these export PATH commands to my .bash_profile using nano, but none of this seems to have helped.
Any help would be appreciated?

A: So I was able to solve this problem by uninstalling git twice and then reinstalled the latest version of git. This removed both the pre-installed version of git and the one that I had installed, eliminating the pathing problem. I ran:
which git

and then ran sudo rm -rf /absolute/path/to/git
which deleted one of the git programs that had been installed. Then I ran both commands again, but the second time which git returned a different path that I used with the second sudo rm -rf /absolute/path/to/git. Finally, I installed git using brew.
Not rocket science but it seems to have worked.

A: I assume you have some version of git already installed? (Type git --version or which git to check.)  If you don't, then go ahead and let brew install git and you're done.
However, assuming you do already have git installed:
Option 1: If brew does not recognise the current git install
Overall this is a super quick fix... worked for me
Run $ brew upgrade git
If the result tells you not installed, then brew doesn't recognise the current installation... your fastest option is to let brew install from scratch:

*

*Rename your existing Apple-installed git (example)

*Let brew install the latest version via brew install git (example)

That step 1, re-naming the Apple-installed git, is just one way to avoid the conflict between Apple-installed Git and the new one you're installing via Homebrew. For a second example of this, see this other post on the blog you linked to for more:
http://rayhightower.com/blog/2014/12/18/git-vulnerability-on-mac-os-x/
Option 2: Getting brew to recognise the git install you have
If you think the above is too clumsy leaving an old git install hanging out on your computer...
An alternative option might be to play with links? My initial attempt at brew link didn't work for me. I didn't try to solve via a symlink or by defining any $PATH. There's surely a neater option than simply abandoning the existing install, but Option 1 sufficed for me for today.

A: This worked for me:

*

*Rename your existing Apple-installed git (https://stackoverflow.com/a/27646134)

*Fix brew's installation of git (No such keg: /usr/local/Cellar/git)

A: By no means an expert but for me, I basically did:

*

*Backup original git directory

*Install Git with Homebrew

*Restart (or source) shell

~ > which git
/usr/bin/git
~ > sudo mv /usr/bin/git /usr/bin/git-original
~ > which git
git not found
~ > brew install git
~ > source /etc/profile
~ > git --version
git version 2.4.3


text:
Q: mysql sum of product rows where data stamp within cost data range I have three tables product, cost and account
CREATE TABLE `product` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `account_id` int(11) DEFAULT NULL,
  `name` varchar(255) NOT NULL DEFAULT '',
  `datestamp` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;

CREATE TABLE `cost` (
  `account_id` int(11) NOT NULL,
  `amount` float NOT NULL,
  `datestamp` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `account` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=103 DEFAULT CHARSET=utf8;

+-----+----------+-----------------+
| id  | name     | email           |
+-----+----------+-----------------+
| 101 | Acme Inc | jondoe@host.com |
+-----+----------+-----------------+

+------------+--------+------------+
| account_id | amount | datestamp  |
+------------+--------+------------+
|        101 |      5 | 2014-01-01 |
|        101 |     10 | 2014-01-03 |
|        101 |     15 | 2014-01-06 |
+------------+--------+------------+

+----+------------+---------+------------+
| id | account_id | name    | datestamp  |
+----+------------+---------+------------+
|  1 |        101 | Alfa    | 2014-01-01 |
|  2 |        101 | Bravo   | 2014-01-02 |
|  3 |        101 | Charlie | 2014-01-03 |
|  4 |        101 | Delta   | 2014-01-04 |
|  5 |        101 | Echo    | 2014-01-06 |
|  6 |        101 | Foxtrot | 2014-01-08 |
+----+------------+---------+------------+

I'd like to return the per unit cost and total quantity for each
account by matching the product row to it's cost based on the date stamps
and grouping those by cost and account so I can sum them.
Here is as far as I have got with the query but I'm stuck at trying
to match the product to the right price.
select
    a.id as account_id,
    count(p.id) as qty,
    c.amount as cost_per_unit,
    c.datestamp as cost_date,
    p.datestamp as product_date
from product p
left join account a on a.id = p.account_id
left join cost c on 1
where p.datestamp <is within right range based on cost date stamps>
group by c.amount, a.id
;

So if the amount was $5 on 2014-01-01 and $10 on 2014-01-3 and $15
on 2014-01-06 each product date stamped before the $10 date
would be $5 and before the $15 would be $10 and so on..
Any suggestions on how to approach this one?
-- edit
Based on the answer below I was able to get what I needed with
SELECT
    a.id AS account_id,
    COUNT(p.id) AS qty,
    c1.amount AS cost_per_unit,
    c1.datestamp AS cost_date
FROM cost c1
    INNER JOIN account a ON a.id = c1.account_id
    LEFT JOIN cost c2 ON c2.datestamp =
    (
        select datestamp
        from cost
        where account_id = a.id
        and datestamp > c1.datestamp
        order by datestamp ASC
        LIMIT 1
    )
    LEFT JOIN product p ON p.datestamp >= c1.datestamp
WHERE p.datestamp < c2.datestamp OR c2.datestamp IS NULL
GROUP BY a.id, c1.amount
ORDER BY c1.datestamp ASC
;

A: This is likely to be brutally inefficient in a production environment, but for your tinkering enjoyment this query should get you most of the way there. I know you're able to polish off the edges as you're doing great so far :)
SELECT a.id AS account_id,
    COUNT(p.id) AS qty,
    c2.amount AS previous_cost_per_unit,
    c1.amount AS cost_per_unit,
    c1.datestamp AS cost_date,
    p.datestamp AS product_date
FROM product p
    INNER JOIN account a ON a.id = p.account_id
    INNER JOIN cost c1 ON c1.account_id = p.account_id AND c1.datestamp = p.datestamp
    LEFT JOIN cost c2 ON c2.datestamp = (SELECT MAX(datestamp) FROM cost WHERE account_id = c1.account_id AND datestamp < c1.datestamp)
GROUP BY account_id, product_date

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is recommended way to compare ReflectionOnlyType with Type? I have realized that I cannot directly compare types from reflection only loaded assemblies with types resolved by typeof, even they both are from the same assembly.
I am currently using:
 reflectionOnlyType.AssemblyQualifiedName == type.AssemblyQualifiedName.
What is the recommended way?

A: This may not be a definitive answer, but it's a bit better than what's in the comments.
Having just asked myself the same question, I did start with AQN equivalency as a first step.  The problem with that is that if the assembly isn't signed, it is trivial to make a duplicate assembly with the same AQN.  (Note, I'm not coming from a security aspect; if you're loading assemblies you shouldn't rely on this answer to keep bad code from executing within your application)
Another option is to use Type.GUID, which some random people on the internet say is generated deterministically, but includes properties of the Type that can be controlled by the programmer.  Therefore the possibility for collisions still remain.  (And this shouldn't be used for security purposes)
There doesn't seem to be a better choice than one of the above (pls answer if I'm wrong!).  If you're reflecting and loading from the same folder (e.g., your bin folder), then using AQN should be adequate. Type.GUID gives a little bit better protection from collisions, and it feels better than using a string comparison.
If you really really need to know, you'd probably have to go overboard, comparing cryptographic hashes of both containing assemblies to verify they are the same, then use the AQN comparison and possibly other attributes of the Type.

A: I solved it by loading the System.ReflectionOnly type using the runtime type I have. That seems to be the safest way:
// Comes from an assembly loaded as reflection only
var reflectionOnlyTypeFromSomeAssembly = GetItFromSomewhere();

// Comes from an assembly that is running
var reflectionOnlyTypeFromRuntimeType =
        Type.ReflectionOnlyGetType(typeof(myType).AssemblyQualifiedName, false, true);

// Now you can compare
if (reflectionOnlyTypeFromSomeAssembly == reflectionOnlyTypeFromRuntimeType)
{
  // do something?
}


text:
Q: NSUserDefaults is not saving globally I have a NSUser Bool() that is in the a global. when i close the app and run it again the bool does save but when i take my exit sugue to my sKcene the sKcene still thinks the Bool value is what it originally was even if. I have change the value using the SwitchMainOnOff function. please help.
import AVFoundation
import Foundation
import SpriteKit
import GameKit
import UIKit
import iAd

var buttonState = NSUserDefaults.standardUserDefaults().objectForKey("buttonState") as! Bool

class SoundController: UIViewController {

func SwitchMainOnOff() {

        if SwitchMain.on == true {
            println("SwitchMain is on from function")
            SwitchMain.on = true
            NSUserDefaults.standardUserDefaults().setObject(Bool(true), forKey:"buttonState")

        }
        if SwitchMain.on == false {
            println("SwitchMain is off from function")
            SwitchMain.on = false
            NSUserDefaults.standardUserDefaults().setObject(Bool(false), forKey:"buttonState")

        }

     }
func Correct() {
    if buttonState == true{
        println("SwitchMain is on")
        SwitchMain.on = true
    }

    if buttonState == false{
        println("SwitchMain is off ")
        SwitchMain.on = false
    }
  }

@IBAction func SwitchMain(sender: AnyObject) {
    SwitchMainOnOff()

    }

I have a UISwitch that will change as shown to check if the Bool saved when moving to other scenes. It called SwitchMain.

A: Try to set your bool in NSUserDefaults this way:
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "buttonState")

And your code will be:
if SwitchMain.on == true {
    println("SwitchMain is on from function")
    SwitchMain.on = true
    NSUserDefaults.standardUserDefaults().setBool(true, forKey: "buttonState")

}
    if SwitchMain.on == false {
    println("SwitchMain is off from function")
    SwitchMain.on = false
    NSUserDefaults.standardUserDefaults().setBool(false, forKey: "buttonState")

}

And read values this way:
let switchState = NSUserDefaults.standardUserDefaults().boolForKey("buttonState")

A: Please call following method after you update NSUserDefaults:
NSUserDefaults.standardUserDefaults().synchronize()

Also, mould the code as Dharmesh has mentioned below.


text:
Q: Accessing loop variable outside loop in Jinja2 We are writing a for loop in Jinja2, which will keep on concatenating the list variable to a string until the end of the list.We are storing the string to a variable. After the loop completes, we want to print the variable.
The code to perform that is as follows
{% set HOSTLIST = groups['master'] | map('extract', hostvars, ['ansible_default_ipv4', 'address'])| list %}
{% set TEST = "spark://" %}
{% for host in HOSTLIST %}
     {% set sample = TEST + host  %}
     {% set TEST = sample+',' %}
{% endfor %}

{{ TEST }}

Can anybody point me, where we are doing a mistake.
Our output is as follows:
 spark://

But the expected output should be like:
 spark://192.168.49.111:7077,192.168.49.112:7077,

A: Why not use it like this?
spark://{{ groups['master'] | map('extract', hostvars, ['ansible_default_ipv4', 'address']) | map('regex_replace','$',':7077') | list | join(',') }}

Your original request to modify outer-scope variable inside a loop is solved only with jumping through some hoops, see Jinja2: Change the value of a variable inside a loop.


text:
Q: The image of an $\epsilon$-neighborhood of a function with a nonzero limit. The following is from Gaughan's Introduction to Analysis:
Suppose $g:D\rightarrow \mathbb{R}$ with $x_0$ and accumulation point of $D$ and $g(x)\neq 0$ for all $x\in D$. Further, assume that g has a limit at $x_0$, and $lim_{x\rightarrow x_0}f(x)\neq 0$. Prove that There is a positive $\epsilon_0$ and positive $M$ such that for all $x\in (x_0-\epsilon_0, x_0+\epsilon_0)\cap D$, $|f(x)|\geq M$.
Here is what I have tried so far:  Since $f(x)$ has a limit, L, at $x_0$, for every $\epsilon>0$ there exists some positive $\delta$ such that  whenever $x\in D$ and $0<|x-x_0|<\delta$, $|f(x)-L|<\epsilon$. If we set $\epsilon_0 = \delta$, then we have $-\epsilon_0<0<|x-x_0|<\epsilon_0$, so $x_0-\epsilon<x<x_0+\epsilon$, and thus $x\in (x_0-\epsilon_0,x_0+\epsilon_0)\cap D$.  We know that under these conditions, for every $\epsilon$ we choose, $|f(x)-L|<\epsilon$. This is where I'm stuck. It seems like there should be some $\epsilon$ that we can choose so that supposing $|f(x)|<M$ gives us a contradiction, or something like that.
Thanks!

A: Take $\epsilon =\frac {|L|} 2$ and use $|f(x)| \geq |L| -|f(x)-L|>\frac {|L|} 2$.


text:
Q: How to get API Tooling to work in Eclipse I have been having a real hard time getting API Tooling to work in Eclipse 3.4.2.  It keeps telling me:
The minor version should be incremented in version 3.4.0.qualifier, since new APIs have been added since version 3.4.0.40001
That being said, I have generated the plugins that are used for the baseline from the exact same code that it is being analyzed against.  The API Tools docs say that it compares the current code against the baseline to see if there are any differences.  I can't see how there could be differences if the built version is built from the current code.
The way that I tested it:

*

*Create a new eclipse workspace

*Create a new Plug-in Project with API Analysis turned on

*Add a simple class to that plugin and export the package with that class in it

*Build/Export that plugin to some location on your hard drive

*Set the workspace baseline to that location and do a full build

You get an error for the project in your problems view.
Thanks,
-One very perplexed user

A: Looks like this is something that got fixed in 3.5.  Too bad my company doesn't want us using 3.5 in case there are any incompatibility issues. (there were 3.3 to 3.4)
My recommendation to anyone who wants to do Eclipse API Analysis is to use 3.5.

A: First off, I apologize for jumping on a thread late after its "active time" but I am currently running into this exact situation, but with Eclipse Helios 3.6.
From your answer, you noted that something was fixed in 3.5.  Are you aware of what this exact fix was AND if you have yet been able to verify that it is working under Eclipse Helios 3.6?
I would really like to have PDE API tooling working but I'm nearing my time allowed on this effort and need to move forward onto some pending tasks.
Thanks!
EDIT: I would have posted this in a followup link but did not see any such links available.


text:
Q: Finding full lengths I have an input file like this
         id_per start end   s_len
con1 P1  95.27   1    148    148
con2 P2  89.86   4    148    148
con3 P5  76.67   1    512    516

For every con I have P (protein). I want to find proteins that have full lengths, if I know the start site, end site and the length of every P, it is possible. The script below does this. However, now my question is, I would like to find lengths, but taking into consideration also +- 10 units, both from start and end sites.
import re
output=open('res.txt','w')
output2=open('res2.txt','w')
f=open('file.txt','r')
lines=f.readlines()
for line in lines:
    new_list=re.split(r'\t+',line.strip())
    id_per=float(new_list[2])
    s_start=int(new_list[3])
    s_end=int(new_list[4])
    s_len=int(new_list[5])
    if s_start == 1 and s_end == s_len and id_per >= 30:
        new_list.append(s_start)
        new_list.append(s_end)
        new_list.append(s_len)
        new_list.append(id_per)
        output.writelines(line)
    else:
        output2.write(line)
f.close()
output.close()
output2.close()

A: If I understand you correctly, your condition can be rewritten as: |distance_from_start_to_end - stated_length| < 10. Here is how to express this in Python:
with open('example.txt', 'r') as infile, \
        open('output.txt', 'w') as outfile, \
        open('errors.txt', 'w') as errfile:
    for line in in file:
        id_per, s_start, s_end, s_len = (line.split()[i] for i in [2, 3, 4, 5])
        start_to_end = (int(s_end) - int(s_start)) + 1
        if abs(int(s_len) - start_to_end) < 10:
            outfile.write(line)
        else:
            errfile.write(line)

There are other improvements in this snippet with respect to your original code:

*

*use with, a context manager, to avoid having to close the file handles explicitly

*you do not need the re module, split can accept a tabulator as character to split by.

*use ,, the tuple operator, to deconstruct automatically the tokens splitted from the line

*ignore fields by setting them to _

*removed the new_list variable because it seems it is not used. Maybe I misunderstood your snippet?


text:
Q: Extracting a value from a fields XML? (Using SQL Server 2016 standard)
I my table "Persons", I have an NVARCHAR(MAX) field called "Log".
This is a sample of what can be in that log:
<?xml version="1.0" encoding="iso-8859-1" ?>
<ArrayOfLogItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <LogItem>
        <OldValue xsi:type="xsd:decimal">40</OldValue>
        <NewValue xsi:type="xsd:decimal">41</NewValue>
        <FieldName>age</FieldName>
    </LogItem>
    <LogItem>
        <OldValue xsi:type="xsd:decimal">2000</OldValue>
        <NewValue xsi:type="xsd:decimal">2100</NewValue>
        <FieldName>salary</FieldName>
    </LogItem>
    <LogItem>
        <OldValue xmlns:q1="http://microsoft.com/wsdl/types/" xsi:type="q1:guid">e5e6aa24-4f2f-437d-bf16-21724e9c61b2</OldValue>
        <NewValue xmlns:q2="http://microsoft.com/wsdl/types/" xsi:type="q2:guid">370cee00-f51a-4bf0-a8bf-c0f1de025a0a</NewValue>
        <FieldName>user_ID</FieldName>
    </LogItem>
</ArrayOfLogItem>

I need to figure out, if the log field has the row with the fieldname "salary" - and if so, I need to extract the old value (2000) and the new value (2100).
Is that possible?
This is how far I've reached...
DECLARE @xml xml
SET @xml =
'<?xml version="1.0" encoding="iso-8859-1" ?>
<ArrayOfLogItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <LogItem>
        <OldValue xsi:type="xsd:decimal">40</OldValue>
        <NewValue xsi:type="xsd:decimal">41</NewValue>
        <FieldName>age</FieldName>
    </LogItem>
    <LogItem>
        <OldValue xsi:type="xsd:decimal">2000</OldValue>
        <NewValue xsi:type="xsd:decimal">2100</NewValue>
        <FieldName>salary</FieldName>
    </LogItem>
    <LogItem>
        <OldValue xmlns:q1="http://microsoft.com/wsdl/types/" xsi:type="q1:guid">e5e6aa24-4f2f-437d-bf16-21724e9c61b2</OldValue>
        <NewValue xmlns:q2="http://microsoft.com/wsdl/types/" xsi:type="q2:guid">370cee00-f51a-4bf0-a8bf-c0f1de025a0a</NewValue>
        <FieldName>user_ID</FieldName>
    </LogItem>
</ArrayOfLogItem>'

SELECT   ???

...and I'm stuck.
Any idea if it is possible?
Thanks


text:
Q: Variable inaccessible inside callback function I have a variable deleteFlag which is inaccessible inside a function even though the variable's scope is global.
Explanation (Pls refer my code simultaneously):
Here, I am trying to get a MongoDB collection details, the collection store a date document (result[i].date). The variable difResult stores the difference between the current date and the date fetched from MongoDB. And let's say if the value of difResult is more than a specific threshold then handle respective if-else conditions.
My if block i.e. if(difResult>20000) has a child-process, exec function and a callback function to delete MongoDB collection, now in this function I am trying to access var deleteFlag which is sort inaccessible.
Why? And how can I make is accessible inside my function?
app.js
MongoClient.connect("mongodb://localhost:27017/", {
  useUnifiedTopology: true
}, function(err, db) {
  if (err) throw err;
  var dbo = db.db("dbName");
  dbo.collection("colName").find({}).toArray(function(err, result) {
    if (err) throw err;
    for (var i = 0; i < result.length; i++) {
      var difResult = Math.round((today - result[i].date));
      var deleteFlag = result[i].date; // Declared here and should be accessbile within the function
      console.log("Delete Flag " + deleteFlag.toISOString()); //Show correct value here
      console.log("Result Date " + result[i].date);
      if (difResult > 20000) {
        var result2 = cp.exec("rm -rf /path/" + deleteFlag.toISOString(), function(error, stdout, stderr) {
          if (error !== null) {
            console.log('exec error: ' + error);
            return res1.status(500).json({
              error: "Failed!"
            });
          } else {
            MongoClient.connect("mongodb://localhost:27017/", {
              useUnifiedTopology: true
            }, function(err, db) {
              console.log("Delete Flag From Collection ", +deleteFlag.toISOString());
              //The above console log gives NaN or null value
              //Suggest that var deleteFlag is not accessible inside this callback function
              if (err) throw err;
              var dbo = db.db("dbName");
              var myquery = {
                date: deleteFlag
              };
              dbo.collection("colName").deleteOne(myquery, function(err, obj) {
                if (err) throw err;
                console.log("1 document deleted");
                db.close();
              });
            });
          }
        });
      } else {
        console.log("Else msg");
      }
    }
    db.close();
  });
});

A: You don't have to call the database twice you can optimize your code and use it like this
    MongoClient.connect("mongodb://localhost:27017/", {
  useUnifiedTopology: true
}, function(err, db) {
  if (err) throw err;
  var dbo = db.db("dbName");
  dbo.collection("colName").find({}).toArray(function(err, result) {
    if (err) throw err;
    for (var i = 0; i < result.length; i++) {
      var difResult = Math.round((today - result[i].date));
      var deleteFlag = result[i].date; // Declared here and should be accessbile within the function
      console.log("Delete Flag " + deleteFlag.toISOString()); //Show correct value here
      console.log("Result Date " + result[i].date);
      if (difResult > 20000) {
        var result2 = cp.exec("rm -rf /path/" + deleteFlag.toISOString(), function(error, stdout, stderr) {
          if (error !== null) {
            console.log('exec error: ' + error);
            return res1.status(500).json({
              error: "Failed!"
            });
          } else {
          var myquery = {
                date: deleteFlag
              };
              dbo.collection("colName").deleteOne(myquery, function(err, obj) {
                if (err) throw err;
                console.log("1 document deleted");
              });
          }
        });
      } else {
        console.log("Else msg");
      }
    }
    db.close();
  });
});

However if for whatever reason you need to call the database twice then store deleteFlag values in an array and then access the array wherever you like


text:
Q: Send fb notification from your own website I cant seem to figure this out. How can I send a FB notification from my own website? Is there an API or something? A way at all to send FB noifications from an external domain?
Either PHP or JS will do

A: These are the steps you need to follow:

*

*You need Facebook API Key, from Facebook Developers.

*Create an Application in Facebook.

*Give the necessary permissions.

*Send the notifications from your server using push notifications.

All the details are there in FB SDK.


text:
Q: how printk is implemented while booting I am porting latest version Linux (linux-stable) to a customized ARM926TEJ-S board, and I want to print messages in the initializing phase. So I am trobuled by the problems of how can i let the uart work in the kernel initializing phase.
printing linux banner in init/main.c:start_kernel()
eventually call printk() to print the message. My question is how the printk() is implemented and how can I let the printk() output to my uart.
Because I know the driver of uart is not initialized there, they are initialize by rest_init() called in the end of start_kernel(). rest_init() will consequently call do_initcalls() and eventually call module_init() of drivers.
And I know putstr("Uncompressing Linux..."); in the uncompressing phase is implemented by arch/arm/boot/compressed/debug.S that using waituart/senduart... that implemented by the files setting by CONFIG_DEBUG_LL_INCLUDE


text:
Q: Access a container from another I see other posts but don't work in my case, maybe i'm beeing dumb.
I tried everything.
My last version of Dockerfile:
version: '3.4'

services:
  bookmemoriesfrontend:
    image: ${DOCKER_REGISTRY-}bookmemoriesfrontend
    build:
      context: .
      dockerfile: Frontend\BookMemoriesFrontend\Dockerfile
    ports:
      - "8000:443"
    depends_on:
      - booksapi
      - authorsapi

  authorsapi:
    image: ${DOCKER_REGISTRY-}authorsapi
    build:
      context: .
      dockerfile: Services\AuthorsAPI\Dockerfile
    ports:
      - "8002:443"

  booksapi:
    image: ${DOCKER_REGISTRY-}booksapi
    build:
      context: .
      dockerfile: Services\BooksAPI\Dockerfile
    ports:
      - "8001:443"

When I open CLI from BookMemoriesFrontend, I tried several curl commmand, when i try :
curl Booksapi/api/book

I think it will receive the api result and I dont receive nothing in result.
When I run CLI my machine:
curl -s https://localhost:8001/api/book

It gives the API result.
Please help me, I'm around this almost a week.

A: You should be able to use curl https://booksapi/api/book or curl https://booksapi:443/api/book.
Since it's https, it'll make the request on port 443 by default, which is what the container is listening on, so there's no need to specify a port.
Port 8001 is only used when you access the API from the host machine. When you're on the bridge network that docker-compose creates, you use the container ports directly.


text:
Q: NSObject is Hashable but a protocol that adopts NSObject is not? Just a sanity check with the community before I file a radar:
In a .h Obj-C file:
@protocol myProto <NSObject>
@end

In a .swift file (that has access to the above protocol definition via bridging header):
class myClass {
    // This line compiles fine
    var dictOne: [NSObject:Int]?
    // This line fails with "Type 'myProto' does not conform to protocol 'Hashable'"
    var dictTwo: [myProto:Int]?
}

Inspection of the NSObject class reveals that it (or the NSObjectProtocol that it maps to) does not implement the hashValue method required by the Hashable protocol, nor does it explicity adopt it.
So, somewhere behind the scenes the NSObject is being flagged as Hashable despite this, but does not extend to protocols that adopt NSObject/NSObjectProtocol.
Have I got a bug or am I missing something?
:)
Teo
Additional info:
The documentation suggests that:

*

*A dictionary's key type's only requirements is that it's Hashable and that it implements ==.

*You can indeed use a protocol.

  Hash Values for Dictionary Key Types

  A type must be hashable in order to be used as a dictionary's key type—that is, the type must provide a way to compute a hash value for itself. A hash value is an Int value that is the same for all objects that compare equal, such that if a == b, it follows that a.hashValue == b.hashValue.
All of Swift's basic types (such as String, Int, Double, and Bool) are hashable by default, and all of these types can be used as the keys of a dictionary. Enumeration member values without associated values (as described in Enumerations) are also hashable by default.

NOTE
    You can use your own custom types as dictionary key types by making them conform to the Hashable protocol from Swift's standard library. Types that conform to the Hashable protocol must provide a gettable Int property called hashValue, and must also provide an implementation of the "is equal" operator (==). The value returned by a type's hashValue property is not required to be the same across different executions of the same program, or in different programs.
    For more information about conforming to protocols, see Protocols.

A: NSObjectProtocol doesn't inherit from Hashable. That's the crucial problem here.
It can't actually inherit from Hashable because Hashable requires a method called hashValue while NSObjectProtocol requires a method called hash.
On the other hand, NSObject class can implement both NSObjectProtocol and Hashable.
The same problem happens with Equatable.
Edit:
There is another more subtle problem. You cannot use a protocol somewhere where Equatable is expected, you always need to use a class type or a value type that adopts Equatable. The reason is that it's not enough for a key to adopt Equatable, all the keys in the dictionary have to be equatable with each other.
For example, if you have a class A and a class B, both conforming to Equatable, then you can compare instances of A with other instances of A and you can compare instances of B with other instances of B but you cannot compare instances of A with instances of B. That's why you cannot use instances of A and instances of B as keys in the same dictionary.
Note that every NSObject is equatable with any other NSObject, so NSObject is an allowed type for keys in a dictionary.

A: I agree that this seems like a missing feature. For anyone interested, I made a little wrapper to deal with it.
struct HashableNSObject<T: NSObjectProtocol>: Hashable {
    let value: T

    init(_ value: T) {
        self.value = value
    }

    static func == (lhs: HashableNSObject<T>, rhs: HashableNSObject<T>) -> Bool {
        return lhs.value.isEqual(rhs.value)
    }

    func hash(into hasher: inout Hasher) {
        hasher.combine(value.hash)
    }
}

You can even make this non-generic by replacing T with NSObjectProtocol, but I think that it's cleaner this way.
It's fairly easy to use, but a bit long when you have to keep mapping with the contained value.
let foo = [MyObjectProtocol]()
let bar = Set<HashableNSObject<MyObjectProtocol>>()
fun1(foo.map { HashableNSObject($0) })
fun2(bar.map { $0.value })

A: Alternatively, you can use the NSObjectProtocol.hash as your key.
var dictTwo: [Int:Int]?
dictTwo[myProtoInstance.hash] = 0


text:
Q: Remembering Results When Navigating Back to Search Page in Laravel I have created a search page using Laravel that has "text to search" filters at the top. When the mouse is taken off the filter the page's JavaScript fires an Ajax call then returns the results.
As I also have pagination enabled (with Ajax), when I click on page 2 (a link that looks like: http://project.test/customers?page=2) the filters at the top keep any previously entered text, and the search results are held, which is just what I need!
Now the problem:
The database I have has two main tables.

*

*Customers

*Purchases
Relationships:
A customer can have many purchases
Any given purchase though belongs to a single customer
I've built a search page so that the user can search for customers that match the given search criteria (e.g., those belonging to a particular city, or country, for example).
In the table below the search filters that shows all the matching customer records, I have a column, with a purchases button that then takes the user to that particular customer's purchase page (here, the purchases button goes a link of the form project.test/customers/{{id}}
The {id} goes through a route, that then loads a new page that shows all the purchases of that particular customer.
Now, I have a "go back" button on this purchase page, that goes the following link:
project.test/customers
This then loads the original search page (but loads it afresh).
THIS IS THE PROBLEM!!!
Because the page is loaded afresh (using the link: project.test/customers)
The search filters are cleared, and the page instead shows ALL the customers. And so, the user then has to re-enter all the search criteria again - which is annoying for the user, as he / she will often need to change a batch of purchase records, across a given set of customers, that match a given set of search criteria - and would rather not have to re-enter the same criteria, again, and again, when navigating away to a customer's purchase page, and then navigating back to the main search page.
Given this problem, my question is, is it possible, conceptually, with Laravel, to go to another page, from a search page, and then, using some method to go back to the original search page, for the search filters, and results, showing from before, to still be there? - This would be a super useful thing to have!
I've seen this done on other sites, possibly using other web technologies, but I'm just unsure how to start / where to begin to do this with Laravel / PHP?
I appreciate any help, thanks in advance!

A: Store the search criteria in the user's session, passing them back to the search page when they navigate back.
Say you have a controller with a function for the search route:
public function search (Request $request)
{
    // store the search criteria
    session(['search_criteria' => $request->input()]);

    // return the results
}

Then within another controller function, add the original parameters to the response:
public function someRouteMethod (Request $request)
{
    return redirect()->with('search_criteria', session('search_criteria'))->to('/search');
}

Then in the search page repopulate the form with the $search_criteria data:
<input value="{{ !empty($search_criteria) ? $search_criteria['foo'] : '' }}" name="foo">


text:
Q: TypeError: to_csv() takes exactly 1 argument (2 given) - Pandas module I'm a fairly new programmer attempting to pull google intraday stock data for every stock in the RUSSEL3000 and place that data into CSV files. 1 file per stock. I'm able to use the following code to accomplish that task for daily data pulled from yahoo finance with pandas without any problems:
import pandas as pd
from pandas import DataFrame
import datetime, csv, pandas.io.data

def PullTicker(file='RUS3000.csv'):
    RUS3000 = []
    with open(file,'rb') as f:
                reader = csv.reader(f)
                for row in reader:
                    RUS3000.extend(row)

    for Ticker in RUS3000:
        Filename = Ticker+'.csv'
        StockData = pd.io.data.get_data_yahoo(Ticker,
                                        start=datetime.datetime(2004, 12, 5),
                                        end=datetime.datetime(2014, 12, 5))
        print Ticker,StockData.head(),'\n'
        StockData.to_csv(Filename)

PullTicker()

This is the code I'm using for GoogleFinance intraday data, with it I'm able to get the data I want to print to the terminal:
import urllib,time,datetime
import pandas as pd
from pandas import DataFrame
import pandas.io.data
import csv

class Quote(object):

  DATE_FMT = '%Y-%m-%d'
  TIME_FMT = '%H:%M:%S'

  def __init__(self):
    self.symbol = ''
    self.date,self.time,self.open_,self.high,self.low,self.close,self.volume = ([] for _ in range(7))

  def append(self,dt,open_,high,low,close,volume):
    self.date.append(dt.date())
    self.time.append(dt.time())
    self.open_.append(float(open_))
    self.high.append(float(high))
    self.low.append(float(low))
    self.close.append(float(close))
    self.volume.append(int(volume))

  def to_csv(self):
    return ''.join(["{0},{1},{2},{3:.2f},{4:.2f},{5:.2f},{6:.2f},{7}\n".format(self.symbol,
              self.date[bar].strftime('%Y-%m-%d'),self.time[bar].strftime('%H:%M:%S'),
              self.open_[bar],self.high[bar],self.low[bar],self.close[bar],self.volume[bar])
              for bar in xrange(len(self.close))])

  def write_csv(self,filename):
    with open(filename,'w') as f:
      f.write(self.to_csv())

  def read_csv(self,filename):
    self.symbol = ''
    self.date,self.time,self.open_,self.high,self.low,self.close,self.volume = ([] for _ in range(7))
    for line in open(filename,'r'):
      symbol,ds,ts,open_,high,low,close,volume = line.rstrip().split(',')
      self.symbol = symbol
      dt = datetime.datetime.strptime(ds+' '+ts,self.DATE_FMT+' '+self.TIME_FMT)
      self.append(dt,open_,high,low,close,volume)
    return True

  def __repr__(self):
    return self.to_csv()

class GoogleIntradayQuote(Quote):
  ''' Intraday quotes from Google. Specify interval seconds and number of days '''
  def __init__(self,symbol,interval_seconds=300,num_days=5):
    super(GoogleIntradayQuote,self).__init__()
    self.symbol = symbol.upper()
    url_string = "http://www.google.com/finance/getprices?q={0}".format(self.symbol)
    url_string += "&i={0}&p={1}d&f=d,o,h,l,c,v".format(interval_seconds,num_days)
    csv = urllib.urlopen(url_string).readlines()
    for bar in xrange(7,len(csv)):
      if csv[bar].count(',')!=5: continue
      offset,close,high,low,open_,volume = csv[bar].split(',')
      if offset[0]=='a':
        day = float(offset[1:])
        offset = 0
      else:
        offset = float(offset)
      open_,high,low,close = [float(x) for x in [open_,high,low,close]]
      dt = datetime.datetime.fromtimestamp(day+(interval_seconds*offset))
      self.append(dt,open_,high,low,close,volume)

if __name__ == '__main__':
  q = GoogleIntradayQuote
  RUS3000 = []
  with open('RUS3000.csv','rb') as f:
                reader=csv.reader(f)
                for row in reader:
                    RUS3000.extend(row)

  for Ticker in RUS3000:
    Filename = Ticker+'.csv'
    StockData = q(Ticker,60,1)
    print StockData
    StockData.to_csv(Filename)

When I attempt to save that data to a csv using pandas to_csv function I get the error:
Traceback (most recent call last):
  File "intraday.py", line 81, in <module>
    StockData.to_csv(Filename)
TypeError: to_csv() takes exactly 1 argument (2 given)

Why would the data from my class, assigned to a variable, count as two arguments while the data pulled using pandas.io.data works perfectly? This is my first question on Stackoverflow and I appreciate any help in advance! Thank you.


text:
Q: My computer has short circuited my graphics card(s) three times, and I have absolutely no idea what's causing it Nearly a year ago, I came home to find my GPU fans spinning very loudly and my computer getting no video at all. So I restarted it, still no video output from the GPU, GPU fans are spinning at 100%, but the computer still boots as I can hear the windows startup sound and remote desktop into it. I tried reseating the card and unplugging everything and plugging it back in, still didn't work. Even tried the card in a friend's build and it still didn't work. So I sent it back to Gigabyte and they sent me a new card.
Card #2 only lasted about 2 days in my build before it happened again. I checked the Windows event logs and nothing suspicious happened. Temps were also all normal, my build stays fairly cool during idle. And the only stress I had put on the card was a few hours of DayZ and Battlefield. I also don't leave my computer on for very long periods of time. Typically only when I'm at work so I can remote into it.
When card #3 arrived, I swapped the motherboard and PSU for brand new counterparts (I was a little due for an upgrade anyways and I had the brand new PSU for free from CoolerMaster laying around). Here's my build before I swapped the hardware, and here's my build after I swapped the hardware. With that swap, I changed absolutely all cabling besides the cables coming from the system fans (obviously can't change those without getting new fans completely). Card 3 lasted for maybe a month and a half, possibly more I can't remember now. Anyways, it did the same thing as the other two.
I don't know what could be causing it after swapping all hardware where the issue could have originated and all the cabling. I'm very sure everything is plugged in securely, I'm taking all proper static prevention precautions during the build, no metals inside the case are touching and the motherboard headers + risers are all fastened and installed properly. I even got a brand new surge protector to prevent anything bad from the wall reaching my PC, and I also moved my build to the other side of the room so I'm on a different power rail. But still, card 3 shit the bed.
I'm also very sure that Gigabyte is sending me different cards each time and not the same faulty card (can tell by serial numbers). Each card also had varying manufacture dates, so they were even from different batches from the factory as well.
Any guesses? Anything at all? I'm super stumped and the only thing I could possibly think of is maybe the RAM is short circuiting the GPU (I've heard of RAM to cause some weird things), but I ran Memtest86+ through 20 passess and it found no errors, saying my memory passed 100% of tests.
Any help is really appreciated, I just want to be able to play games again without having to worry about this damn thing. I'm willing to answer any and all relevant questions. My entire hardware listing is in the above links from before and after I swapped hardware from my build.
Thanks.

A: There's no way to prove this, but it seems like your monitor should be a prime suspect.  I've had a monitor kill a graphic card before, and it was a very similar situation: nothing in the logs, components all checked out, and my whole rig on a surge protector.  I had another card fail in less than 3 months, and when I replaced it the next time, I got two shiny new monitors to replace my old one at the same time.  No problems ever since.
Well, at least not with the graphics card.  :P. You know windows, there's always somethin'.


text:
Q: How to set the default image to tabbar item programmatically? I am creating a tabbar with 5 tab items. I have created the tabbar programmatically. I want to set the default image(More) to tabbar item. If I create tabbar through IB I would select the identifier as "More", but how to do it programmatically?

A: For this purpose you need to create a class whose parent class will be UITabBar.
Here is its .h file:
    #import <UIKit/UIKit.h>

    @interface ImageTabBar : UITabBar
    {

    }

    @end

And here is its .m file:
    #import "ImageTabBar.h"
    #import "GlobalVars.h"

    @implementation ImageTabBar

    - (void) drawRect:(CGRect)rect
    {
        UIImage *tabImage;
        switch (intTabBarSelectedIndex)
        {
            case 0:
                tabImage=[UIImage imageNamed:@"TabBarImageTwitter.png"];
                [tabImage drawAtPoint:CGPointMake(0, 0)];
                break;
            case 1:
                tabImage=[UIImage imageNamed:@"TabBarImageCalender.png"];
                [tabImage drawAtPoint:CGPointMake(0, 0)];
                break;

            case 2:
                tabImage=[UIImage imageNamed:@"TabBarImageStanding.png"];
                [tabImage drawAtPoint:CGPointMake(0, 0)];
                break;

            case 3:
                tabImage=[UIImage imageNamed:@"TabBarImageNews.png"];
                [tabImage drawAtPoint:CGPointMake(0, 0)];
                break;

            case 4:
                tabImage=[UIImage imageNamed:@"TabBarImagePhotos.png"];
                [tabImage drawAtPoint:CGPointMake(0, 0)];
                break;

            default:
                break;
        }
    }

    - (void)dealloc
    {
        [super dealloc];
    }

    @end

In the statement:
switch (intTabBarSelectedIndex)

intTabBarSelectedIndex will be defined as global variable and is of integer type.
Now come to TabBarController class.
Here is its .h file
#import <UIKit/UIKit.h>

@class  ImageTabBar;

@interface TabBarViewController : UIViewController <UITabBarControllerDelegate>
{
    ImageTabBar *objOfImageTabBar;

    IBOutlet UITabBarController *uiTabBarC;
}

@property (nonatomic, retain) IBOutlet UITabBarController   *uiTabBarC;

- (void)setNeedsDisplay;

@end

And here is its .m file
Include the following functions in your TabBarController class' .m file:
- (void)viewDidLoad
{
    [self.navigationController setNavigationBarHidden:YES];

    self.view               = uiTabBarC.view;
    uiTabBarC.selectedIndex = intTabBarSelectedIndex;
    uiTabBarC.delegate      = self;
    [super viewDidLoad];
}

#pragma mark TaBarViewController delegate

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    intTabBarSelectedIndex = uiTabBarC.selectedIndex;

    UITabBar *aTabBar = tabBarController.tabBar;
    [aTabBar setNeedsDisplay];
}

- (void)setNeedsDisplay
{

}

Do exactly like this, your code will run perfectly.


text:
Q: Taylor Method ODE I am trying to implement the Taylor method for ODEs in MatLab:
My code (so far) looks like this...
function [x,y] = TaylorEDO(f, a, b, n, y0)
% syms t
% x = sym('x(t)'); % x(t)
% f = (t^2)*x+x*(1-x);

h = (b - a)/n;

fprime = diff(f);
f2prime = diff(fprime);

y(0) = y0,
for i=1:n
    T((i-1)*h, y(i-1), n) = double(f((i-1)*h, y(i-1)))+(h/2)*fprime((i-1)*h, y(i-1))
    y(i+1) = w(i) + h*T(t(i), y(i), n);

I was trying to use symbolic variables, but I don´t know if/when I have to use double.
I also tried this other code, which is from a Matlab function, but I do not understand how f should enter the code and how this df is calculated.
http://www.mathworks.com/matlabcentral/fileexchange/2181-numerical-methods-using-matlab-2e/content/edition2/matlab/chap_9/taylor.m
As error using the function from this link, I got:
>> taylor('f',0,2,0,20)
Error using feval
Undefined function 'df' for input arguments of type 'double'.

Error in TaylorEDO (line 28)
  D = feval('df',tj,yj)

The f I used here was
 syms t
 x = sym('x(t)'); % x(t)
 f = (t^2)*x+x*(1-x);

A: This is a numerical method, so it needs numerical functions. However, some of them are computed from the derivatives of the function f. For that, you need symbolic differentiation.
Relevant Matlab commands are symfun (create a symbolic function) and matlabFunction (convert a symbolic function to numerical).
The code you have so far doesn't seem salvageable. You need to start somewhere closer to basics, e.g., "Matlab indices begin at 1". So I'll fill the gap (computation of df) in the code you linked to. The comments should explain what is going on.
function [T,Y] = taylor(f,a,b,ya,m)
syms t y
dfs(1) = symfun(f, [t y]);                         % make sure that the function has 2 arguments, even if the user passes in something like 2*y
for k=1:3
    dfs(k+1) = diff(dfs(k),t)+f*diff(dfs(k),y);    % the idea of Taylor method: calculate the higher derivatives of solution from the ODE
end
df = matlabFunction(symfun(dfs,[t y]));            % convert to numerical function; again, make sure it has two variables

h = (b - a)/m;                                     % the rest is unchanged except one line
T = zeros(1,m+1);
Y = zeros(1,m+1);
T(1) = a;
Y(1) = ya;
for j=1:m
  tj = T(j);
  yj = Y(j);
  D = df(tj,yj);                                   % syntax change here; feval is unnecessary with the above approach to df
  Y(j+1) = yj + h*(D(1)+h*(D(2)/2+h*(D(3)/6+h*D(4)/24)));
  T(j+1) = a + h*j;
end
end

Example of usage:
syms t y
[T, Y] = taylor(t*y, 0, 1, 2, 100);
plot(T,Y)


text:
Q: Is it possible to 'see' the object graph for garbage collection? I have a Java application that is leaking memory. I know which objects are not being freed during garbage collection, but I can't work out what is referencing them.
Is it at all possible to have some sort of visibility of the object graph that is being held internally by the JVM?
It is at all otherwise possible to find out which objects are referencing another object?

A: On a really basic level, you can use the commands jhat and jmap to read a heap file from a running Java process and then process it - it starts a small web server on a local port. It's not exactly easy to read, but you don't have to buy a profiler to use it.

A: Profilers do this. JProfiler for example. Back in the day I used Optimizeit (which seems to be dead now).
The conclusion was that listeners were being passed to some collection and not being removed from that collection. The listeners were anonymous inner classes defined on a Frame or a corresponding control class that referenced the Frame, and an anonymous inner class has an implicit reference to its outer class. So that little listener held the whole frame and all its attendant objects in active memory.


text:
Q: Laravel validation with Bootstrap Modal I've included this Github script to make a validation form with Bootstrap Modal everything is set up correctly but when I included this script the form don't submit because there are some errors which is good but it doesn't show them in the view
Controller
$this->validate($request, [
    'nom' => 'required|unique:filieres'
]);

View
@if($errors->get('nom'))
    @foreach($errors->get('nom') as $error)

{{$error}}

    @endforeach
@endif

A: can you just type this code in your view file
        @include('includes.form_error')

second type this in your controller
    public function store(UsersRequest $request)
    {
    }

and you create UserRequest file in Requests folder and type this
    public function rules()
    {
        return [
            'name' => 'required',
        ];
    }

after you got proper error


text:
Q: Javascript unit testing in eclipse I am doing a firefox extension using eclipse and need to know how I can do unit testing for that project.

A: I think you can use Jasmine Framework for that.

A: I've been using JSTestDriver, http://code.google.com/p/js-test-driver, and it is an excellent framework. Lightning fast testing, test on save, and other cool features.
Initial setup is a bit complicated, but it's certainly worth it.

A: I've used JsUnit in the past, but this project is no longer maintained.


text:
Q: Launching an application if installed or redirect to Google Play Until now I was using this code to launch a 3rd party application if installed or redirect to Google Play to download it if not installed already:
Intent intent = Intent intent = getPackageManager().getLaunchIntentForPackage("com.package.address");
if (intent != null)
{
/* we found the activity now start the activity */
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else
{
/* bring user to the market or let them choose an app? */
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id="+"com.package.address"));
startActivity(intent);
}

Reading here I found the way to launch a particular activity instead (that was my desired result):
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new  ComponentName("com.package.address","com.package.address.xxxxxActivity"));
startActivity(intent);

It works launching the particular activity, but with my very very very limited knowledge I don't know how to modify the condition to launch the link to Google Play if the app isn't installed.
Hope someone can help me^^
Thanks!

A: you can use a try catch to see if the package name exists
try {
    PackageManager pm=getPackageManager();
    PackageInfo info=pm.getPackageInfo("com.package.address",PackageManager.GET_META_DATA);
} catch (NameNotFoundException e) {
    //launch play store
}

A: A complete working solution
Intent intent = getPackageManager().getLaunchIntentForPackage("slidy.whatsappsticker");
            if (intent != null)
            {
                /* we found the activity now start the activity */
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                showInterstitial();
            }
            else {
                try {
                    PackageManager pm = getPackageManager();
                    PackageInfo info = pm.getPackageInfo("com.package.name", PackageManager.GET_META_DATA);
                } catch (PackageManager.NameNotFoundException e) {
                    //launch play store
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.package.name")));
                }
            }


text:
Q: Run function after user has stopped typing I have an input field in which user can input a long value. This value is then used as input value in a complex time consuming function.
My question is: how can I start execution of this function approximately 1 second after the user finished his typing? (I don't want to run it after each key press as it is really slowing the page). So if his next keystroke is in the 1s limit from the last key stroke, than wait additional second.
Do you have any suggestions?
additional note: I also need to pass some parameters into this function

A: This is really late, I know, but I really disliked the lines of code needed to achieve this every time it was needed, so I extracted the logic into a page initiation function that only runs once.
(function(){
    var keystoppedTimer = null;
    var keystoppedInputs = document.getElementsByTagName('input');
    for (var i = 0, l = keystoppedInputs.length; i < l; i++) {
        keystoppedInputs[i].addEventListener('keydown', function(event){
            clearTimeout(keystoppedTimer);
            keystoppedTimer = setTimeout(function() {
                event.target.dispatchEvent( new Event('keystopped') );
            }, 600);
        }, false);
    }
}());

Adding this (think of it as a polyfill), allows for much simpler usage. All you need to do to target the user stopping typing is add an event listener to your element targeting 'keystopped'.
inputElement.addEventListener('keystopped', function(event){
    console.log('Stopped typing');
}, false);

I picked keystopped because it matches keydown, keyup, etc.

A: Here's a rough draft : http://jsfiddle.net/jomanlk/msmJp/
Uses setTimeout and clearTimeout

var timer = null;
    $('#text').keyup(function(){
           clearTimeout(timer);
           timer = setTimeout(doStuff, 1000)
    });

    function doStuff() {
        alert('do stuff');
    }

<input type='text' id='text'>

A: Use the bindWithDelay jQuery plugin:
element.bindWithDelay(eventType, [ eventData ], handler(eventObject), timeout, throttle)

A: I have posted a solution when it ll show user is typing and user stopped type

function typingAction(){
  $('#typing').text("user is typing....");
clearTimeout();
setTimeout(()=>{
  $('#typing').text(' user stopped typing.....'); //**can call your function here**
  },2000);
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Chat | ChatApp</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  <link rel="stylesheet" href="/css/styles.css">

<input name="message" type="text" placeholder="Message" autofocus autocomplete="off" oninput="typingAction()" />


text:
Q: What ip address range to use for mailjet in gcp setup I am creating a firewall rule on gcp for mailjet. How do I choose what destination ip address range to use ?

A: Based on : Php Mailer Function not working on Google Cloud Platform

Under Destination filter, set 0.0.0.0/0 if you want to allow egress
  traffic from the VM instance to any destination. If you want to limit
  the destination, enter another IP range here. THIS IS IMPORTANT IF
  YOUR EMAIL IS HOSTED SOMEWHERE ELSE.


text:
Q: c++ Reading the first few bytes out of every X bytes efficiently I want to read the first 16 bytes out of every X*16 bytes of a file. The code I wrote works, but is quite slow, because of many function calls.
std::vector<Vertex> readFile(int maxVertexCount) {
    std::ifstream in = std::ifstream(fileName, std::ios::binary);
    in.seekg(0, in.end);
    int fileLength = in.tellg();
    int vertexCount = fileLength / 16;

    int stepSize = std::max(1, vertexCount / maxVertexCount);

    std::vector<Vertex> vertices;
    vertices.reserve(vertexCount / stepSize);
    for (int i = 0; i < vertexCount; i += stepSize) {
        in.seekg(i * 16, in.beg);
        char bytes[16];
        in.read(bytes, 16);
        vertices.push_back(Vertex(bytes));
    }
    in.close();
}

Could someone give me some suggestions to increase the performance of this code?

A: Don't use seek, I would mmap this whole file and then simply read off the bytes at the desired locations.
I'm not going to write the code for you, but it should be along the lines of:

*

*Open the file, calculate the file size

*mmap the whole file

*Iterate through in your step sizes calculating the address of each block

*Construct each Vertex based on the block and push into the vector

*return the vector.

A: It's likely not the function calls itself, but the non-sequential access pattern, picking small segments from a large file. Even though you are reading only 16 bytes,  the storage subsystem likely read (and caches) larger blocks. Your access pattern is deadly for typical I/O.
(Profiling should show whether disk access is the bottle neck. If it was "many function calls", CPU would be.)
So, first and foremost, can you change this requirement?
This is in all scenarios the easiest way out.
Could you scatter less? E.g. instead of reading vertices 0, 20, 40, ..., 1000 , read vertices 0,1,2,3,4, 100, 101, 102, 103, 104, 200, 201, 202, 203, 204, ... - same number of vertices, from "all parts" of the file.
Second, OS specific optimizations.
There's no portable way to control OS level caching.
One solution is memory mapping the file (CreaterFileMapping on Windows, mmap on Linuxy systems), as suggested by @Nim. This can omit one memory copy, but still the entire file will be read.
Can't help much with Linux, but on Windows you have as parameters to CreateFile:

*

*FILE_FLAG_NO_BUFFERING which basically means you do the buffering, giving you finer control over the caching that happens, but you can't seek + read willy-nilly.

*FILE_FLAG_SEQUENTIAL_SCAN which just telsl the cache not to store old data
Neither of these will solve the problem with your access pattern, but the first may mediate it somewhat - especially if your steps are larger than disk sectors, and the second can take pressure from the subsystem.
Third, Snapshot.
The best option may be to store an interleaved snapshot either in an associated file.
The snapshot could simply be the result of your operation, for a particular maxVertexCount. Or multiple snapshots, like mipmapping. The idea is to replace the scattered read by a sequential read.
Alternatively, the snapshot can store the data in interleaved order. For 128 vertices, you could store vertices in that order (roughly, beware of off-by<-one, zero-vs-one-based and aliasing effects, and my mistakes):
64,   32, 96,   16, 48, 80, 112   8, 24, 40, 56, 72, 88, 104, 120  ...
Whether you read the first 3 or first 7 or first 15 or first 31... values, the samples are equally spread out across the file, like in your original code. Rearranging them in memory will be much faster - especially if it's just a small subset.
Note: you need a robust algorithm to detect that your snapshot is out of date, independent of the many funny things that happen with "last write date" on different file systems.  A "change counter" in the main file would be the safest one (though it would icnrease the cost of changes).
Fourth, Change the file format
(In case you can control that)
The interleaved storage suggested above could be used for the entire file. However, this has big implications for processing - especially if you need to restore the "original" order at some point.
An elegant option would be having such an interleaved subset as part of the file, and the full list of vertices in original order. There is a cutoff stepSize where this doesn't help much anymore, probably around 2*sector/block size of the disk. So file size would increase only by a few percent. However, writes would get a little more costly, changes to the amount of vertices significantly worse.

Aliasing warning
If this is intended to get a "statistical" or "visually sufficient" sampling, a fixed stepSize might be problematic, since it can create aliasing effects (think Moire patterns) with any patterns present in the data.
In this case, a random sampling would be preferrable. That may sound scary and makes some of the solutions above a bit harder, but is often the easiest way to  avoid many suboptimal cases.

A: ... and if for some reason you can't use map, read the file into a buffer in "great big gulps" ... a buffer-size that is some multiple of X bytes. Continue reading into that buffer (taking care to notice how many bytes were read). until you reach the end of the file.
What you're specifically trying to avoid is a whole bunch of physical I/O operations: movement of the disk's read/write mechanism. The operating system likes to buffer things for this reason but it can only guess at what your application is trying to do and it might guess wrong. Once the disk has positioned the read/write head to the proper track ("seek time"), it can retrieve a whole track's worth of data in one rotation. But "seek time" is comparatively slow.
Mapping the file, and then reading the data in the mapped file non-randomly, is clearly the most favorable strategy because now the operating system knows exactly what's going on.

A: First, I assme you're returning the vector by value from the definition even though your posted code lacks a return statement, so the vector has to be copied.  Pass it by reference into your method so no copying is needed.
And you can use low-level pread() to read without needing to seek:
void readFile( size_t maxVertexCount, std::vector<Vertex> &vertices )
{
    struct stat sb;
    int fd = std::open( fileName, O_RDONLY );
    std::fstat( fd, &sb );

    size_t vertexCount = sb.st_size / 16;

    size_t stepSize = std::max( 1, vertexCount / maxVertexCount );

    vertices.reserve( vertexCount / stepSize );

    for ( off_t i = 0; i < vertexCount; i += stepSize)
    {
        char bytes[ 16 ];
        std::pread( fd, bytes, 16, 16 * i );
        vertices.push_back( Vertex( bytes ) );
    }

    std::close( fd );
}

You should be able to figure out the required error handling and header files.
This takes advantage of the kernel's page cache and likely read-ahead.  Depending on your OS and configuration, other methods such as mmap() or reading the entire file may or may not be faster.


text:
Q: Double-click prevention on save I have a kendo grid with its dataSource, the grid has an editor dialogue with save button. I need to prevent the save button being double clicked. The onsave functions fire when the save button is clicked. I have a requestEnd event that fires when the save is to be re-enabled.
The problem: onSave1 looks to fail 1 time in 100 . It's based on adding an additional click handler, invoking preventDefault(). Is it fundamentally flawed?
Is onSave2 any better?
onSave1: function (e) {
    $(event.srcElement)
    .addClass("k-state-disabled")
    .bind("click", disable = function (e) { e.preventDefault(); return false; })
    this.dataSource.one("requestEnd", function () {
        $("[data-role=window] .k-grid-update")
            .off("click", disable)
            .removeClass("k-state-disabled");
    })
}

onSave2: function (e) {
    $(event.srcElement)
        .removeClass(".k-grid-update")
        .addClass("k-state-disabled")
        .addClass("disabledMarker");
    this.dataSource.one("requestEnd", function () {
        $("[data-role=window] .disabledMarker")
            .addClass(".k-grid-update")
            .removeClass("k-state-disabled")
            .removeClass("disabledMarker");
    })
}

A: First Jquery bind has been deprecated since version 3.0 so I would recommend not using it anymore. http://api.jquery.com/bind/
You do not need an onClick event or in your case bind because onSave is already being called during the click. So simply disable the button onSave. Second you should use complete or whatever kendo grid uses for when the save event is finished instead or requestEnd. Code listed below.
     onSave: {$(event.srcElement)addClass("k-state-disabled")}, complete:{ $(event.srcElement)removeClass("k-state-disabled")};


text:
Q: The verb after suggest I wrote:

I suggest you point to what A should return and match[ing?] it with the output of B in README

My complete suggestion is:

I suggest you that you point to what A should return and say the user to match it with the output of B in README

Does my original sentence convey this meaning, if not what are the mistakes?

A: Honestly, i think there's a better version of both sentences:
"I suggest that you point to what A should return and tell the user to match it with the output of B in README."
Here are my reasons:
1- when you're pointing to the content, you should use tell instead of say based on the British Dictionary
2- "you" after suggest in this sentence seems unessential and abundant.


text:
Q: TensorFlow Object Detection API Weird Behavior I was playing with TensorFlow's brand new Object Detection API and decided to train it on some other publicly available datasets.
I happened to stumble upon this grocery dataset which consists of images of various brands of cigarette boxes on the supermarket shelf along with a text file which lists out the bounding boxes of each cigarette box in each image. 10 major brands have been labeled in the dataset and all other brands fall into the 11th "miscellaneous" category.
I followed their tutorial and managed to train the model on this dataset. Due to limitations on processing power, I used only a third of the dataset and performed a 70:30 split for training and testing data. I used the faster_rcnn_resnet101 model. All parameters in my config file are the same as the default parameters provided by TF.
After 16491 global steps, I tested the model on some images but I am not too happy with the results -

Failed to detect the Camels in top-shelf whereas it detects the product in other images

Why does it fail to detect the Marlboros in the top row?

Another issue I had is that the model never detected any other label except for label 1

Doesn't detected a crop instance of the product from the training data

It detects cigarette boxes with 99% confidence even in negative images!
Can somebody help me with what is going wrong? What can I do to improve the accuracy? And why does it detect all products to belong in category 1 even though I have mentioned that there are 11 classes in total?
Edit Added my label map:
item {
  id: 1
  name: '1'
}

item {
  id: 2
  name: '2'
}

item {
  id: 3
  name: '3'
}

item {
  id: 4
  name: '4'
}

item {
  id: 5
  name: '5'
}

item {
  id: 6
  name: '6'
}

item {
  id: 7
  name: '7'
}

item {
  id: 8
  name: '8'
}

item {
  id: 9
  name: '9'
}

item {
  id: 10
  name: '10'
}

item {
  id: 11
  name: '11'
}

A: How many images are there in the dataset? The more training data that you have the better the API performs. I tried training it on about 20 images per class, the accuracy was pretty bad. I pretty much faced all the problems that you have mentioned above. When I generated more data, the accuracy improved considerably.
PS: Sorry I couldn't comment since I don't have enough reputation

A: Maybe it is too late now, but I wanted to post the comments if anyone struggles with this in the future:
Unfortunately, TF documentation is not the best and I struggled with this a lot before finding the reason. The way the model is constructed is that it allows for a MAXIMUM of x amount of predictions per single image. In your case I think it is 20. You can easily test my hypothesis by editing the original photo like this:
Obviously before the boxes are actually drawn and you should see some better results.
Pretty nasty limitation.

A: There are some parameters to configure like:
train_input_reader {
  max_number_of_boxes: 1000
}

eval_input_reader {
  max_number_of_boxes: 1000
}

They are very important. By default they are set to 100.

A: So I think I figured out what is going on. I did some analysis on the dataset and found out that it is skewed towards objects of category 1.
This is the frequency distribution of the each category from 1 to 11 (in 0 based indexing)
0 10440
1 304
2 998
3 67
4 412
5 114
6 190
7 311
8 195
9 78
10 75

I guess the model is hitting a local minima where just labelling everything as category 1 is good enough.
About the problem of not detecting some boxes : I tried training again, but this time I didn't differentiate between brands. Instead, I tried to teach the model what a cigarette box is. It still wasn't detecting all the boxes.
Then I decided to crop the input image and provide that as an input. Just to see if the results improve and it did!
It turns out that the dimensions of the input image were much larger than the 600 x 1024 that is accepted by the model. So, it was scaling down these images to 600 x 1024 which meant that the cigarette boxes were losing their details :)
So, I decided to test the original model which was trained on all classes on cropped images and it works like a charm :)

This was the output of the model on the original image

This is the output of the model when I crop out the top left quarter and provide it as input.
Thanks everyone who helped! And congrats to the TensorFlow team for an amazing job for the API :) Now everybody can train object detection models!

A: It seems, the dataset size is rather small. Resnet is a large network, which will require even more data to train properly.
What to do:

*

*Increase data set size

*Use pre-trained networks and fine tune on your dataset (you probably already do this)

*Use data augmentation (resize, blur,...; flipping may not be appropriate for this dataset).


text:
Q: Non static method getChildFragmentManager() cannot be referenced from a static context In fragment I am trying use getChildFragmentManager() in static method.  But it show error and suggest me make method not static.
Non static method getChildFragmentManager() cannot be referenced from a static context

fragment:
public class C_Fragment extends android.support.v4.app.Fragment

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_a, container, false);
    }

 static void updateProductList(){
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (getChildFragmentManager().findFragmentByTag("kz.dreamwings.unimax.fragments.C_Category_A_prudacts")!=null) {
//                            C_Category_A_prudacts.adapter.notifyDataSetChanged();
                    Fragment frg = null;
                    frg = getChildFragmentManager().findFragmentByTag("kz.dreamwings.unimax.fragments.C_Category_A_prudacts");
                    final FragmentTransaction ft = getChildFragmentManager().beginTransaction();
                    ft.detach(frg);
                    ft.attach(frg);
                    ft.commit();
                }
            }
        }, 300);
    }

A: Yes, you cannot access not-static context from static context. You're trying to get a fragment instance in your static method, you should do it outside the static method so you can access getChildFragmentManager().
private static Fragment fragment;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {

    fragment = getChildFragmentManager().findFragmentByTag("kz.dreamwings.unimax.fragments.C_Category_A_prudacts");

    //.... other code
}

static void updateProductList(){
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (fragment!=null) {
                //.... other code
            }
            }
        }, 300);
    }

A: You can use the method with creation of making object of specific class,without making the static method
For ex:
If the class name is MainActivity.java
If the method name is updateProductList()
Just make an object of MainActivity like
MainActivity a = new MainActivity();

Then use this object to call method of MainActivity in other class
Like a.updateProductList();

A: You cannot call getFragmentManager() or getChildFragmentManager() from a static method in Java . Consider using an interface to or a callback to
update your 'products list'
public interface OnDoneLoading{

   void updateProductsList();
   //or better use  void updateProductsList(ArrayList<Products> products);

}

implement this interface in your Fragment.


text:
Q: NativeModule.RNDeviceInfo is null I'm trying to use react-native-device-info (8.7.0) to get some device information on an Android React Native application (RN version 0.60.5).
As soon as the app runs, this error shows up with or without doing manual linking.
react-native-device-info:
NativeModule.RNDevicelnfo is null. To
fix this issue try these steps:
• For react-native<=
0.59: Run react-native link
react-native-device-info" in the project
root.
• Rebuild and re-run the app.
• If you are using CocoaPods on iOS,
run "pod install' in the "ios directory
and then rebuild and re-run the app
You may also need to re-open Xcode to
get the new pods.
If none of these fix the issue, please
open an issue on the Github repository:
https://github.com/react-native-device
-info/react-native-device-info

I've searched the library documentation and found no solution for this.
Anyone with the same problem?


text:
Q: how to create a button in uiview programmatically in iphone In my iPhone application, how to add next and previous buttons in uiview programmatically?

A: You can create dynamic buttons using the following code
    UIButton *but=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    but.frame= CGRectMake(200, 15, 15, 15);
    [but setTitle:@"Ok" forState:UIControlStateNormal];
    [but addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:but];


text:
Q: how to show/hide a  with material-ui I want to do something really simple : using material-ui, I would like to have an
Info
 tag and when I click it, it unrolls a
Lorem Ipsum
 text. This is a simple toggle section.
I did some researches on the official website https://material-ui.com/ but I didn't find.
Using hidden doesn't seems appropriate (right ?).
Do you know how to do it (is there a material-ui functionnality to do it) ? I'm using React.js
This stackoverflow post didn't help me.
Thanks in advance for your help,
I hope this will be usefull to some people.

A: You can do with the collapse component.
       <Collapse in={checked}>
          <YourComponentToShowAndHide />
        </Collapse>


text:
Q: Tweet button not adding link url I have a Twitter Tweet button on the pages in my website. On the content pages, when you click the Tweet button, the link url is not getting added to the tweet.
Here's the code for the tweet:

    Tweet

The actual Tweet button works, so I don't think I need to add that code (request it if I still do).
This leads me to believe that it's a problem with the .Replace() on my @Model.Team.Name. The reason that was added was because a team called "Franklin & Marshall". That caused problems in urls since the & character was interpreted as a parameter instead of the actual text in the url.
Is that the issue with my tweet link url?

A: I went to the site you mentioned and found the page you're having issues with. If you go to a team without any spaces or special characters in it, the URL shows up when you attempt to tweet it. Seems like you need to URL encode the team names when they are displayed. It also could be easier to use an ID instead of a string of text with names so you don't have to URL encode them.


text:
Q: I have a row vector and I would like to add it onto the end of a matrix I have lots of FFT data and I would like to place it all into a 2-dimensional array. Each new entry looks like: [1 2 3 4 5 6 7 ...]  (and so on, for 1200 columns).
And I would like to add it to the end (the bottom of a matrix) e.g.:
[ 1 2 3 4 5 6 7
  1 2 3 4 5 6 7
  ... ]             <-- add here please

I was wondering how I should go about that?

A: I think you mean basic concatenation
>> a = [1 2 3 4 5 6 7 ...];
>> b = [2 3 4 5 6 7 8 ...];
>> c = [a; b]
c =
   1 2 3 4 5 6 7 ...
   2 3 4 5 6 7 8 ...

If you do this in a loop, it is a good habit to pre-allocate the matrix beforehand:
>> a = zeros(5);
>> for i = 1:5
>>     a(i, :) = randi(10,1,5);
>> end
a =
     3     6    10    10     2
    10    10     5     9     2
     5    10     8    10     7
     1     9    10     7     8
     8     4     7     2     8

While it is technically possible to 'grow' the array (as in a = [a; randi(10,1,5)]), it is not advisable to do this inside loops -- this makes them really much slower.

A: Alternatively, you can use cat for concatenation.

A: Cheers guys, I have managed to solve my problem using a different solution. I will share my answer in case anybody in the future stumbles upon this.
i=1;
A=zeros(m,n);
while(i<m)
  (do some FFT stuff here)
  A(i,1:n)=(F.*conj(F))';       %where F is the temporary vector for storing FFT results
  i=i+1;
end


text:
Q: SQL Server Arithmetic Overflow Error - converting nvarchar to datetime I'm retrieving data from a view, and one of the columns I'm using is nvarchar(50), but is only ever N'True' or N'False', depending on the operation of a related date column in this parent view.
The following code retrieves the record ID and the column I'm looking for, YTD:
SELECT Enquiry_Number, YTD
FROM dbo.vw_SalesPO_YTD

Output:
ENQ-001 True
ENQ-002 False
ENQ-003 True

However, I'm unable to filter my results using this YTD column for some reason. If I attempt to do this:
SELECT Enquiry_Number, YTD
FROM dbo.vw_SalesPO_YTD
WHERE YTD = N'True'

Then it fails with the following error:

Arithmetic overflow error converting expression to data type datetime.

Which I don't understand because there are no datetime expressions in play in this query. Yes the True or False was determined by comparing datetimes in the parent view, but I don't understand how that might have trickled down to this subquery. Attempting the same thing in the parent view yields the same error - I'm demonstrating it this way for simplicity's sake.
However, performing a similar operation in the SELECT portion of the query works without issues:
SELECT
    Enquiry_Number,
    YTD,
    CASE
       WHEN YTD = N'True' THEN 1 ELSE 0
    END As C
FROM
    dbo.vw_SalesPO_YTD

Output:
ENQ-001 True 1
ENQ-002 False 0
ENQ-003 True 1

However, these 1's and 0's inherit the same flaw, where I can't use them in a WHERE clause without getting this datetime error.
I've been searching hard and am not sure how to identify the core issue. I've been reading things about Collations and type precedence, but can't understand why this behaviour is happening.
When I've checked YTD in INFORMATION_SCHEMA.COLUMNS, it confirms that this column is no different from other columns in my table: YTD is nvarchar(50), using the Latin1_General_CI_AS collation.
Related question: SQL Server Arithmetic overflow error converting expression to data type datetime

The Source of the Problem
This issue is still unsolved, but if you wish to reproduce it, this code from the parent view must be generating this issue:
CASE WHEN
Award_Date <= DATEFROMPARTS(FinancialYear - 1, 11, 1) + GETDATE() - DATEADD(year, DATEDIFF(month, '20161101', GETDATE()) / 12, '20161101')
THEN N'True'
ELSE N'False'
END

Yes this looks overly complicated. We're checking the Award_Date against its associated FinancialYear, which runs from November 1st to October 31st. Each record already knows which FinancialYear it's in. The ultimate aim is to compare TODAY's position (2016-11-30) against TODAY last year (2015-11-30), and TODAY the year before (2014-11-30), etc.
So the code takes today's date and combines it with the FinancialYear for the associated record, and spits out whether the record had occurred between the start of its financial year and the today of the same year. And it's doing this successfully, but then I can't do anything with the N'True' or N'False' it's producing.

A: I do not know what the type of the source YTD is.
Try using the following:
SELECT Enquiry_Number, [YTD] FROM (
    SELECT Enquiry_Number, CONVERT(nvarchar(10),YTD) AS [YTD] FROM dbo.vw_SalesPO_YTD
) AS A
WHERE A.YTD = N'True'

10 is just a thump suck value. It will cut of any part of the field longer that 10. It depends on your actual field size.

A: SELECT *
FROM (SELECT Enquiry_Number, YTD
     FROM dbo.vw_SalesPO_YTD) AS A
     WHERE cast(A.YTD as varchar) = 'True'

A: I used the following as an example:
DECLARE @Data TABLE
(
    Enquiry_Number nvarchar(10),
    YTD nvarchar(50)
)

INSERT INTO @Data(Enquiry_Number, YTD)
SELECT N'ENQ-001', N'True' UNION
SELECT N'ENQ-002', N'False' UNION
SELECT N'ENQ-003', N'True'

SELECT Enquiry_Number, [YTD] FROM (
    SELECT Enquiry_Number, CONVERT(nvarchar(10),YTD) AS [YTD] FROM @Data
) AS A
WHERE A.YTD = N'True'

Result:
ENQ-001 True
ENQ-003 True

There must be results in the YTD field that causes to return it as a datetime type.
Try a query like:
SELECT * FROM dbo.vw_SalesPO_YTD WHERE ISDATE(YTD)= 1

Updated Question:
Try:
ISNULL(CASE WHEN  Award_Date <= DATEFROMPARTS(FinancialYear - 1, 11, 1) + GETDATE() - DATEADD(year, DATEDIFF(month, '20161101', GETDATE()) / 12, '20161101') THEN N'True' ELSE N'False' END, 'false')

A: Try this:- Don't add n before string
SELECT *
 FROM (SELECT Enquiry_Number, YTD
     FROM dbo.vw_SalesPO_YTD) AS A
     WHERE A.YTD = 'True'

A: This is a successful workaround, not a solution per se or explanation of the core issue.
There's obviously an issue with the data coming out of the view, which will not allow YTD column's results to be operated on in a WHERE clause, and yet they can be operated on by the time the query reaches its SELECT phase.
I've created a new table which explicitly defines the YTD column as nvarchar(50), and then inserted all the records from my view into this table, which has resolved the issue. The records can then be sorted and filtered by YTD as they are supposed to.


text:
Q: how to differ the machine code of jalr and beq in RISC-V In RiSC-V, since the opcode and funct3 of the instructions jalr and beq are the same, I'm wondering whether the machine would confuse them or not.
Or is there range limits of their RS and immediate?

A: The instructions have the following func3 and opcode:
func3#  opcode#  opcode name    opcode#(hex)
 000    1100011    BEQ            63
 000    1100111    JALR           67

So, they are different in the value of the opcode#.

As a side note, you can use tools to see the differences, for example, using RARS, which is an easy to use simulator where you can type in assembly code the following, and see machine code for it:
    .text
    jalr zero zero 0
label:
    beq zero zero label


text:
Q: How to stop jQuery $.animate when using increments I have the following code to increment number using jQuery $.animate. I need to stop the animation whenever I need to, but calling $("#el").stop() does not work. Any ideas?

EDIT:
Please also provide a solution to stop the $.animateNumbers found on: https://github.com/talmand/jquery-animate-numbers

A: The animation doesn't run on #el, so it cannot be stopped from there. It runs on the object you pass to $(), so you have to stop it there:
var obj =  $({someValue: 40000}).animate(...);
obj.stop();


text:
Q: How to hide Notification Panel after sending a PendingIntent to Service in a notification All
I write a service to to update system state, and I use startForeground to put the service to foreground, also adding a notification to it. In the notification, I use remoteView to have three images with three OnClickPendingIntent. One of them is sending back to the service, and do the notification update codes.
code for creating notification:
 Intent intentApp = new Intent(this,ScreenOffWidgetConfigure.class);
 intentApp.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
 PendingIntent piApp = PendingIntent.getActivity(this, 0, intentApp, 0);

 Intent intentOnOff = new Intent(CV.SERVICE_INTENT_ACTION);
 intentOnOff.putExtra(CV.SERVICEACTION, CV.SERVICEACTION_TOGGLE);
 PendingIntent piOnOff = PendingIntent.getService(this, 0, intentOnOff, 0);

 Intent intentScreenOff = new Intent(CV.SERVICE_INTENT_ACTION);
 intentScreenOff.putExtra(CV.SERVICEACTION, CV.SERVICEACTION_SCREENOFF);
 PendingIntent piScreenOff = PendingIntent.getService(this, 1, intentScreenOff, 0);

 // setup remoteview
 RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_notification);
 remoteViews.setOnClickPendingIntent(R.id.image_logo, piApp);
 remoteViews.setOnClickPendingIntent(R.id.image_status, piOnOff);
 remoteViews.setOnClickPendingIntent(R.id.image_screenoff, piScreenOff);

 if(CV.getPrefChargingOn(this) && CV.isPlugged(this))
 {
     remoteViews.setImageViewResource(R.id.image_status,R.drawable.widget_charging_on);
 }
 else
 {
     if(CV.getPrefAutoOnoff(this))
     remoteViews.setImageViewResource(R.id.image_status,R.drawable.widget_on);
     else
     remoteViews.setImageViewResource(R.id.image_status,R.drawable.widget_off);
 }

 // build the notification
 Notification noti = new Notification.Builder(this)
 .setContent(remoteViews)
 .setSmallIcon(R.drawable.ic_launcher)
 .setOngoing(true)
 .build();

 return noti;

code for updating notificaton, after receiving the intent:
 Notification notify = createNotification();
 final NotificationManager notificationManager = (NotificationManager) getApplicationContext()
                        .getSystemService(getApplicationContext().NOTIFICATION_SERVICE);

 notificationManager.notify(NOTIFICATION_ONGOING, notify);

My question is: after calling my updating function, the notification image is actually changed; however, the notification panel is still there!! It does not disappear just like what it should be for launching activities.
Is there a flag I can set for notification, pendingIntent, or what API calls I can use after receiving the intent in service?

A: find my question answered in other place:
1. Android: How to collapse status bar on android 4.2?
2. Preventing status bar expansion
first, add use permission lines to AndroidManifest.xml

<uses-permission android:name="android.permission.EXPAND_STATUS_BAR"/>

second, use following codes to make it work:
try
{
    Object service  = getSystemService("statusbar");
    Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");
    if (Build.VERSION.SDK_INT <= 16)
    {
        Method collapse = statusbarManager.getMethod("collapse");
        collapse.setAccessible(true);
        collapse.invoke(service);
    }
    else
    {
        Method collapse2 = statusbarManager.getMethod("collapsePanels");
        collapse2.setAccessible(true);
        collapse2.invoke(service);
    }
}catch(Exception ex){}

it's hacky, but it did work.


text:
Q: Jumping forward within panels I have a total of 10 panels. They are all on top of each other. There is a location where I want to jump forward a few panels. For example, on panel 7 the user can click the "Skip" button and jump forward to panel 10 and continue OR they can continue from panel 7 to panel 8, panel 9, and then arrive at panel 10.
I've discovered that the "Skip" button isn't going directly to panel 10, although I have placed the code panel10.Visible = true;. Instead it is making panel 10 visible after panel 9 has been arrived at. Hence, the user must go through all the panels to see panel 10 instead of clicking and it jumping there directly (not seeing any panels in between). I've set all the panels visibility to false.
Is there any way to achieve what I want? Have panel 10 display after clicking "Skip" on panel 7?

A: I found the solution. If I want to skip forward some panels, I have to set the panels in between visibility to true. Hence my answer is:
panel8.Visibility = true;
panel9.Visibility = true;
panel10.Visibility = true;

Now I arrive at panel 10 from panel 7 with one click.


text:
Q: spfx modern ui extension(Custom menu only showing in pages under sitepages)? I successfully deployed my custom menu using application customizer(extension) but I noticed the menu only shows up when i view pages under sitepages.
It doesn't come up when viewing list and document libraries.
Is this how its suppose to work?
Thanks in advance

A: Its all about where are you registering the custom menu, basically if you want to have your custom actions in a list / doc lib, you need to use a List View Command set, where you need to set the proper location, so where the commands are displayed. The possible values are:

*

*ClientSideExtension.ListViewCommandSet.ContextMenu: The context menu of the
item(s).

*ClientSideExtension.ListViewCommandSet.CommandBar: The top command set menu in a list or library.

*ClientSideExtension.ListViewCommandSet: Both the context menu and the command bar (corresponds to SPUserCustomAction.Location="CommandUI.Ribbon").

Resulting in having your commands in the list menu like shown here:

Take a look at the following article: https://docs.microsoft.com/en-us/sharepoint/dev/spfx/extensions/get-started/building-simple-cmdset-with-dialog-api#debugging-your-listview-command-set-using-gulp-serve-and-query-string-parameters


text:
Q: Implementing undo and redo in a UITextView with attributedText I'm trying to add undo and redo functionality to my implementation of a UITextView. I am using attributedText and not simply the text property of the UITextView. I've tried using the function calls in undoManager as cited in the Apple documentation, however nothing seems to be happening. I was surprised that I could not find anything on the subject by Googling. Has anyone encountered this issue before / implemented undo and redo on a UITextView with attributedText / knows how to go about this?
Sample Code
textView.attributedText = NSMutableAttributedString(string: "SOME TEXT")

@objc func undo(_ sender: UIButton) {
    textView.undoManager?.undo()
}

@objc func redo(_ sender: UIButton) {
    textView.undoManager?.redo()
}

A: Here's some sample code to handle undo/redo for a UITextView. Don't forget to update your undo/redo buttons state initially and after each change to the text.
class ViewController: UIViewController {

    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var undoButton: UIButton!
    @IBOutlet weak var redoButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        updateUndoButtons()
    }

    @IBAction func undo(_ sender: Any) {
        textView.undoManager?.undo()
        updateUndoButtons()
    }

    @IBAction func redo(_ sender: Any) {
        textView.undoManager?.redo()
        updateUndoButtons()
    }

    func updateUndoButtons() {
        undoButton.isEnabled = textView.undoManager?.canUndo ?? false
        redoButton.isEnabled = textView.undoManager?.canRedo ?? false
    }
}

extension ViewController: UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {
        updateUndoButtons()
    }
}

Obviously you'll need to hook up the actions/outlets and the text view's delegate outlet in a storyboard

A: This isn't the solution to OP's problem but a crude alternative
I've not handled this before I think you could get this by implementing a stack data structure in combination with the UITextField delegate callback textViewDidFinishEditing(textField: UITextField). The idea is that for every change the user makes to the text field, you place the current attributed string onto the stack. The undo feature comes into play by hooking up a button to your stack and popping off the most recent attributed string and setting the textfields attributed string property accordingly.


text:
Q: Ways to compare ordered binary datasets? This question regards the best way to compare ordered binary data. My situation is as follows:
I'm interested in evaluating how well a model conforms to human performance data on a set of validation problems. For a test set of 30 problems, I have a record of whether my model produced a correct response (denoted as a "1") or no response at all** (a "0") within a time limit. Because the model operates probabilistically, I have data for multiple runs of the model on the same test set (organized in a binary matrix of run # vs. problem #). I'd like to compare this accuracy data against the accuracy data produced by a group of human participants working on the same validation set. My question is: what test(s) can I use to measure the degree of coherence between the two datasets that takes into account the different questions in the validation set (i.e., that recognizes that data in the first column of the model accuracy matrix [corresponding to performance on the first question in the validation set] should only be compared against data in the first column of the human accuracy matrix, etc.)?
Apologies if this has been answered elsewhere!
** Because the model is structured such that it never generates a response unless it is the correct one (i.e. it simply keeps running until it either (1) finds the correct answer or (2) runs out of time, whichever comes first), the response output doesn't include false positives or false negatives (so far as I understand those terms).


text:
Q: How to find intersection points between two circles? We have two points (centers of two circles) and their radius in meters, those radius make the circle. We need to find intersection points. For example we have  lat1 = 55.685025, lng1 = 21.118995, r1 = 150 and lat2 = 55.682393, lng2 = 21.121387, r2 = 250. Below you can find our current formula:
// Find a and h.
$a = ($circle_1_r * $circle_1_r - $circle_2_r * $circle_2_r + $distance * $distance) / (2 * $distance);
$h = sqrt($circle_1_r * $circle_1_r - $a * $a);

// Find P2.
$circle_3_x = $circle_1_x + $a * ($circle_2_x - $circle_1_x) / $distance;
$circle_3_y = $circle_1_y + $a * ($circle_2_y - $circle_1_y) / $distance;

// Get the points P3.
$intersection_1 = $this->newLatLngPoint(
    ($circle_3_x + $h * ($circle_2_y - $circle_1_y) / $distance),
    ($circle_3_y - $h * ($circle_2_x - $circle_1_x) / $distance)
);

$intersection_2 = $this->newLatLngPoint(
    ($circle_3_x - $h * ($circle_2_y - $circle_1_y) / $distance),
    ($circle_3_y + $h * ($circle_2_x - $circle_1_x) / $distance)
);

We find such intersection points (yellow markers), however those locations doesn't match in real world.

Someone, can help to find where the problem is and how to sort it ?
P.S.
Does the altitude (Height above mean sea level) affect the final result? I don't use it but may be should?