text:
Q: Swift: combine filter, map to dictionary I've been having a headache of combining two arrays into one.The connection of arrays is like levels.Id = rooms.levelAppreciate all the ideas!
So, here are my 2 arrays of dictionaries:
let levels = [
  ["Name":"Floor 1", "Order":0, "Id": 1],
  ["Name":"Floor 2", "Order":1, "Id": 2],
  ["Name":"Outdoor", "Order":2, "Id": 3]]
let rooms = [
  ["Name":"Master bedroom", "Order":2, "Id": 3, "Level": 2],
  ["Name":"Guest bedroom", "Order":1, "Id": 4, "Level": 2],
  ["Name":"Kitchen", "Order":0, "Id": 1, "Level": 1],
  ["Name":"Boiler", "Order":0, "Id": 2, "Level": 3]]

And result supposed to be like this, sorted by the "Order" value in both arrays :
["Floor 1" : ["Kitchen"],
 "Floor 2" : ["Guest bedroom", "Master bedroom"],
 "Outdoor" : ["Boiler"]]

This is how i made this array but it looks ugly:
func replaceIdWithName(id : Int)->String {
    return rooms.first(where: { $0["Id"] as? Int == id })!["Name"] as! String
}
func getLevelId(id : Int)->String {
    return (levels.first(where: { $0["Id"] as? Int == rooms.first(where: { $0["Id"] as? Int == id })?["Level"] as? Int })?["Name"]) as! String
}
var arr : [String : [Any]] = Dictionary(grouping: rooms.map { $0["Id"] as! Int }, by: { getLevelId(id: $0) })
arr.forEach{ arr[$0.0] = $0.1.map { replaceIdWithName(id: $0 as! Int) } }

And before, i've sorted both arrays by this func:
func sortLevels(p1:[String:Any], p2: [String:Any])->Bool {
    let i = p1["Order"] as? Int
    let j = p2["Order"] as? Int
    if i != nil && j != nil {
        return i! < j!
    } else {
        return false
    }
}

A: struct Level {
    let name: String
    let order: Int
    let id: Int
}

struct Room {
    let name: String
    let order: Int
    let id: Int
    let level: Int
}

first you need to do some mapping for easier work
let mappedLevels = levels.flatMap { level -> Level? in
    guard let name = level["Name"] as? String, let id = level["Id"] as? Int, let order = level["Order"] as? Int else { return nil }

    return Level(name: name, order: order, id: id)
}

this one levelIdMappings will be used later for easier work
let levelIdMappings = mappedLevels.reduce(Dictionary<Int, Level>()) { (result, level) -> Dictionary<Int, Level> in
    var mutableResult = result
    mutableResult[level.id] = level

    return mutableResult
}

do also room mapping
let mappedRooms = rooms.flatMap { room -> Room? in
    guard let name = room["Name"] as? String, let id = room["Id"] as? Int, let order = room["Order"] as? Int, let level = room["Level"] as? Int else { return nil }

    return Room(name: name, order: order, id: id, level: level)
}

now filter only levels which you are interested in and fill levelRoomsMapping ( I could do this with reduce)
var levelRoomsMapping = Dictionary<Int, [Room]>()

mappedRooms.filter { levelIdMappings.keys.contains($0.level) }.forEach {
    if var rooms = levelRoomsMapping[$0.level] {
        rooms.append($0)
        levelRoomsMapping[$0.level] = rooms
    } else {
        levelRoomsMapping[$0.level] = [$0]
    }
}

and now just filter information what you need, and create final dictionary
let finalResult = levelRoomsMapping.reduce(Dictionary<String,[String]>()) { (dictionary, next) -> Dictionary<String,[String]> in
    guard let key = levelIdMappings[next.key]?.name else { return dictionary }

    var mutableDictionary = dictionary
    mutableDictionary[key] = next.value.map {
        $0.name
    }

    return mutableDictionary
}

You can paste it to playground and print whatever you like to get better insight

A: Working with arrays of dictionaries directly is going to be a type casting nightmare.  But if you want to do it anyways, Swift 4's new Dictionary initializers can help.
Here's an example:
let levelNames = [Int:String](uniqueKeysWithValues:levels.map{($0["Id"]! as! Int, $0["Name"] as! String)})
let roomLevels = rooms.map{( levelNames[$0["Level"]! as! Int]! , [$0["Name"]! as! String])}
let levelRooms = [String:[String]](roomLevels, uniquingKeysWith:+)

print(levelRooms)
// ["Floor 1": ["Kitchen"], "Floor 2": ["Master bedroom", "Guest bedroom"], "Outdoor": ["Boiler"]]

.
The levelNames variable will act as an index to get a level name from a level Id.
The roomLevels variable is an array of room names with their respective level name obtained using the levelNames variable.  Note that the room name is returned as a single element array to make the next step easier.
levelRooms is the final dictionary initialized with the uniquingKeysWith option which will combine values (room names) for entries with identical keys (level name).   Because the room name was returned as a single element array, we can simply use the + operator for the combining function and it will perform array additions into a multi-element array for the level name.
[EDIT] note that you could hide away most of the type casting while still using the arrays of dictionaries as your data structure by creating functions to access the values by their key names.
struct Level
{
   static func Id(_ dict:[String:Any])    -> Int    { return dict["Id"]    as? Int    ?? 0 }
   static func Name(_ dict:[String:Any])  -> String { return dict["Name"]  as? String ?? ""}
   static func Order(_ dict:[String:Any]) -> Int    { return dict["Order"] as? Int    ?? 0 }
}

struct Room
{
   static func Id(_ dict:[String:Any])    -> Int    { return dict["Id"]    as? Int    ?? 0 }
   static func Name(_ dict:[String:Any])  -> String { return dict["Name"]  as? String ?? ""}
   static func Level(_ dict:[String:Any]) -> Int    { return dict["Level"] as? Int    ?? 0 }
   static func Order(_ dict:[String:Any]) -> Int    { return dict["Order"] as? Int    ?? 0 }
}

The above solution would then be much more readable and you get the added benefit of not repeating key names in string literals all over your code
let levelNames = [Int:String](uniqueKeysWithValues:levels.map{(Level.Id($0), Level.Name($0))})
let roomLevels = rooms.map{( levelNames[Room.Level($0)]! , [Room.Name($0)])}
let levelRooms = [String:[String]](roomLevels, uniquingKeysWith:+)


text:
Q: What is the last part of rpm package release field? Example 1:
using yum info vim-enhanced I get this:
Name        : vim-enhanced
Arch        : x86_64
Epoch       : 2
Version     : 7.4.629
Release     : 5.el6_8.1
Size        : 2.2 M
Repo        : installed

Example 2:
yum info kernel
Installed Packages
Name        : kernel
Arch        : x86_64
Version     : 3.10.0
Release     : 514.el7
Size        : 148 M
Repo        : installed
From repo   : anaconda
Summary     : The Linux kernel
URL         : http://www.kernel.org/
License     : GPLv2
Description : The kernel package contains the Linux kernel (vmlinuz), the core of any
            : Linux operating system.  The kernel handles the basic functions
            : of the operating system: memory allocation, process allocation, device
            : input and output, etc.

Name        : kernel
Arch        : x86_64
Version     : 3.10.0
Release     : 514.26.2.el7
Size        : 148 M
Repo        : installed
From repo   : updates
Summary     : The Linux kernel
URL         : http://www.kernel.org/
License     : GPLv2
Description : The kernel package contains the Linux kernel (vmlinuz), the core of any
            : Linux operating system.  The kernel handles the basic functions
            : of the operating system: memory allocation, process allocation, device
            : input and output, etc.

what I really interested in is Release field:  5.el6_8.1 , 514.el7, 514.26.2.el7.
According to some answers, there is no official rule governing the naming convention of Release field.  is this true? or do they have specific naming convention for each kind of software package?

A: See https://fedoraproject.org/wiki/Packaging:DistTag for comprehensive documentation.
This macro is used to distinguish two identical packages, which are in fact not identical.
For example package python-alembic. You can have files python-alembic-0.9.1-1.el6.rpm and python-alembic-0.9.1-1.fc26.rpm. They have the same content, the same code. But they are stored in different path. EL6 use /usr/lib/python2.6/site-packages/alembic but FC26 have /usr/lib/python2.7/site-packages/alembic (the difference is in python version).
So .el6 package will not work in Fedora 26 and vice versa.
Without the dist tag you will have only python-alembic-0.9.1-1 and you will have hard time to figure whether it is suitable for your OS.
And you usually do not define the content of dist tag. It is defined by one of system packages automatically.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to write two install .iso (for example windows and linux) on one flash? How to write two installer .iso images (for example Windows and a Linux system like Ubuntu) on one USB flash drive?

A: You can use YUMI (Your Universal Multiboot Installer). Its a great utility to list down multiple ISO files in one boot menu.


text:
Q: Can't find the error in my javascript code This js program should display the first 100 prime numbers, but instead it crashes each and every time and I can't find the error! Could someone point me towards the best way to debug js code?! Thank you!
// initialisation of the array p holding the first 100 prime numbers
var p = [];

// set the first prime number to 2
p.push(2);

// find the first 100 prime numbers and place them in the array p
var i = 3;
while (p.length < 100) {
    var prime = true;
    loop:
    for (var item in p){
        if (i%item === 0){
            prime = false;
            break loop;
        }
    }
    if (prime)
        p.push(i);
    i = i + 2;
}

// display the first 100 prime numbers found
var i=1;
for (var item in p){
    document.writeln(i,item);
    i++;
}

A: Change:
for (var item in p) {

to:
for (var i = 0; i < p.length; i++) {
    item = p[i];

for-in iterates over the keys of an object or array, not the values.

A: First, put your algorithm in to a funciton and put this function into a page html. like:

    test

then open this page in Chrome or firefox.
press F12 to open the debug panel.
then go to Sources tag dans choose your page (for exemple: test.html) in the left view and make a stop point debug on the line var p =[];then click the link test on the page to begin your debug. F10 to go to another line and F11 to enter method, F8 to go to next stop point.
Hope that helps.

A: Just change
if (i%item === 0){

to
if (i % p[item] == 0){

then it will work.
jsfiddle

A: This is what the final working code looks like:
// initialisation of the array p holding the first 100 prime numbers
var p = [];

// set the first prime number to 2
p.push(2);

// find the first 100 prime numbers and place them in the array p
var i = 3;
var item;
var prime;
while (p.length < 100) {
    prime = true;
    for (item in p){
        if (i%p[item] === 0){
            prime = false;
            break;
        }
    }
    if (prime)
        p.push(i);
    i = i + 2;
}

// display the first 100 prime numbers found
var s = "";
for (item in p){
    if (item != p.length - 1){
        s = s + p[item] + ",";
    }
    else{
        s = s + p[item];
    }
}
alert(s);


text:
Q: Triple integral between two spheres Evaluate
$$
\iiint_{E}(2.1 z) d V
$$
where $E$ is bounded between two spheres:
$$
x^{2}+y^{2}+z^{2}=8.5^{2} \text { and } x^{2}+y^{2}+(z-8.5)^{2}=8.5^{2} .
$$
Region between two spheres
I am supposed to convert the integral to spherical coordinate $(\rho, \phi, \theta)$ where $\phi$ is the azimuthal angle and $\theta$ is the polar angle. I don't know how to determine the boundaries of the three variables. Please help me.
Here is my attempt
We have
$\rho = \sqrt{x^2 + y^2}$
The region is in the upper half of the first sphere so
$$x^2 + y^2 + z^2 = 8.5^2 \implies z = \sqrt{8.5^2 - \rho^2} \quad (1)$$
For the second sphere, it is in the lower half so I took the minus sign instead
$$x^2 + y^2 + (z-8.5)^2 = 8.5^2 \implies z = -\sqrt{8.5^2 - \rho^2} + 8.5 \quad (2)
$$
From (1) and (2), I found the intersection $\displaystyle z = 4.25, \rho = \frac{17\sqrt3}{4}$
Therefore the integral is
$$\int_0^{2\pi}\int_{0}^{\frac{17\sqrt3}{4}}\int_{-\sqrt{8.5^2 - \rho^2} + 8.5}^{\sqrt{8.5^2 - \rho^2}} (2.1z\rho) dzd\rho d\phi$$

A: Your working is correct for cylindrical coordinates. If you were to do it in spherical coordinates,
$x = \rho \cos\phi \sin \theta, y = \rho \sin\phi \sin\theta, z = \rho \cos\theta$
$x^2 + y^2 + (z-8.5)^2 = 8.5^2 \implies x^2 + y^2 + z^2 = 17 z$
So $ \ \rho = 17 \cos\theta, 0 \leq \theta \leq \frac{\pi}{2}$
The sphere centered at the origin is $\rho = \dfrac{17}{2}$
At intersection of both sphere, $\rho = 17 \cos\theta = \dfrac{17}{2} \implies \theta = \dfrac{\pi}{3}$
Now if we integrate wrt $\rho$ first and then $\theta$, we need to split it into two integrals. For $0 \leq \theta \leq \dfrac{\pi}{3}$, $\rho$ is bound above by the sphere centered at the origin whereas for $\dfrac{\pi}{3} \leq \theta \leq \dfrac{\pi}{2}$, $\rho$ is bound above by the sphere $\rho = 17 \cos\theta$.
But if we integrate wrt $\theta$ first, we can set it up in one integral.
$\displaystyle \int_0^{2\pi} \int_0^{17/2} \int_0^{\arccos(\rho/17)}  1.05 \rho^3 \sin (2\theta) \ d\theta \ d\rho \ d\phi$


text:
Q: What is the density of random variable $\sqrt{X}$?
Given is $U \sim R(0,1)$ and $X=g(U) = -\frac{1}{\lambda} \ln(U),
\space \space \lambda > 0$
What is the density of random variable $\sqrt{X}$?
($X \sim R(a,b)$ in general means equal distribution.)

Original question is from here Calculate the densitiy of the random variable $X$
But I wondered how you can do it correct and easy when there is little change, like here from $X$ to $\sqrt{X}$.
$$P(\sqrt{X} \leq x) = P\left(\sqrt{-\frac{1}{\lambda} \cdot \ln(U)} \leq x\right) = P\left(-\frac{1}{\lambda} \cdot \ln(U) \leq x^2\right) = P\left(\ln(U) \geq  -\lambda x^2\right) = P\left(U \geq e^{-\lambda x^2}\right)$$
$$F_X(x) = \int_{e^{-\lambda x^2}}^{1} dU = 1-e^{-\lambda x^2}$$
$$f(x) = \frac{d}{dx}\left(1-e^{-\lambda x^2}\right) = -\lambda 2xe^{-\lambda x^2}$$
Is it correct like this?


text:
Q: Upgrading old SAN, expected performance increase? I am working with a postgresql database that sits on really old Hardware.
1 Sun Sunfire V60x with a single 3.0ghx Xeon FSB 400 512kb cache with 6gb of RAM running RHEL 4 (32bit)
The table space and logs are stored in the same 250gb LUN on a Hitach 9520v SAN running with 8 10k RPM USCSI drives with 146gb each.
Our budget is tight and given the performance advance of modern HDD's and cheap RAM I wonder how many new 15k RPM drives it would take to offer the same performance.
The table space is around 80 GB and our workload is probably 90% read and 10% write as the RDMS holds our organizations registry and is [almost] only used for reporting.
Edit: We will be using a brand new server with 2x Xeon 5620s and 32gb of RAM. I wonder if I can avoid the expense of the SAN.

A: I'm not sure how much help more RAM would be as you have a 32bit environment.  More RAM would be a pretty inexpensive upgrade to see how much it would help out.
New 15k drives would give you some performance improvement, depending on where your bottleneck currently is.  If you aren't storage bound then spending money on the storage isn't going to do anything for you.  I think you need to dig into the metrics of your server before you decide where to spend your money.
(My experience is from using Microsoft SQL Server on Windows, but the basic metric information and the underlying principals are the same.)

A: Truthfully, the investment into HDDs would only give a slight improvement at best for disk-access.  I think you'd be waisting most of your money if you invested in new drives.  As far as RAM.... when it comes to RDBMS, recommended is "MORE".   No matter how much you have, more is better.  It wouldn't hurt to do some profiling either & find out where your pinch-points are.  You might simply need to add an index to one or two fields & would see HUGE improvements in performance.

A: I guess that you could at least match the performance of your old SAN with a modern server grade SSD (or a few with a good RAID controller), and likely have much better access times.

A: SAN is used to export block devices .. the only thing that SAN offers is flexibility in storage (single point of storage, any point of mount over the net of connection of you choosing). In speed you cannot beat the local attached storage in hardware (or software) raid ... if you need speed, the easiest, fastest and cheapest (as you already have the hdds) solution would be (IMHO) raid 10 (4 hdds in raid1 and the both volumes in raid0) and that would give you 2 x 146 gb of storage ... also 2 X hdds in raid 1 and 4 x raid1 in raid0 would also be a solution...
anyway at this stage and at this size i would strongly recommend to look over ssd prices and capacities .. 2 X 240 gb ssd (consumer) in raid1 are smoking fast!

A: Have you thought about software based ISCSI SANs as an alternative, check http://www.starwindsoftware.com/starwind. You will be able to cut cost, have your centralized storage, and have a scalable solution for clustering if that is something you are considering to do in the future. Otherwise, direct attached storage will probably satisfy your I/O.


text:
Q: Scrollbars in TextView I just didn't want to use ScrollView. So I have a textview with enabled vertical scrollbars.
<TextView
    android:id="@+id/tv_service_ticketinfo_details"
    android:layout_width="fill_parent"
    android:layout_height="150dp"
    android:textColor="@color/black"
    android:autoLink="web"
    android:scrollbars="vertical"
    android:text="empty"
    android:background="@drawable/custom_shape_grey">
</TextView>

The problem is, that scrollbars are scrollable only for texts, which contain a web-links. For other texts I see a scrollbar, but can't scroll.
I can't explain it. And you?
UPD:
Another strange thing:
once I set the text with links, then I can replace it by another one without links and the textView stays scrollable

A: So I think the problem is that TextViews don't automatically scroll, just because you set android:scrollbars. You have to set the ScrollingMovementMethod.
However, when you use autoLink and links are found, the android framework will set the MovementMethod for you. That's why the behaviour's different.
There are two solutions that work for me.
After we set our text, force the movement method to one that supports links and scrolling.
final TextView output = (TextView) findViewById(R.id.output);
output.setText(content);
// ensure that text will scroll with or without linked text
output.setMovementMethod(LinkMovementMethod.getInstance());

Or set the movement method, assuming plaintext, before adding text to the TextView. If autoLink detects links, it will change the movement method itself.
final TextView output = (TextView) findViewById(R.id.t_output);
// ensure that text defaults to scrollable
output.setMovementMethod(ScrollingMovementMethod.getInstance());
output.setText(content);

(FYI: I'm using android:autoLink="all")

A: add this in your code(may be in onCreate)
//textView.setMovementMethod(ScrollingMovementMethod.getInstance());
tv_service_ticketinfo_details.setMovementMethod(ScrollingMovementMethod.getInstance());

and test.

A: To get a scroll bar at run time or from code, you may try with following solution:
xml:
<LinearLayout
        android:id="@+id/view1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center">
          <TextView
                   android:id="@+id/tv_service_ticketinfo_details"
                   android:layout_width="fill_parent"
                   android:layout_height="150dp"
                   android:textColor="@color/black"
                   android:autoLink="web"
                   android:scrollbars="vertical"
                   android:text="empty"
                   android:background="@drawable/custom_shape_grey">
          </TextView>
   </LinearLayout>

java:
mTextViewPort = (LinearLayout) findViewById(R.id.view1);
// Create a ScrollView instance
ScrollView mScrollView = new Scrollview(mContext);
// here mContext would be Activity's context. You may also choose
// mScrollView as a global variable.
mScrollView.setScrollBarStyle(SCROLLBARS_OUTSIDE_INSET);
mTextViewPort.addView(mScrollView,
    new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
TextView mTextView = (TextView) findViewById(R.id.tv_service_ticketinfo_details);
mScrollView.addView(mTextView );

This may help to resolve this problem.


text:
Q: How do I combine spring errors tag logic with jstl logic I have the following div for displaying my spring messages.  errorContainer DIV and errText UL contain the classes to show my error icon and format my error message text.
<c:if test="${not empty modelAttr}">
  <spring:hasBindErrors name="${modelAttr}">

        <form:errors path="*" element="li" delimiter=

" />

  </spring:hasBindErrors>
</c:if>

I want to also use the errorContainer(or a duplicate div) for my jquery error messages.  I need to figure out how to rewrite the previous jstl and spring tag logic to put another div on the page only when the c:if and spring:hasBindErrors tags above evaluate to false together.  I need to base my conditional on the outcome of both of these tags without putting my new div within them.

A: Could you just add another condition in the jstl tag to check when your conditions are met?
<c:choose>
    <c:when test="${not empty modelAttr}">   <%-- evaulates to true --%>
      <spring:hasBindErrors name="${modelAttr}">

             <form:errors path="*" element="li" delimiter=

" />

      </spring:hasBindErrors>
    </c:when>
    <c:otherwise> <%-- evaulates to false --%>
        Your spring test in here
    </c:otherwise>
</c:choose>


text:
Q: Here FindSequence Limit Waypoint I need to get an optimized sequence of a route with up to max 120 waypoints.
I was trying to use "Here API" but with trial plan (I guess) even though I enter 10/20/30/40 destinations (waypoints), it always calculates only the top 5 destinations.
Is a plan problem?
thanks!
Maurizio

A: I'm using it successfully with up to 119 waypoints. I'm a customer (not trial).
Endpoint I'm using:  https://wse.api.here.com/2/findsequence.json
Hope it helps


text:
Q: Do I need full recovery mode when I have multiple daily backup? I have created 5 maintenance plans on my SQL server (say 50 !) which generate databse backup 5 times daily. As I read in this Q/A the full recovery is good when I need Point-in-time recovery.
My exact question: Is generating multiple daily backup with simple recovery model, similar to full recovery backup with longer period?

A:
I have created 5 maintenance plans on my SQL server (say 50 !) which generate database backup 5 times daily.

Why not just create one maintenance plan and run it five times.

My exact question: Is generating multiple daily backup with simple recovery model, similar to full recovery backup with longer period?

Full backups or differential backup, no matter in what recovery model you take, are same in terms on what they backup. Now I believe you have combination of full and differential backups and my answer is it all depends on on RPO and RTO (how much data you are willing to loose in case of disaster). A DB in simple recovery model which can afford some data loss and does not needs point in time recovery would just do fine with full and differential backups.
The other important thing is you make sure you restore the backup files on other machine to see that you meet your recovery objective

A: Setting a database to full recovery is not enough by itself to ensure you have point in time recoverability. You also need to take regular log backups. You should also be taking time regularly to test that you personally know how to execute the required commands to actually perform a restore to an arbitrary point-in-time.
In lieu of running loads of home brewed full backups, the fire-and-forget solution you want is probably to just install Ola Hallengren's backup solution. Running this script installs the required objects and deploys the required jobs to manage all of the full recovery databases on an instance. You will find these jobs 1 under SQL Server Agent > Jobs named by default DatabaseBackup - USER_DATABASES ... and similar. Add a schedule to these jobs that suits you 2 and disable other backup jobs to prevent conflicts.
You should still need to regularly take time in the normal course of business to ensure you and others on your team are able to actually restore the backups you have, regardless of how you take them.

1: assuming you're using SSMS here
2: 5 times daily if you like, but probably a bit less is fine


text:
Q: linear combinations of Chebyshev polynomials of first and second kind I do not know if this problem was considered before.
Prove that there are infinitely many pairs $(a,b)$ of mutually prime integers such that none of the polynomials
$P_n(x) = a*T_n(x) +b*U_n(x) $
has a quadratic factor of the form $(c*X^2+d)$ where $c$ and $d$ are nonzero integers. Here $T_n$ and $U_n$ are the Chebyshev polynomials of first and second kind and $n$ varies over the set of positive integers.
I suspect much more is true, that is, there are infinitely many such pairs $(a,b)$ for which $P_n(x)$ is "almost" irreducible for every $n$. The word "almost" is needed since both $T_n(x)$ and $U_n(x)$ have a factor of x when n is odd.
I did some testing in MAPLE and it looks like the set of such good pairs $(a,b)$ may even have positive density in $\mathbb{Z}^2$. Any help would be greatly appreciated.


text:
Q: Inserting a footnote on a bibliography entry I am not trying to make footnote citation. What I am doing is citing some unpublished correspondence in my thesis. I am publishing those in an appendix. So I want to add a footnote to the bibliography pointing the reader to the appendix if they are interested in the citation.
I am using biblatex with the following command:
\usepackage[backend=biber, style=ieee]{biblatex}

The citation I want to add the footnote on looks like this in the bib file:
@misc{GRPHT_DOCS_5,
author={Keenan, Charles H.},
organization={Brookhaven National Laboratory Associated Universities Inc.},
howpublished={Private Correspondance with T. Cantwell},
title={Letter authorizing the sale of 100 tons of graphite to MIT.},
month={April},
year={1955}
},

A: This solution does not add a footnote, but places the hint in the entry directly. It was not clear to me where the footnote should be attached to.
You use the command \includefullref{<entrykey>} in the appendix when you include a copy of the full source. Everything else happens automatically: If that command was called it creates a label full:<entrykey>, if such a label is defined the corresponding bibliography entry refers to that label.
\documentclass[british]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{babel}
\usepackage{csquotes}

\usepackage[backend=biber, style=ieee]{biblatex}

\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@misc{GRPHT_DOCS_5,
  author       = {Keenan, Charles H.},
  organization = {Brookhaven National Laboratory Associated Universities Inc.},
  howpublished = {Private Correspondance with T. Cantwell},
  title        = {Letter authorizing the sale of 100 tons of graphite to MIT.},
  date         = {1955-04},
}
\end{filecontents}

\addbibresource{\jobname.bib}
\addbibresource{biblatex-examples.bib}

\renewbibmacro{finentry}{%
  \ifcsundef{r@full:\thefield{entrykey}}
    {}
    {\printtext{see section~\ref{full:\thefield{entrykey}}
       on page~\pageref{full:\thefield{entrykey}}}}%
  \finentry}

\newcommand*{\includefullref}[1]{\section{\citetitle{#1}}\label{full:#1}}

\begin{document}
\cite{sigfridsson,GRPHT_DOCS_5}
\printbibliography

\appendix
\includefullref{GRPHT_DOCS_5}
Full text here
\end{document}


text:
Q: SharePoint Getting errors: "Version conflict" or "The file XXX has been modified by YYY on ZZZ date and time" SharePoint Problem:
For a library created with Versioning Settings set to No Versions
For folders created with Add-PnPFolder, when some (it's intermittent) of the folders are later modified with Set-PnPListItem or Set-PnPListItemPermission:
One of these two ExecuteQuery errors (may) occur:

*

*Version conflict.

*The file XXX has been modified by YYY on ZZZ date and time.

Environment:
SharePoint 2019
WindowsPowerShell\Modules\PnP.PowerShell
PSVersion 5.1.19041.2364


text:
Q: Storing text lines in an array, C I am new to C and I am confused how I can read through a file and store each line to an index of an array.
Example file:

What color is the sky?  Red  Orange  Yellow  Blue

Desired result of code:

input[0] = What color is the sky?  input[1] = Red  input[2] =
  Orange  input[3] = Yellow  input[4] = Blue

Hhere is what I have so far:
char input[60];

//declare string array of size 80, for 80 lines

for(int i = 0; fgets(input, sizeof(input), inFile)!=NULL; i++){

    //string[i] = input; storing this line to the string index

}

//later on use the string[80] that now has all lines

I understand that declaring input[60] is only determining the length of each line, not the number of lines. I am so used to thinking about strings in other coding languages, that the use of char is throwing me off. I have tried video tutorials but they didn't help me.

A: Each line of the file is a different string, and each string is a char* pointer to an array; so what you are needing is a 1D array of char* pointers (or alternately a 2D array of char.)
char *line[ MAX_LINES ];  // 1D array of char* pointers.

You can either initialize a two dimensional array of char, or you can malloc the memory for each line of the 1D  char* pointers.
Here's an example of the malloc approach.  The variable it's stored in is called "line" rather than "input"; but you can exchange the variable names if you like, and change the print formatting to solve your particular problem.  This is just intended as an example of reading the strings into memory, in the same way you desire.  No practical system has less than 4K of heap space, so I've omitted the malloc memory check.
#include <string.h>
#include <malloc.h>
#include <stdio.h>

#define MAX_LINES 10
#define MAX_LEN   60

int main( int narg, char *arg[] ) {
    char input[ MAX_LEN ];
    char *line[ MAX_LINES ];
    FILE *inFile;
    int i,j;

    if ( narg != 2 ){fprintf( stderr, "Use: %s filename\n", arg[0] ); return 2;}
    if (!(inFile=fopen(arg[1],"r") )){
          fprintf( stderr, "Can't open '%s'\n",arg[1]);
          return 2;
    }

    for ( i=0; i<MAX_LINES && fgets(input, sizeof(input), inFile ); ++i ) {
        int lineLen=strlen(input) + 1;
        line[i] = strncpy( malloc( lineLen ), input, lineLen );
    }

    for ( j=0; j<i; ++j ) { printf( "Line %d:%s", j+1, line[j] ); free(line[j]); }
    fclose(inFile);
    return 0;
}


text:
Q: Getting error messages from psycopg2 exceptions This is my first project using psycopg2 extensively. I'm trying to find a way to extract the psql error message for whenever a connection attempt fails. I've tested the code below will work if all the variables are set correctly, however whenever an error condition occurs (e.g. user chooses a database that doesn't exist), Python will give me the following:
I am unable to connect to the database
None
Traceback (most recent call last):
  File "./duplicate_finder.py", line 163, in <module>
    main(sys.argv[1:])
  File "./duplicate_finder.py", line 142, in main
    print e.diag.message_detail
AttributeError: 'OperationalError' object has no attribute 'diag'

Is there a simple, catch-all method to catch whatever error message psql generates when a connection fails, or do I need to write except blocks for multiple psycopg2 exceptions?
Extract from my script:
import sys, getopt, os, time, csv, psycopg2

    ...
    ...

    conn_string = "host=" + dbhost + " dbname=" + database + " user=" + dbuser + " password=" + dbpass
    try:
        conn = psycopg2.connect(conn_string)
    except psycopg2.Error as e:
        print "Unable to connect!"
        print e.pgerror
        print e.diag.message_detail
        sys.exit(1)
    else:
        print "Connected!"
        cur = conn.cursor()
        cur.execute("SELECT id, lastname, firstname, location FROM test ORDER BY ctl_upd_dttm DESC;")
        print cur.fetchone()
        ...
        conn.close()

A: Ended up here because of

class 'psycopg2.errors.InvalidCursorName'

on Django. If that's your case, be sure to makemigrations

A: You are catching all exceptions with the base class psycopg2.Error. Your problem is probably that the diag attribute is new in psycopg2 2.5. What is your version?
>>> print psycopg2.__version__
2.5.1 (dt dec pq3 ext)

A: When I try to catch exceptions, e.pgerror is always None for connection errors. The following code block gets around this by directly printing 'e'.
try:
    conn = psycopg2.connect(conn_string)
except psycopg2.OperationalError as e:
    print('Unable to connect!\n{0}').format(e)
    sys.exit(1)
else:
   print('Connected!')
   # do stuff

For example, in the case of password authentication failure:
Unable to connect!
FATAL:  password authentication failed for user "user"

I realize this question is a year old but hopefully might help someone in the future

A: Since Python 3.9 (.removesuffix(), f-strings) I use
except psycopg2.Error as e:
  log.error(f"{type(e).__module__.removesuffix('.errors')}:{type(e).__name__}: {str(e).rstrip()}")
  if conn: conn.rollback()

where log is logger.
Connection errors lives directly in psycopg2 module while syntax errors in psycopg2.errors submodule. There is an unwanted newline at the end of every psycopg2 error message.


text:
Q: How to insert/update an updatable view using EF Code-First I have a scenario in which I have created an updatable view composed of several tables that uses INSTEAD OF triggers. I have verified that I can manually insert into this view using SSMS without an issue. However, as my application is using EF Code-First to represent the view, when attempting to insert a record I end up with a problem because of the EF's use of SCOPE_IDENTITY() in the subsequent SELECT after the insert statement. I have tried including a statement at the end of my trigger to "force" the scope_identity()'s inclusion, but without success. I have also tried including the OUTPUT option on my insert statement with no luck either. I'm beginning to wonder if my scenario is too complex for EF to handle?
Based upon feedback, I am greatly simplifying this scenario into something that's easy to reproduce for everyone:
The relevant table and view definitions:
IF NOT EXISTS(SELECT * FROM [sysobjects] WHERE [type] = 'U' AND [name] = 'Parent')
BEGIN
    CREATE TABLE [dbo].[Parent]
    (
        [ent_pk] INT IDENTITY(1,1) NOT NULL,
        [ent_id] VARCHAR(25) DEFAULT('') NOT NULL,
        CONSTRAINT [PK_Parent] PRIMARY KEY CLUSTERED ([ent_pk])
    )
END
GO
IF NOT EXISTS(SELECT * FROM [sysobjects] WHERE [type] = 'U' AND [name] = 'Child1')
BEGIN
    CREATE TABLE [dbo].[Child1]
    (
        [c1_entfk] INT NOT NULL,
        [c1_field1] VARCHAR(30) DEFAULT('') NOT NULL,
        [c1_fees] DECIMAL(7,2) DEFAULT(0) NOT NULL,
        CONSTRAINT [PK_Child1] PRIMARY KEY CLUSTERED ([c1_entfk])
    )
END
GO
IF EXISTS(SELECT * FROM sys.views WHERE [object_id] = OBJECT_ID(N'[dbo].[vwView]'))
    DROP VIEW [dbo].[vwView]
GO
CREATE VIEW [dbo].[vwView] AS
SELECT [ent_pk],
    [ent_id],
    [c1_field1],
    [c1_fees]
    FROM [Parent]
        LEFT JOIN [Child1] ON [c1_entfk] = [ent_pk]
GO

The trigger code is as follows:
IF EXISTS(SELECT * FROM sysobjects WHERE [type] = 'TR' AND [name] = 'trg_vwView_i')
    DROP TRIGGER [trg_vwView_i]
GO
CREATE TRIGGER [trg_vwView_i] ON [dbo].[vwView] INSTEAD OF INSERT
AS
BEGIN
    INSERT INTO [Parent] ([ent_id])
        SELECT [ent_id]
        FROM [Inserted] [I]

    INSERT INTO [Child1] ([c1_entfk], [c1_field1], [c1_fees])
        SELECT [E].[ent_pk], [c1_field1], [c1_fees]
        FROM [Inserted] [I]
            INNER JOIN [Parent] [E] ON [E].[ent_id] = [I].[ent_id]
END
GO

Because of Foreign Key constraints not included in the above table and view definitions, the Parent record must be inserted first before inserting the records in the other tables in order to maintain referential integrity.
And the POCO class definition is:
[Table("vwView")]
public class SimpleViewTest
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ent_pk { get; set; }

    [MaxLength(25)]
    public string ent_id { get; set; }

    [MaxLength(30)]
    public string c1_field1 { get; set; }

    public decimal c1_fees { get; set; }

}

A sample of the SQL generated by EF for the insert:
exec sp_executesql N'INSERT [dbo].[vwView]([ent_id], [c1_field1], [c1_fees])
VALUES (@0, @1, @2)
SELECT [ent_pk]
FROM [dbo].[vwView]
WHERE @@ROWCOUNT > 0 AND [ent_pk] = scope_identity()',N'@0 nvarchar(25),@1 nvarchar(30),@2 decimal(7,2) ',@0=N'AK FED CU',@1=N'Alaska Federal Credit Union',@2=10.00

Now, executing the above SQL statement in SSMS correctly inserts the records into the various tables. But, it fails to return anything in the select because SCOPE_IDENTITY() returns NULL.
So, I'm not sure how to get the SCOPE_IDENTITY() to return the value for the insert into the [Parent] table or if it's even possible. Does anyone know if this is something that can be done, or if I need to explore defining stored procedures to handle this sort of scenario? Or are there any other suggestions people have?
NOTE: I want to represent the entity in my application as a "flat" object, not one composed of multiple objects...

A: Ok. After digging around a lot more into the EF documentation, I ran across this: https://msdn.microsoft.com/en-us/library/dn469464(v=vs.113).aspx. Furthermore, I found the following BLOG post regarding implementing the IDbCommandInterceptor where it makes reference to being able to modify the SQL generated by EF before it gets executed: https://www.skylinetechnologies.com/Blog/Skyline-Blog/December-2013/Entity-Framework-6-Intercepting-SQL-produced.
So, my solution was to implement my own IDbCommandInterceptor and override the ReaderExecuiting method as follows:
public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
    string sqlToIntercept = "INSERT [dbo].[vwView]";

    if (command.CommandText.Contains(sqlToIntercept))
    {
        command.CommandText = command.CommandText.Replace("WHERE @@ROWCOUNT > 0 AND [ent_pk] = scope_identity()", "WHERE @@ROWCOUNT > 0 AND [ent_id] = @1");
    }
}

Now, while not perfectly suited to every possible variation of this problem, in my case it does work quite nicely as the ent_id field in the Parent table must be unique thanks to business rules.
Hopefully, even if this scenario isn't exactly the same as a similar one you may encounter, this solution may provide additional direction allowing you to solve your specific scenario.
Thanks to everyone who took the time to read this and comment. All the best.


text:
Q: tikz parameterized circle node with t-lines inside within a tree diagram I would like to draw a tree diagram consisting of circle nodes with three subparts divided by a t-line (see sample below). Instead of separating every tree node by hand I would like to only specify the style of the node accompanied by at least three parameters (the fields inside the circle node drawing). I already achieved the following by putting the following by putting this stackexchange circle node with t-lines example into a style:
\tikzset{%
  sectors/.style n args={5}{%
    circle,
    draw,
    minimum width=#4,
    append after command={
      \pgfextra{
        \draw (\tikzlastnode.center) -- (\tikzlastnode.south) ;
        \draw (\tikzlastnode.west)   -- (\tikzlastnode.east) ;
        \path (\tikzlastnode.center) -- node[#5] {#1} (\tikzlastnode.north);
        \path (\tikzlastnode.center) -- node[#5] {#2} (\tikzlastnode.south west);
        \path (\tikzlastnode.center) -- node[#5] {#3} (\tikzlastnode.south east);
      }
    }
  }
}

This works fine as long as there is only one root node. But as soon as I want to draw children nodes tikz fails to compile sayiong "Error: No shape named is known. [...]". So the following does not work.
\begin{tikzpicture}[]

  \node[sectors={0}{1}{1}{1.5cm}{}]{}%
    child{
      node [sectors={1}{2}{3}{1.5cm}{font=\bfseries}]{}
    };%
\end{tikzpicture}

I already noticed that there are problems with using tex macros within tree structures but I was not able to find a solution through the answers given there. I have not specified a simple tex-macro but a parameterized style. Maybe under the hood this works similar but I am not a pro when it comes to tikz and therefore was not able to adapt the solutions to this case.
Any help would be appreciated.
Here you see an outline of the tree structure I want to achieve:

A: append after command uses a similar approach for saving the node's name as the tree uses to connect the nodes. For this, I borrow most of the code from a label or a pin and apply it in your example, too. I am using edges here since with your \pgfextra example, you would also need the additional \pgfinterruptpath.
Unfortunately, both implementations do not inherit the style from the node. The path picture does this if I recall correctly but is very impractical in combination with transformations and you cannot use the node's anchors.
For the best experience it would be best to implement this as a separate shape (at least the lines inside the circle).
Code
\documentclass[tikz]{standalone}
\makeatletter
\tikzset{
  sectors/.style n args={5}{
    shape=circle, draw, minimum width={#4},
    append after command={%
      \bgroup
        [current point is local = true]
        \pgfextra{\let\tikz@save@last@fig@name=\tikz@last@fig@name}
        {[-,shorten >=+.5\pgflinewidth, shorten <=+.5\pgflinewidth]
          (\tikzlastnode.west)   edge (\tikzlastnode.east)
          (\tikzlastnode.center) edge (\tikzlastnode.south)
          [every edge/.style=]   edge node[#5] {#1} (\tikzlastnode.north)
                                 edge node[#5] {#2} (\tikzlastnode.south west)
                                 edge node[#5] {#3} (\tikzlastnode.south east)
        }
        \pgfextra{\global\let\tikz@last@fig@name=\tikz@save@last@fig@name}
      \egroup}}}
\makeatother
\begin{document}
\begin{tikzpicture}
  \node[sectors={0}{1}{1}{1.0cm}{}] {}%
    child{
      node [sectors={1}{2}{3}{1.0cm}{font=\bfseries}] {}
    };
\end{tikzpicture}
\end{document}


text:
Q: error: package org.apache.commons.net.ntp does not exist I downloaded commons-net-3.0.1-bin.zip file and extracted it to java lib folder. I have set the path to java bin folder and classpath=.;C:\Program Files\Java\jdk1.7.0_01\lib\commons-net-3.0.1.
commons-net-3.0.1 folder has  commons-net-3.0.1 jar , commons-net-3.0.1-sources.jar  and  commons-net-examples-3.0.1.jar files.
In my program I imported org.apache.commons.net.ntp.* package, and it gave the "package doesn't exist" error.

A: Just adding the directory containing the JAR files isn't enough.  Add the specific JAR file to the classpath instead, e.g.

classpath=.;C:\Program Files\Java\jdk1.7.0_01\lib\commons-net-3.0.1\commons-net-3.0.1.jar

Alternatively, use a classpath wildcard to add all JARs in a given directory.  See How to use a wildcard in the classpath to add multiple jars?

A: *

*check that package org.apache.commons.net.ntp.* presents in jar file

*make sure that the jar file is in the class path of an application How to set Classpath


text:
Q: Custom font color for PagerTabStrip in ViewPager for my Android app I need to change the font color for PagerTabStrip in ViewPager for my Android app. This is the xml layout for the same. Is there any way I can do this?
<android.support.v4.view.ViewPager
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/head"
    android:id="@+id/myfivepanelpager">

        <android.support.v4.view.PagerTabStrip
         android:id="@+id/pgstrip"
        android:layout_width="fill_parent"
        android:background="@color/strip"
        android:layout_height="@dimen/pagerstripht"
        android:layout_gravity="top"
        />

    </android.support.v4.view.ViewPager>

A: in your code :
<android.support.v4.view.PagerTabStrip
         android:id="@+id/pgstrip"
        android:layout_width="fill_parent"
        android:background="@color/strip"
        android:layout_height="@dimen/pagerstripht"
        android:layout_gravity="top"
        />

I think adding android:textColor="#000" will change the text color.

A: If you haven't found out yet, code is below
PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pager_title_strip);
pagerTabStrip.setDrawFullUnderline(true);
pagerTabStrip.setTabIndicatorColor(Color.RED);

A: Get the child views of the PagerTabStrip and check if it is an instance of a TextView. If it is, set text color:
PagerTabStrip mPagerTabStrip = (PagerTabStrip) findViewById(R.id.pgstrip);
for (int i = 0; i < mPagerTabStrip.getChildCount(); ++i) {
    View nextChild = mPagerTabStrip.getChildAt(i);
    if (nextChild instanceof TextView) {
        TextView textViewToConvert = (TextView) nextChild;
        textViewToConvert.setTextColor(getResources().getColor(R.color.primary_text_color_dark_gray));
    }
}

A: Why don't you use:
pagerTabStrip.setTextColor(int color);


text:
Q: The arguments of a function gets called in different files The complete testing code shown in the following
The header file ( say, a.h ) defines the following codes:
typedef uint8_t EnrollT(uint16_t test1, uint16_t test2);
typedef void ChangeT(uint64_t post1, uint8_t post2);
struct ClusterT * ClientAlloc(EnrollT *, ChangeT *);

In one of my c ( say, test1.c) files which includes a.h shown below:
void Enroll(uint16_t test1, uint16_t test2){
     printf("Happy Enrolling");
}

void Change(uint64_t post1, uint8_t post2){
     printf("Happy Changing");
}

struct ClusterT * ClientAlloc(EnrollT *p, ChangeT *q)
{
    p = Enroll;
    q = Change;

    return something;
}

Above codes gets compiled okay, however, in the following code, I am a little bit confused in the another c file ( say, test2.c ) which includes a.h as well.
void priTest(){
    somethingOkay = ClientAlloc( ???? );
}

In this case, what arguments should I add in my ClientAlloc() function in test2.c ?

@dasblinkenlight
To be clear, I've modified the code as shown in the following:
In the header
typedef uint8_t EnrollT(uint16_t test1, uint16_t test2);
typedef void ChangeT(uint64_t post1, uint8_t post2);
struct ClusterT * ClientAlloc(EnrollT *, ChangeT *);

In test1.c
void Enroll(uint16_t test1, uint16_t test2){
     printf("Happy Enrolling");
}

void Change(uint64_t post1, uint8_t post2){
     printf("Happy Changing");
}

struct ClusterT * ClientAlloc(EnrollT *p, ChangeT *q)
{
    p = Enroll;
    q = Change;

    return something;
}

In test2.c
uint8_t Enroll(uint16_t test1, uint16_t test2);
void Change(uint64_t post1, uint8_t post2);

void priTest(){
    somethingOkay = ClientAlloc( Enroll, Change );
}

@Joachim Pileborg
I modifed my code as shown in the following, please let me know if I misunderstand what you mean in your reply.
In my header a.h
typedef uint8_t (*EnrollT)(uint16_t test1, uint16_t test2);
typedef void (*ChangeT)(uint64_t post1, uint8_t post2);
struct ClusterT * ClientAlloc(EnrollT *, ChangeT *);

In test1.c
void Enroll(uint16_t test1, uint16_t test2){
     printf("Happy Enrolling");
}

void Change(uint64_t post1, uint8_t post2){
     printf("Happy Changing");
}

struct ClusterT * ClientAlloc(EnrollT *p, ChangeT *q)
{
    *p = Enroll;
    *q = Change;

    return something;
}

In test2.c
EntrollT enroll;
ChangeT  change;

void priTest(){
    somethingOkay = ClientAlloc( &enroll, &change );
}

A: First of all, if you want e.g. EnrollT to be a pointer to a function, then you need to declare it as such:
typedef uint8_t (*EnrollT)(uint16_t test1, uint16_t test2);

Secondly, the functions definitions you use do not match the type-alias you create, so while it might build without errors, you still have problems in your code that should cause compiler warnings, and if you don't get warnings then you should enable more warnings when building. Warnings are often a sign of you doing something you should not do, that might lead to undefined behavior and possible crashes. And don't fix warnings by just some simple casting, try to find out the root cause of the warnings, and fix that instead.
Thirdly, and the problem you're asking about. If you make the change in the first paragraph, then it's simple:
EntrollT enroll;
ChangeT  change;

ClientAlloc(&enroll, &change);

However, that is the simple part, because you have to modify the ClientAlloc function too, to be able to handle the emulated pass by reference handling:
struct ClusterT * ClientAlloc(EnrollT *p, ChangeT *q)
{
    // Note use of dereference operator `*` here
    *p = Enroll;
    *q = Change;

    return something;
}

At least if you want to set p and q to the functions Enroll and Change, so you could call them from the code that called ClientAlloc. IF that's not what you want to do, but instead pass in functions pointer to be called by e.g. ClientAlloc then you need to make more modifications, like saving the pointer passed to the function instead of assigning to them.

If you want to pass in function pointer to be used by ClientAlloc instead, then you should not define the functions inside that source file, instead define them where they are supposed to be, in the source calling ClientAlloc, then you should have e.g.
Header file:
typedef uint8_t (*EnrollT)(uint16_t test1, uint16_t test2);
typedef void (*ChangeT)(uint64_t post1, uint8_t post2);

struct ClusterT * ClientAlloc(EnrollT, ChangeT);

Test1.c:
// Declare the function pointers
// (static so the won't be exported)
static EnrollT enroll;
static ChangeT change;

struct ClusterT * ClientAlloc(EnrollT e, ChangeT c)
{
    enroll = e;
    change = c;

    ...
}

And finally your test2.c:
uint8_t my_enroll_function(uint16_t test1, uint16_t test2)
{
    ...
}

void my_change_function(uint64_t post1, uint8_t post2)
{
    ...
}

int main(void)
{
    ClientAlloc(my_enroll_function, my_change_function);
}

A: You cannot use Enroll and Change to make an EnrollT and ChangeT function pointers, because they are incompatible. In order for the functions to match, they must have the same signatures as the functions declared in your typedefs:
uint8_t Enroll(uint16_t test1, uint16_t test2){
    printf("Happy Enrolling");
    return 0;
}
void Change(uint64_t post1, uint8_t post2){
     printf("Happy Changing");
}

Now you can pass these functions to ClientAlloc:
somethingOkay = ClientAlloc(Enroll, Change);

Since the call happens in a different file, you need to forward-declare your functions at the top of the file:
uint8_t Enroll(uint16_t test1, uint16_t test2);
void Change(uint64_t post1, uint8_t post2);


text:
Q: Problem installing rcov-0.8.1.2.0 on OS X I have a rails 3.0.7 application that is failing to load the development console.  I keep getting the error:
Could not find rcov-0.8.1.2.0 in any of the sources
Try running `bundle install`.

When I do, the it keeps failing to install that gem.  I get this error:
Installing rcov (0.8.1.2.0) with native extensions /opt/local/lib/ruby1.9/1.9.1/rubygems/installer.rb:483:in `rescue in block in build_extensions': ERROR: Failed to build gem native extension. (Gem::Installer::ExtensionBuildError)

/opt/local/bin/ruby extconf.rb
creating Makefile

make
/usr/bin/gcc-4.2 -I. -I/opt/local/include/ruby-1.9.1/x86_64-darwin10 -I/opt/local/include/ruby-1.9.1/ruby/backward -I/opt/local/include/ruby-1.9.1 -I. -I/opt/local/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE   -fno-common -pipe -O2 -arch x86_64 -fno-common  -o callsite.o -c callsite.c
callsite.c:2:17: error: env.h: No such file or directory
callsite.c:3:18: error: node.h: No such file or directory
In file included from callsite.c:4:
/opt/local/include/ruby-1.9.1/ruby/backward/st.h:2:2: warning: #warning use "ruby/st.h" instead of bare "st.h"
callsite.c: In function 'callsite_custom_backtrace':
callsite.c:82: error: 'ruby_frame' undeclared (first use in this function)
callsite.c:82: error: (Each undeclared identifier is reported only once
callsite.c:82: error: for each function it appears in.)
callsite.c:84: error: 'NODE' undeclared (first use in this function)
callsite.c:84: error: 'n' undeclared (first use in this function)
callsite.c:89: error: dereferencing pointer to incomplete type
callsite.c:90: error: dereferencing pointer to incomplete type
callsite.c:92: error: dereferencing pointer to incomplete type
callsite.c:92: error: dereferencing pointer to incomplete type
callsite.c:93: error: dereferencing pointer to incomplete type
callsite.c:93: error: dereferencing pointer to incomplete type
callsite.c:94: error: dereferencing pointer to incomplete type
callsite.c:96: error: dereferencing pointer to incomplete type
callsite.c:96: error: dereferencing pointer to incomplete type
callsite.c:101: error: dereferencing pointer to incomplete type
callsite.c: At top level:
callsite.c:121: error: expected ')' before 'event'
callsite.c: In function 'cov_install_callsite_hook':
callsite.c:161: error: 'coverage_event_callsite_hook' undeclared (first use in this function)
callsite.c:162: error: too few arguments to function 'rb_add_event_hook'
callsite.c: In function 'cov_remove_callsite_hook':
callsite.c:176: error: 'coverage_event_callsite_hook' undeclared (first use in this function)
make: *** [callsite.o] Error 1

Gem files will remain installed in /Users/johnmayer/.bundler/tmp/42427/gems/rcov-0.8.1.2.0 for inspection.
Results logged to /Users/johnmayer/.bundler/tmp/42427/gems/rcov-0.8.1.2.0/ext/rcovrt/gem_make.out
    from /opt/local/lib/ruby1.9/1.9.1/rubygems/installer.rb:486:in `block in build_extensions'
    from /opt/local/lib/ruby1.9/1.9.1/rubygems/installer.rb:446:in `each'
    from /opt/local/lib/ruby1.9/1.9.1/rubygems/installer.rb:446:in `build_extensions'
    from /opt/local/lib/ruby1.9/1.9.1/rubygems/installer.rb:198:in `install'
    from /opt/local/lib/ruby1.9/gems/1.9.1/gems/bundler-1.0.14/lib/bundler/source.rb:101:in `block in install'
    from /opt/local/lib/ruby1.9/gems/1.9.1/gems/bundler-1.0.14/lib/bundler/rubygems_integration.rb:78:in `preserve_paths'
    from /opt/local/lib/ruby1.9/gems/1.9.1/gems/bundler-1.0.14/lib/bundler/source.rb:91:in `install'
    from /opt/local/lib/ruby1.9/gems/1.9.1/gems/bundler-1.0.14/lib/bundler/installer.rb:58:in `block (2 levels) in run'
    from /opt/local/lib/ruby1.9/gems/1.9.1/gems/bundler-1.0.14/lib/bundler/rubygems_integration.rb:93:in `with_build_args'
    from /opt/local/lib/ruby1.9/gems/1.9.1/gems/bundler-1.0.14/lib/bundler/installer.rb:57:in `block in run'
    from /opt/local/lib/ruby1.9/gems/1.9.1/gems/bundler-1.0.14/lib/bundler/spec_set.rb:12:in `block in each'
    from /opt/local/lib/ruby1.9/gems/1.9.1/gems/bundler-1.0.14/lib/bundler/spec_set.rb:12:in `each'
    from /opt/local/lib/ruby1.9/gems/1.9.1/gems/bundler-1.0.14/lib/bundler/spec_set.rb:12:in `each'
    from /opt/local/lib/ruby1.9/gems/1.9.1/gems/bundler-1.0.14/lib/bundler/installer.rb:49:in `run'
    from /opt/local/lib/ruby1.9/gems/1.9.1/gems/bundler-1.0.14/lib/bundler/installer.rb:8:in `install'
    from /opt/local/lib/ruby1.9/gems/1.9.1/gems/bundler-1.0.14/lib/bundler/cli.rb:222:in `install'
    from /opt/local/lib/ruby1.9/gems/1.9.1/gems/bundler-1.0.14/lib/bundler/vendor/thor/task.rb:22:in `run'
    from /opt/local/lib/ruby1.9/gems/1.9.1/gems/bundler-1.0.14/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task'
    from /opt/local/lib/ruby1.9/gems/1.9.1/gems/bundler-1.0.14/lib/bundler/vendor/thor.rb:246:in `dispatch'
    from /opt/local/lib/ruby1.9/gems/1.9.1/gems/bundler-1.0.14/lib/bundler/vendor/thor/base.rb:389:in `start'
    from /opt/local/lib/ruby1.9/gems/1.9.1/gems/bundler-1.0.14/bin/bundle:13:in `<top (required)>'
    from /opt/local/bin/bundle:19:in `load'
    from /opt/local/bin/bundle:19:in `<main>'

Ruby:
ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10]

I am running rails 3.0.7, although rails -v fails with the same suggestion to install the gem.  I am on OS X 10.6.7.
Any help would be appreciated.


text:
Q: Spring MVC HelloWorld I'm trying to run my helloWorld program using Spring web mvc but there is a problem in my JSP file .. it can't read the value of "message" attribute added to ModelMap .. the jsp page opens normally but it displays the jsp EL as it is ${message} .. not the value of message !!
handler-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<context:component-scan base-package="com.shura" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

</beans>

HelloWorld.java
package com.shura;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/hello")
public class HelloWorld {
@RequestMapping(method=RequestMethod.GET)
public String printHello(ModelMap model){
    model.addAttribute("message", "Hello World");
    return("hello");
}

}
hello.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

Spring MVC Hello World Example

${message}

web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Archetype Created Web Application</display-name>

<servlet>
<servlet-name>handler</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>handler</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

A: Can you please change the version to 2.4 instead of 2.3 in the web.xml
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

Also please check the URL that you are using to access the web page:
http://{ip address or localhost}:{port}/{web app context}/hello/

A: Here problems with your jsp page tag
for instant solution use below jsp code without taglib
 <%@ page contentType="text/html; charset=UTF-8" %>

      <title>Hello World</title>

${message}

A: is(/hello) request going to controller? I am guessing that you are accessing the jsp page directly and is not going via controller. Also, Can you change either request mapping URL or JSP name and try?

A: As far as I remember, when returning from the method printHello we have to return an object which contains view information and model information also.
Although you are forming model but what I see is that you are not returning it.
You are only returning a string which is understood as a view name.
So, you need to return an object of ModelAndView.

A: try this,
public class HelloWorld {
@RequestMapping(method=RequestMethod.GET)
public String printHello(ModelMap model){
    model.addAttribute();
    return new ModelAndView("hello","message", "Hello World");
}

Hope this helps!!


text:
Q: Efficiency of Javascript functions Q1. I would like to confirm whether Version 1 of below code is more efficient than Version 2? I'd like to know for future reference so I will be writing codes according to the style of either V1 or V2.
Q2. How does one measure efficiency of the code? (Doesn't have to be in depth, I just want to have a rough idea)
Version 1:
function average(array) {
  return array.reduce(function(a,b) {    return a + b;  }) / array.length;
}

Version 2:
function average(array) {
  function plus(a,b) {    return a + b;  }
  return array.reduce(plus) / array.length;
}

Edit: assuming that at a later stage I would be writing much more complex code and I would like to get into the habit of writing efficient code now. I know that for simple one-liners there's no explicit difference.

A: These functions are equally efficient from a big-O perspective.  The reason they are the same, is that they both pass a function into reduce() (the way in which the function is declared is different, but it's the same underlying structure and thus the same efficiency). The functions are otherwise the same. If I were you, I'd opt for the second case as it is probably easier to maintain.
If you want, you can use a speed test, but honestly it's a waste of your time as these two approaches are identical.

A: With a sequential loop, it's far faster:
http://jsperf.com/anonymous-vs-named-function-passing/2
function average3(array) {
      var sum =0;
      for( var i=0, len=array.length; i< len; i++ )
        sum+=array[i];
      return sum/array.length;
    }

A: You will have the same result. Or difference will be negligible. Depends on JS engine and how good its optimizer is.
As others suggested you can use jsperf.com for speed tests.
But if you really care about performance then check third case here
http://jsperf.com/anonymous-vs-named-function-passing/3

A: They are the same... but you could optimize by avoiding to create a new closure of the sum function.
function sum(a,b){
    return a+b;
}

function average(array){
    return array.reduce(sum) / array.length;
}

This way sum won't hold a reference to array in its context; and a new instance of sum with the context won't be necessary. Remember that a closure will hold a reference of the arguments of the function that contains it even if you don't use those arguments.
This means that a new function sum won't be instantiated every time that you call average.


text:
Q: How to draw a circle and fills outside border with color I was wondering if it's possible to achieve that in CSS 2/3 (or if not possible, in JS).
In fact my wish is instead of having this as an image, is to set the percent of filled color with a class (or in js if it's not possible)

Any tutorial/help is appreciated.
Thanks.

A: You can't achieve this result with css. You have to use a canvas element and a javascript framework like http://paperjs.org/

A: You can also do this with SVG. Define a gradient, then draw an arc, and fill it with the gradient. You can also specify inline markers on your path.

A: Set border-width to 1000px. This trick worked for me.


text:
Q: How to Put method using xUnit I try to test Update method using xUnit and I don't know how to do it, below is my code:
Put method in controller:
[HttpPut]
[Route("{id}")]
public IActionResult Put([FromBody]BookDto book, [FromRoute]int id)
{
    if (!ModelState.IsValid)
    {
        return BadRequest();
    }
    var isUpdated = _service.Update(book);
    if (!isUpdated)
    {
        return NotFound();
    }
    return Ok();
}

BookService update method:
public bool Update(BookDto book)
{
    var bookDb = _context.Books.FirstOrDefault(x => x.Id == book.Id);
    if(bookDb == null)
    {
        return false;
    }
    bookDb.Title = book.Title;
    _context.SaveChanges();
    var existingAuthors = _context.Book_Authors.Where(x => x.BookId == book.Id).ToList();
    _context.Book_Authors.RemoveRange(existingAuthors);
    _context.SaveChanges();

    foreach (var AuthorsId in book.AuthorsId)
    {
        var newBookAuthors = new Book_Author()
        {
            BookId = book.Id,
            AuthorId = AuthorsId
        };
        _context.Book_Authors.Add(newBookAuthors);
    }
    _context.SaveChanges();

    return true;
}

BookDto:
public class BookDto
{
    public int Id { get; set; }
    public string Title { get; set; }
    public List<int> AuthorsId { get; set; }
}

Any suggestions how to write PutMethod test using Moq?

A: *

*I would suggest to collect the test cases:

*

*Given an invalid book When I call put Then It returns bad request

*Given a non-existing book When I call put Then It returns not Found

*Given an existing book When I call put Then It returns ok

*I would suggest to AAA pattern for each test case, for example:

*

*Arrange: Setup a book service mock which returns false whenever someone calls the update

*Act: Call your controller's put method

*Assert: Verify that the returned result is not found as expected

*Try to codify. For example
public void GivenANonExistingBook_WhenICallPut_ThenItReturnsNotFound()
{
    //Arrange
    var book = ...;
    var serviceMock = new Mock<IBookService>();
    serviceMock.Setup(svc => svc.Update(It.IsAny<BookDto>()))
               .Returns(false);

    var sut = new YourController(serviceMock.Object);

    //Act
    var result = sut.Put(book, 0);

    //Assert
    var actionResult = result as NotFoundResult;
    Assert.IsNotNull(actionResult);
}

It is also a good practice to verify that the Update method of the service has been called only once with the book variable: serviceMock.Verify(svc => svc.Update(book), Times.Once);.


text:
Q: Jquery .length keeps returning 0 I'm trying to count the section tags on a page but whenever this script runs it returns a 0. Any ideas?
    var sectionCount = $( "section").length;
    console.log(sectionCount);

The HTML I'm counting from is as follows:

1

2

3

A: Just add a $(document).ready() clause so that it runs after the html DOM has been loaded.

$( document ).ready(function() {
  var sectionCount = $( "section").length;
  console.log(sectionCount);
 });

1

2

3


text:
Q: appdomain close console without kill main process hi i need direction how to close appdomain console application without kill main process?
i create appdomain like this.
AppDomain testApp = AppDomain.CreateDomain("testApp");
try
{
    string[] args = new string[] { };
    string path = ConfigurationManager.AppSettings.Get("testApp");

    testApp.ExecuteAssembly(path, new System.Security.Policy.Evidence(), args);
}
catch (Exception ex)
{
    //Catch process here
}
finally
{
    AppDomain.Unload(testApp);
}

"testApp" was console application, and when I close that console, main application that call AppDomain closing.
*Edit
I execute code above on main application, let's say "MyApplication". When code above executed, its runs "testApp" and console windows show up. My problem is when i close "testApp" console windows, "MyApplication" process is closing.

A: It could be that the assembly your AppDomain is calling is ending prematurely (Environment.Exit(1), etc.).
What you can do is to subscribe to the AppDomain's event -- ProcessExit.
namespace _17036954
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain testApp = AppDomain.CreateDomain("testApp");
            try
            {
                args = new string[] { };
                string path = ConfigurationManager.AppSettings.Get("testApp");

                //subscribe to ProcessExit before executing the assembly
                testApp.ProcessExit += (sender, e) =>
                {
                    //do nothing or do anything
                    Console.WriteLine("The appdomain ended");
                    Console.WriteLine("Press any key to end this program");
                    Console.ReadKey();
                };

                testApp.ExecuteAssembly(path);
            }
            catch (Exception ex)
            {
                //Catch process here
            }
            finally
            {
                AppDomain.Unload(testApp);
            }
        }
    }
}


text:
Q: how to call API post method in karma unit testing and get response from it in angular 4 I am trying to write karma unit test cases in angular 4 to get response from post method. I required data coming from API to write further test cases. My sample code snippet is as follows it run but I am not able to get response.
spec.ts
  describe('Login service : ', () => {
  let component: LoginComponent;
  let fixture: ComponentFixture<LoginComponent>;

  beforeEach(async(() => {
  TestBed.configureTestingModule({
  imports: [
    HttpClientModule,
    HttpClientTestingModule
  ]
  })
  .compileComponents();
  }));

afterEach(inject([HttpTestingController], (backend: HttpTestingController) => {
backend.verify();
}));

 beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();

debugElement = fixture.debugElement.query(By.css('#userName'));
htmlElement = debugElement.nativeElement;

 });

  it(`should emit 'true' for 200 Ok status `, async(inject([LoginService, HttpTestingController],
(service: LoginService, backend: HttpTestingController) => {
  service.login({ userName: 'CF09221601k', password: 'LK6XOMPBRkH0', BrowserInfo: 'chrome 46.0.2490.86' }).subscribe((next) => {
    expect(next).toBeTruthy();
  });
  backend.expectOne('api/ValidateClientLogin').flush(null,
    { status: 200, statusText: 'Ok' });
})));

loginService.ts
export class LoginService {

constructor(private httpClient: HttpClient) { }

public login(user) {
    return this.httpClient.post(APPCONFIG.WEBSERVICE_URL + APIURL.ValidateClientLogin, user, {observe: 'response'});
}
}


text:
Q: Given a number field $K$, is there a number field $L$ containing $K$ such that all prime ideals of $K$ are unramified in $L$? We know that there is no nontrivial extension $L$ of $K=\mathbb{Q}$ such that all the primes of $K$ are unramified in $L$ (The discriminant $\delta_L>1$).
Suppose that $\mathbb{Q}\subsetneq K$. Can we find an extension $L$ of $K$ such that all primes of $K$ are unramified in $L$ ?


text:
Q: Panic Runtime Error index out of range [3] with length 3 Facing an error Panic Runtime Error index out of range [3] with length 3. The below error seems to indicate the index is out of range or length
panic: runtime error: index out of range [3] with length 3
main.romanToInt(0xc000022080, 0x3, 0x8)
solution.go, line 15
main.__helper__(...)
solution.go, line 30
main.main()
solution.go, line 58

func romanToInt(s string) int {
    romanNum := map[byte]int{
        'I': 1,
        'V': 5,
        'X': 10,
        'L': 50,
        'C': 100,
        'D': 500,
        'M': 1000,
    }

    var sum int = 0
    for i := 0; i <= len(s); i++ {
        currentInt := romanNum[s[i]]
        nextInt := romanNum[s[i+1]]
        if currentInt < nextInt {
            sum = sum + (nextInt - currentInt)
            i += 1
        } else {
            sum = sum + currentInt
        }
    }
    return sum
}

Error pointing to
nextInt := romanNum[s[i+1]]

A: For i=len(s)-1, the expression s[i+1] accesses the index s[len(s)], which is invalid. The index you are accessing does not exist. Even if you fix it,  your loop range includes len(s), so next time around s[i] will be out of range.

A: Let's say that you pass the string XII to your function. That makes len(s) 3, which means that the body of your loop would (if the panic didn't occur) execute 4 times (when i is 0, 1, 2 and 3 since your condition is i <= len(s).
On the iteration where i is 2 (i.e. it refers to the second I in XII, the last character), when the line
nextInt := romanNum[s[i+1]]

attempts to access the next character (i+1 will be 3) then it will be out of bounds. Remember, slices/arrays are 0 indexed. This is the reason for the panic.
It's also worth nothing that if the panic did not occur when i was 2, then it would certainly occur during the next iteration where i is 3, since 3 is out of bounds for s, on the following line:
currentInt := romanNum[s[i]]

To fix the issue, you need to reconsider how you approach the condition of the loop. Using <= here is likely to cause you a problem. Also, within the body of the loop, you need to consider that when you're looking at the last character in the string, there is not a next character, but your code just assumes that there is. Addressing both of these problems should help you overcome the issue.


text:
Q: NoSuchMethodError : google common ImmutableSet.copyOf(..) I upgraded my Google app Engine app from 1.7. to 1.8. + Java 7 and i leveled up all API libraries to be up-to-date. I am getting strange exceptions during app inicialization in GAE container :
Constructor threw exception; nested exception is java.lang.NoSuchMethodError:
java.lang.NoClassDefFoundError: Could not initialize class com.google.gdata.client.contacts.ContactsService
.
 and this exception follows :
.
java.lang.NoSuchMethodError: com.google.common.collect.ImmutableSet.copyOf([Ljava/lang/Object;)Lcom/google/common/collect/ImmutableSet;:
.
.
com.google.apphosting.runtime.jetty.AppVersionHandlerMap.createHandler(AppVersionHandlerMap.java:219)

"suspicious" Libraries :

*

*guava 11.0.2 (because it`s dependency for actual gdata project 1.47.1)

*gdata-contacts-3.0.jar

*gdata-contacts-meta-3.0.jar

*gdata-core-1.0.jar

*gdata-client-1.0.jar

*gdata-base-1.0.jar

*http client librares version : 1.14.1

*(and bunch of others nonrelated to this issue)
Even without guava library there`s the same error. What causes this incompatibility ? I did not found newer version of gdata-contact API (1.47.1). Any ideas ?

A: i removed latest guava library and used some rc05 version which works fine.


text:
Q: Why does a linux compiled program not work on Windows I am almost sure my problem is due to the fact that the compiled program is compiled as a linux executable, but I just want to double check this.
#include <stdio.h>
#include <stdlib.h>
int main()
{
    printf("Hello world!\n");
    return EXIT_SUCCESS;
}

The above "program" should compile on Windows and Linux just fine, since it is source code compatible, as there are no operating system specific libraries or anything like that.
Yet, when I type in "c99 hello.c -o hello.exe" on my Linux box, and then transfer that "executable" to a windows machine, it refuses to run. From what I understand, Linux generates an executable file that only runs on linux, so adding ".exe" has no effect. To build that program on Linux for Windows, I would need to recompile that program on a Windows machine?
Or is there another simpler method that will work?

A: Windows and Linux executable files use two different incompatible formats:
On Windows, it is the Portable Executable format.
On Linux it is the ELF (Executable and Linkable Format).
Each format makes uses of the specificities of the OS they are supposed to run on, so they can't normally be executed on another platform.
Also, an executable only contains a small portion of the code that is executed after it is loaded into memory. An executable file is linked to system libraries that provide most of the functionality that allows the program to interact with the system.
As systems are very different from each other, libraries vary, and a program for say, Linux, cannot be run on FreeBSD despite the latter using also ELF, because they are not linked to the same libraries.
To compile a Windows executable on Linux, a technique known as cross-compilation can be used.
A compiler is after all just a program that writes into a binary file, so any compiler can in theory write code for any platform, as long as the target system's libraries are available to be linked against.
The MinGW-w64 project provides a toolchain that allows this.
For example, you can install it on debian-based systems using the sudo apt-get install mingw-w64 command.
The installed executables can be used like this:
i686-w64-mingw32-gcc hello.c -o hello32.exe      # 32-bit
x86_64-w64-mingw32-gcc hello.c -o hello64.exe    # 64-bit

A: Its a compilation situation, diferently from java .exe don't have any virtual machine to interpret the code in diferent OS. Then he needs to have all specific .dll's and lib's from OS to execute the job who is made for.
In .exe all things are made to run on a specific OS, other way in Java a virtual machine is the magic who interpret and run your code on diferents OS.


text:
Q: How to use path-to-regexp (and react-router-4) to match all paths that's not starting with /auth? I can't figure out how to use react-router-4 (and so path-to-regex) to match all path tha's not starting with /auth
<Switch>
    <Route path="/^(?!\/?auth).+$/"  component={AppWelcome} />
    <Route path="/auth"  component={AppAuth} />
    <Route component={NoMatch} />
</Switch

With /^(?!\/?auth).+$/ i get this error


text:
Q: Query to verify anti-cheat system I have a table that basically collects votes for a specific user:
ID | user_id | ip | timestamp

Every time someone votes for a user, an entry is created logging the user_id they voted for, their IP address and the time and date.
To prevent cheating we don't allow more than 20 votes per user per IP per day.
Now I'd like to verify these votes, starting from a given date and I've come up with the following query myself but I'm by no means an expert so if anyone could tell me if I have this correct I would greatly appreciate it.
SELECT count(*) As `votes`, user_id, ip, DATE( timestamp ) the_date
FROM `user_votes`
GROUP BY user_id, ip, the_date
HAVING the_date > '2012-07-26'
ORDER BY the_date ASC, user_id ASC, votes DESC

A: try this:
SELECT count(*) As `votes`, user_id, ip, DATE( timestamp ) the_date
FROM `user_votes`
where the_date > '2012-07-26'
GROUP BY user_id, ip, DATE( timestamp )
having count(*)>20
ORDER BY DATE( timestamp ) ASC, user_id ASC, votes DESC

having count(*)>20 will give you counts more than 20

A: To get users having valid number of votes you can try this:
SELECT COUNT(*) As `votes`, user_id, ip, DATE( timestamp ) the_date
FROM `user_votes`
WHERE DATE(timestamp ) > '2012-07-26'
GROUP BY user_id, ip, the_date
HAVING COUNT(*) <= 20
ORDER BY the_date ASC, user_id ASC, votes DESC;


text:
Q: Dynamic children navigation in React.js (propagating events and properties) One thing I'm still struggling with in React.js is the proper way to handle child event and property propagation. There are many examples of this being done already, but the implementations are always vastly different. Surely, there is a "right way" to do it...
The task is to create a "Nav" component which is made up of "NavItem" components. Below is the code that I am expecting to work, but it doesn't. The comments explain where I'm having issues. Please advise on the best solution and let me know what I'm doing wrong.
Nav.jsx
var Nav = React.createClass({
    propTypes: {
        active:         React.PropTypes.string,
        onSelect:       React.PropTypes.func
    },
    getInitialState: function () {
        return {
            active: this.props.active
        };
    },
    render: function () {
        return this.transferPropsTo(

                {this.props.children.map(this.renderChild)}

        );
    },
    renderChild: function (child, i) {
        // Here I want to generate a unique 'key' property for each child as well
        // as define a custom onSelect method which will tell the "Nav" component which is
        // the active key.
        return React.addons.cloneWithProps(child, {
            // Here I want to use the 'active' property of the Nav component to drive the
            // the 'active' property of the child.
            active: this.state.active === i ? true, false,
            key: i,
            onSelect: this.handleSelect
        });
    },
    handleSelect: function (event, component) {
        // PROBLEM: Here I want to get the 'key' property of the child. But there seems to be
        // no way to do this.
        var _child_key_ = 'impossible';
        this.setState({active: _child_key_});
    }
});

NavItem.jsx
var NavItem = React.createClass({
    propTypes: {
        active:     React.PropTypes.string,
        onSelect:   React.PropTypes.func
    },
    getInitialState: function () {
        return {
            active: this.props.active
        };
    },
    render: function () {
        return this.transferPropsTo(

                {this.props.label}

        );
    },
    handleSelect: function (event, component) {
        // Propagate the event up to the parent event property.
        if (this.props.handleSelect) this.props.handleSelect(event, component);
    }
});

MyApp.jsx
var App = React.createClass({
    render: function () {
        return (

                <NavItem label="Home" />
                <NavItem label="Page1" />
                <NavItem label="Page2" />

        );
    }
});

React.renderComponent(new App(), document.body)

A: I believe this is the most sane way.
var Nav = React.createClass({
    propTypes: {
        active:         React.PropTypes.string,
        onSelect:       React.PropTypes.func
    },

    // no state
    //getInitialState: function () {},

    render: function () {
        // use React.Children.map because children is opaque
        return this.transferPropsTo(

                {React.Children.map(this.props.children, this.renderChild)}

        );
    },
    renderChild: function (child, i) {
        return React.addons.cloneWithProps(child, {
            // use the prop, not state
            active: this.props.active === i,
            key: i,

            // let the parent decide how to handle the data change
            // give it the clicked index
            onSelect: this.props.onSelect.bind(null, i)
        });
    }
});

var NavItem = React.createClass({
    propTypes: {
        // it's a boolean
        active:     React.PropTypes.bool,
        onSelect:   React.PropTypes.func
    },
    // again, no state
    //getInitialState: function () {},

    render: function () {
        // just pass the onSelect handler in directly
        // let the parent handle it
        return this.transferPropsTo(

                {this.props.label}

        );
    }
});

var App = React.createClass({
    getInitialState: function(){ return {active: 0} },

    handleSelect: function(i){ this.setState({active: i}) },

    render: function () {
        return (

                <NavItem label="Home" />
                <NavItem label="Page1" />
                <NavItem label="Page2" />

        );
    }
});


text:
Q: Laravel 4 using php to create dynamic blade commands I have this blade view template
<title><?
$page = App::make('page');
echo $page->getTitle( );
?></title>
<?php
$css = $page->getCssList('all');

foreach($css as $item){?>
    {{ HTML::style('<?=$item['loc'];?>', array('media' => '<?=$item['media'];?>'))}}
<?}

$js = $page->getJsList('all');
foreach($js as $item){?>
    {{ HTML::script('<?=$item['loc'];?>')}}
<?}?>

It does not work. What happens is it actually outputs the blade commands to the screen.
If i cut and paste these blade command into the view then they are rendered correctly.
What is the problem? Is is not possible to create dynamic blade commands? How can I solve this problem?

A: You are using PHP inside of PHP.
Change this
{{ HTML::script('<?=$item['loc'];?>')}}

to this
{{ HTML::script($item['loc']) }}

and change
{{ HTML::style('<?=$item['loc'];?>', array('media' => '<?=$item['media'];?>'))}}

to
{{ HTML::style($item['loc'], array('media' => $item['media'])) }}

A: The curly braces are simply a shortcut for printing PHP code.
You can just write
{{ HTML::script($item['loc']) }}

Which is functionally identical to
<?php echo HTML::script($item['loc']); ?>


text:
Q: use async write log in asp.net mvc I want  async write   log in asp.net mvc,the code is like this:
public ActionResult Index()
        {
            byte[] buffer = Encoding.UTF8.GetBytes(string.Format("log:{0}{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff"), Environment.NewLine));
            FileStream fs = new FileStream(@"c:\log.txt", FileMode.Append, FileAccess.Write, FileShare.Write, 1024, true);
            fs.BeginWrite(buffer, 0, buffer.Length, ar =>
              {
                  fs.EndWrite(ar);
                  fs.Close();
              }, null);
         }

But the result is not I expected, some log not be recorded,can anyone tell me what's wrong with the code

A: You need to ensure that only one thread is writing to the file. If you have 2 concurrent users calling the Index action at the same time chances are they will try to write to the log file at the same time and the second will fail. In a multithreaded applications such as ASP.NET always make sure that you are properly synchronizing access to shared resources.
Also in your code you are not guarding against errors. What if an exception is thrown? You never close this stream and the second attempt to access it will throw an exception.
So one possibility to simplify this code is to use the TPL:
private static object _synRoot = new object();

public ActionResult Index()
{
    Task.Factory.StartNew(() =>
    {
        lock (_synRoot)
        {
            var data = string.Format("log:{0}{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff"), Environment.NewLine)
            System.IO.File.AppendAllText("log.txt", data);
        }
    });
    return View();
}

and to avoid such noise and pollution in your controllers you could use action filters:
public class LogAttribute : ActionFilterAttribute
{
    private static object _synRoot = new object();

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        Task.Factory.StartNew(() =>
        {
            lock (_synRoot)
            {
                var data = string.Format("log:{0}{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff"), Environment.NewLine)
                System.IO.File.AppendAllText(@"log.txt", data);
            }
        });
    }
}

and then:
[Log]
public ActionResult Index()
{
    return View();
}

But instead of reinventing wheels I would recommend you using the tracing capabilities built into the .NET framework.


text:
Q: Serving static files Go seems inefficient..or maybe its just me :-) Over months I've read tons of articles about Go and best practices.  Among those articles are numerous google searches and SOF searches regarding how to and the best way to serve static files.
This is what I currently have
fs := http.FileServer(http.Dir("static/"))
myRouter.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))

myRouter.PathPrefix("/admin/static/").Handler(http.StripPrefix("/admin/static/", fs))
myRouter.PathPrefix("/admin/accounts/static/").Handler(http.StripPrefix("/admin/accounts/static/", fs))
myRouter.PathPrefix("/admin/admin_tools/static/").Handler(http.StripPrefix("/admin/admin_tools/static/", fs))
myRouter.PathPrefix("/admin/audit_tools/static/").Handler(http.StripPrefix("/admin/audit_tools/static/", fs))
myRouter.PathPrefix("/admin/demand/static/").Handler(http.StripPrefix("/admin/demand/static/", fs))
myRouter.PathPrefix("/admin/optimization/static/").Handler(http.StripPrefix("/admin/optimization/static/", fs))
myRouter.PathPrefix("/admin/reports/static/").Handler(http.StripPrefix("/admin/reports/static/", fs))
myRouter.PathPrefix("/admin/setups/static/").Handler(http.StripPrefix("/admin/setups/static/", fs))
myRouter.PathPrefix("/admin/queue/static/").Handler(http.StripPrefix("/admin/queue/static/", fs))
myRouter.PathPrefix("/admin/tagservers/static/").Handler(http.StripPrefix("/admin/tagservers/static/", fs))
myRouter.PathPrefix("/admin/client/static/").Handler(http.StripPrefix("/admin/client/static/", fs))
myRouter.PathPrefix("/client/static/").Handler(http.StripPrefix("/client/static/", fs))

My issue with this is that for every path I have to add a new line to cover where the static files come from.  Most examples show how it's done when you have a single landing page with no real navigations built into it. Coming from a Python background I suppose I was bit spoiled with some of the lightweight frameworks, such as Flask and Tornado, where one just points to the static folder once.
Another issue with this current setup is it doesn't play nice with NGINX.  Again with frameworks like Flask and Tornado, all you have to do in NGINX is set the static location once.  With Go I have to set the static location just like the code above (by defining each path).
Has anyone found a better way to serve static files?  I know in theory a function could probably be written to automate it, but it wouldn't really change the fact that each path has to be accounted for on the app level and NGINX level.
UPDATE: In reply to @mkopriva I've attached two screenshots.  The first is of the browser running the app with dev tools open to show the 404s on the static files. The Second is of the server code, to produce those errors all I did was comment out one line.  The line that handles the audit_tools path. If I uncomment it everything routes no problem.

Edit, both @mkopriva and @sberry did a great job. I wish I could pick two correct answers.

A: If you are using nginx to do this work then you don't need Go to do it too (unless you want to be able to run standalone without nginx).  If that is the case then you can use a Path call instead of PathPrefix so you can do pattern matching.
If you are just trying to do this via nginx then something like this should work:
server {
    listen 8080;

    location ~* ^/static/ {
        root /path/to/directory/containing_static;
    }

    location  ~* ^.*/static/(.*)$ {
        rewrite "^.*/static/(.*)$" /static/$1 last;
    }

    location @forward_to_app {
       # send to your go app here
    }

  }

You can probably do without the rewrite, but that was an easy approach to take.

A: All those PathPrefix and StripPrefix calls seem to me to be functionally pointless. If your static directory is inside your Go project and its structure looks something like this:
.
├── main.go
└── static
    ├── admin
    │   ├── accounts
    │   │   └── file.txt
    │   ├── file.txt
    │   └── reports
    │       └── file.txt
    └── file.txt

then to serve files from that static directory with Go, all you should really need is this.
package main

import (
    "log"
    "net/http"
)

func main() {
    fs := http.FileServer(http.Dir("static/"))
    http.Handle("/", fs)

    log.Fatal(http.ListenAndServe(":8080", nil))
}


text:
Q: Network/Graph Analysis Beginner Resources I am a beginner to Network/Graph Analysis. I have data in the following format:
Customer | CustomerSpend
Anna                    $10
Bob                     $30
Charlie                 $50
...
...
Customer1 | Customer2 | RelationshipStrength | Location
Anna          Bob            5                      NY
Bob           Charlie        10                     TX
...
...

*

*I want to visualize and conduct some analysis on the data set (which groups spend most, which locations spend most, etc.).

*I am thinking of using NodeXL or igraph (in R) to get started.

*I also want to brush up on graph theory to understand the various metrics I could look at.

What resources can I leverage to get started?


text:
Q: Python 3.6, utf-8 to unicode conversion, string with double backslashes There are many questions about utf-8 > unicode conversion, but I still haven't found answer for my issue.
Lets have strings like this:
a = "Je-li pro za\\xc5\\x99azov\\xc3\\xa1n\\xc3\\xad"

Python 3.6 understands this string like Je-li pro za\xc5\x99azov\xc3\xa1n\xc3\xad. I need to convert this utf-8-like string to unicode representation. The final result should be Je-li pro zařazování.
With a.decode("utf-8") I get AttributeError: 'str' object has no attribute 'decode', because Python means the object is already decoded.
If I convert it to bytes first with bytes(a, "utf-8"), the backslashes are doubled only and .decode("utf-8") returns it to my current a again.
How to get unicode string Je-li pro zařazování from this a?

A: You have to encode/decode 4 times to get the desired result:
print(
  "Je-li pro za\\xc5\\x99azov\\xc3\\xa1n\\xc3\\xad"

  # actually any encoding support printable ASCII would work, for example utf-8
  .encode('ascii')

  # unescape the string
  # source: https://stackoverflow.com/a/1885197
  .decode('unicode-escape')

  # latin-1 also works, see https://stackoverflow.com/q/7048745
  .encode('iso-8859-1')

  # finally
  .decode('utf-8')
)

Try it online!
Besides, consider telling your target program (data source) to give different output format (byte array or base64 encoded, for example), if you can.
The unsafe-but-shorter way:
st = "Je-li pro za\\xc5\\x99azov\\xc3\\xa1n\\xc3\\xad"
print(eval("b'"+st+"'").decode('utf-8'))

Try it online!
There are ast.literal_eval, but it may not worth using here.


text:
Q: Inserindo caracter especial no view Tenho uma table HTML onde uma de suas td preciso inserir a seguinte informação:
@item.OrderSend º

Queria inserir desta forma:
@item.OrderSendº

Porém ao juntar o carácter º com a variável OrderSendº o compilador entende que o º faz parte do nome da variável
Como eu posso juntar esse carácter com o valor da variável?
A variável retorna valores inteiros, por exemplo 1, 2, 3.
A saída na view deveria ser: 1º, mas esta saindo assim: 1 º

A: Use item.OrderSend dentro de parênteses, assim o razor vai entender que o símbolo "º" não faz parte do nome da variável.
@(item.OrderSend)º

A: Outra forma de fazer é usando string.Concat, para concatenar as strings.
@string.Concat(item.OrderSend, "º")


text:
Q: Can I nest CodeIgniter "Helpers" in sub directories? I know I can nest libraries in subfolders, but can I do the same for Helpers?
The end result would be to have something to the effect of:
application/helpers/foo/bar_helper.php
application/helpers/baz_helper.php

Then call the helpers with:
$this->load->helper('foo/bar');
$this->load->helper('baz');

A: Yes you can store and load as follows (tested)
$this->load->helper('myHelperSubFolder/myHelperName');

Even in your autoload.php you can load a helper as follows
$autoload['helper'] = array('url','myHelpers/functions_helper'); // 'myHelpers' is the folder inside my helper folder and 'functions_helper' is my helper file.


text:
Q: "custom agents" vs. "customs agents" Does one write "custom agents" or "customs agents"? I saw both:

*

*Wikipedia: "US and Canadian custom agents".

*gov.uk: "Search the register of customs agents and fast parcel operators".

A: It is normally called "customs" (e.g., "U.S. Customs and Border Protection"), so the plural is better. Also, "custom" could be confused with the adjective "custom", which has a very different meaning. Google Books ngrams confirms that the plural is usual.


text:
Q: Manually plotting significance relations between sub-groups on ggplot2 barplot I've been trying to plot manually labelled significance bars for a subset of groups on a ggplot2 barplot using ggsignif or ggpubr without much luck. The data is something like the following MWE:
set.seed(3)
## create data
df <- data.frame(activity = rep(c("Flying", "Jumping"), 3),
                 mean = rep(rnorm(6, 50, 25)),
                 group = c(rep("Ecuador", 2),
                           rep("Peru", 2),
                           rep("Brazil", 2)))
## plot it
ggplot(df, aes(x = activity, y = mean, fill = group)) +
    geom_bar(position = position_dodge(0.9), stat = "identity",
             width = 0.9, colour = "black", size = 0.1) +
    xlab("Activity") + ylab("Mean")

Where I'd like to manually specify significance labels, say between Brazil/Ecuador" on "Flying", and Ecuador/Peru on "Jumping". Does anyone know how to properly deal with this kind of data, for example with ggsignif? And is there a way to refer to each bar by name, rather than try to work out its x-axis position?

A: If you know on which barchart you want to add your significance labels, you can do:
library(ggsignif)
library(ggplot2)

ggplot(df, aes(x = activity, y = mean, fill = group)) +
  geom_bar(position = position_dodge(0.9), stat = "identity",
           width = 0.9, colour = "black", size = 0.1) +
  xlab("Activity") + ylab("Mean")+
  geom_signif(y_position = c(60,50), xmin = c(0.7,2), xmax = c(1,2.3),
              annotation=c("**", "***"), tip_length=0)

Does it answer your question ?


text:
Q: Javascript: CreateElement putting onClick function on other element I'm trying to make a script that creates a button with an onclick function; but when I make the code and run it, the onclick function that should be added to the newly created button gets placed onto the button I used to create the new button with. (The idea is that the first button in the end gets replaced with a document.load function but currently this is easier for testing to make sure it shows up where I want it.)
I'm a bit stuck as to why it places the "hideElement" function on the wrong button.
The current code is have:

function makeButton(){
  var newB = document.createElement('button');
  newB.innerHTML = 'Hide';
  newB.onclick = hideElement();

  var y = document.getElementsByClassName("element")[0];

  y.insertAdjacentElement('afterend', newB);
}

function hideElement(){
  var y = document.getElementsByClassName("element")[0];

  if (y.style.display === "none") {
    y.style.display = "block";
  } else {
    y.style.display = "none";
  }
}

Blablabla

<button onclick=makeButton();>Create</button>

Thanks in advance for helping my tiny brain comprehend this issue.