Q:

NHibernate: trying to save collection of children of the same object type fails

I have a class that has a one-to-many relationship within itself, when trying to save a collection of children, only the first child is being saved, here is my mapping:
 <class name="AMU" table="AMU">
        <id name="ID" column="ID">
          <generator class="identity"/>
        </id>

        <many-to-one name="_Manager" class="AMU" column="ParentID" access="field"/>
        <many-to-one name="User" column="UserID"/>
        <many-to-one name="MCT" column="MctID"/>
        <set name="ManagedAMUs" fetch="select" cascade="all-delete-orphan" inverse="false">
          <key column="ParentID"/>
          <one-to-many class="AMU"/>
        </set>
      </class>

here is the class definition:
public class AMU : TABS.Components.BaseEntity
    {
        public AMU()
        {
            this.User = null;
            this.Manager = null;
            this.ManagedAMUs = new List<AMU>();
        }

        public virtual int ID { get; set; }
        public virtual User User { get; set; }
        private AMU _Manager;
        public virtual AMU Manager
        {
            get { return _Manager; }
            set { _Manager = value; }
        }
        public virtual ICollection<AMU> ManagedAMUs { get; set; }
public virtual MCT MCT { get; set; }
}

when I use a for loop to add several AMUs to a parent AMU

foreach(var amu in AMUList)
{
    myAMU.ManagedAMUs.Add(amu);
}

and then saving the parent AMU, it only saves one child

A:

The issue is related to the fact, that NHiberante <set> (in comparison with <bag>) is representing a collection of unique records. How to fix it? There are two, very different ways:

change the mapping from <set> to <bag>
implement the bool Equals(object obj) and int GetHashCode() in the AMU class

The first solution, is in fact saying: collection could contain one same item many times.
The second solution is about handling the word same. How to check if the objects are the same? well from perspective of the <set> the methods GetHashCode() and Equals() are called.
In this case we need to distinguish child objects (becuase of hierarchical nature, the parent as well). It should

not be based on the surrogated key (ID) but
e.g. on properties like Code or Name... or combination. Or in the example above on the User.ID

NOTE: By the way, even if we change <set> to be a <bag>, our mapped entities should override these methods. It is simply a good practice.


Q:

Javascript Canvas how to shoot in 360* from a rotating object

All my searching comes up with more general arc/sin/cos usage or shooting to the mouse position.
I am looking to aim and fire a projectile with the keyboard and have done a lot of it from scratch, as a noob in a web class doing a project, but I am stuck on this. My current math got me to this mess in firing the shot in the direction the line is currently pointing... (code names cleaned for readability):
this.x = x + len * Math.cos(angle);
this.y = y + len * Math.sin(angle);
this.xmov = -((x + len * Math.cos(angle)) - x) / ((y + len * Math.sin(angle)) - y);
this.ymov = ((y + len * Math.sin(angle)) - y) / ((x + len * Math.cos(angle)) - x);

if (Math.abs(this.xmov) > Math.abs(this.ymov)) {
    this.xmove = (this.xmov * Math.abs(this.ymov));
} else {
    this.xmove = this.xmov;
}
if (Math.abs(this.ymov) > Math.abs(this.xmov)) {
    this.ymove = (this.xmov * this.ymov);
} else {
    this.ymove = this.ymov;
}

(And here is the full thing http://jsbin.com/ximatoq/edit. A and D to turn, S to fire (on release). Can also hold S while turning.)
... but, you'll see that it only works for 3/8's of it. What is the math to make this fire from a complete circle?

A:

Use this as shoot function:
this.shoot = function() {
     if (this.fire > 0) {
          this.x = P1gun.x2;
          this.y = P1gun.y2;
          this.xmove = (P1gun.x2 - P1gun.x)/100;
          this.ymove = (P1gun.y2 - P1gun.y)/100;
          this.fire = 0;
          this.firetravel = 1;
     }
}

The /100 can be removed, but you have to reduce the projectile speed.
If you want to shoot gun2 change the P1gun to P2gun.


Q:

Python dictionary

I am having some trouble understanding this, I have tried to reduce the problem to this set of code
for k in y.keys():
    if k in dateDict.keys():

        if yearDict[k] in dict1:
            dict1[yearDict[k]].extend(y[k])
        else:
            dict1[yearDict[k]] = y[k]

        if yearDict[k] in dict2:
            dict2[yearDict[k]].extend(y[k])
        else:
            dict2[yearDict[k]] = y[k]
    else:
        continue

I have two dictionaries y and dateDict to begin with. For a matching key for y in dateDict, I am populating two other dictionaries dict1 and dict2, hashed with keys from some other dictionary yearDict. Unfortunately the result are duplicated in dict1 and dict2, I have values repeating themselves. Any idea what could be happening?
Also I notice that this code works as expected,
for k in y.keys():
    if k in dateDict.keys():

        if yearDict[k] in dict1:
            dict1[yearDict[k]].extend(y[k])
        else:
            dict1[yearDict[k]] = y[k]
    else:
        continue

A:

If y[k] is a list (which it looks like), the same list will be assigned to everywhere where is it used. Dictionaries do not make copies of the elements when they are assigned, they just keep references to their objects. In your example, both keys in dict1 and dict2 will point to the same object.
Later, when it is modified, the same elements will be appended with the new values, once for each map. To prevent this, you can create a new list when initially assigning:
dictl[yearDict[k]] = list(y[k])

However, it is always good to know the Python standard library. This code could be made much more readable, and without the error, by using collections.defaultdict:
from collections import defaultdict

# This goes wherever the dictionaries
# where initially defined.
dict1 = defaultdict(list)
dict2 = defaultdict(list)

# You can get the value here, no need to search it later.
for k, value in y.items():
    if k in dateDict.keys():
        # No need to call this everywhere.
        new_key = yearDict[k]

        # Note the defaultdict magic.
        dict1[new_key].extend(value)
        dict2[new_key].extend(value)

    # No need for the 'continue' at the end either.

When asked for a key that does not exist yet, the defaultdict will create a new one on the fly -- so you don't have to care about initialization, or creating copies of you values.


Q:

If a functor $\varphi : C \to C'$ is full, then so is the functor $\varphi \circ$

Let $I, C, C'$ be three categories, $\varphi : C \to C'$ a functor.  Then $\varphi$ determines a functor $\varphi \circ : \text{Fct}(I,C) \to \text{Fct}(I, C')$.  I want to show that if $\varphi : \text{Hom}_C(X,Y) \to \text{Hom}_C(\varphi X, \varphi Y)$ is surjective for all $X,Y \in C$, then $\varphi \circ : \text{Hom}_{\text{Fct}(I,C)}(F,G) \to \text{Hom}_{\text{Fct}(I,C')}(\varphi F, \varphi G)$ also surjective.  Hints please!

A:

Counterexample:
Let $I$ be the category given by a single nontrivial arrow $f:I_0\to I_1$. Let $C$ be two disconnected copies of $I$, say $\iota_0,\iota_1:I\to C$ map to the separate copies of $I$. Let $C'=I$. Define $\varphi:C\to C'$ so that $\varphi\circ\iota_i=1_I$ ($i=0,1$).
Then, there is no natural transformation between $\iota_0$ and $\iota_1$ in $\mathrm{Fct}(I,C)$, whereas there is one between $\varphi\circ\iota_0$ and $\varphi\circ\iota_1$ in $\mathrm{Fct}(I,C')$.


Q:

JPA/Hibernate Native Queries do not recognize Parameters

I am using Hibernate/JPA to execute native PostGIS queries. The problem with these queries is that they need parameters that are not of the classical X = 'value' form.
For example, the following lines crash
 String queryString = "select * from Cell c where ST_DWithin(c.shape, SetSRID(ST_GeomFromEWKT('POINT(:lon :lat)'),4326), 0.1)";
  Query query = Cell.em().createNativeQuery(queryString, Cell.class);
  query.setParameter("lon", longitude);
  query.setParameter("lat", latitude);

play.exceptions.JavaExecutionException: org.hibernate.QueryParameterException: could not locate named parameter [lon]
 at play.mvc.ActionInvoker.invoke(ActionInvoker.java:259)
 at Invocation.HTTP Request(Play!)
Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryParameterException: could not locate named parameter [lon]
 at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:358)

The following query works however :
String queryString = String.format("select * from Cell c where ST_DWithin(c.shape, SetSRID(ST_GeomFromEWKT('POINT(%f %f)'),4326), 0.1)", longitude, latitude);
Query query = Cell.em().createNativeQuery(queryString, Cell.class);

(but it is SQL-injection-prone...)
Does anyone know how to use setParameter() in this case ?

A:

The use of named parameters is not defined for native queries. From the JPA specification (section 3.6.3 Named Parameters):

Named parameters follow the rules for
  identifiers defined in Section 4.4.1.
  The use of named parameters applies to
  the Java Persistence query language,
  and is not defined for native queries.
  Only positional parameter binding may
  be portably used for native queries.

So try the following instead:
String queryString = "select * from Cell c where ST_DWithin(c.shape, SetSRID(ST_GeomFromEWKT('POINT(?1 ?2)'),4326), 0.1)";
Query query = Cell.em().createNativeQuery(queryString, Cell.class);
query.setParameter(1, longitude);
query.setParameter(2, latitude);

Note that in JPA >= 2.0 you can use named parameters in native queries.

A:

Maybe you can replace
'POINT(:lon :lat)'

with
'POINT(' || :lon || ' ' || :lat || ')'

This way the parameters are outside of constant strings and should be recognized by the query parser.

A:

I had a similar problem and found that parameters can be set with question marks in native queries.
Try this:
String queryString = "select * from Cell c where ST_DWithin(c.shape, SetSRID(ST_GeomFromEWKT('POINT(? ?)'),4326), 0.1)";

Query query = Cell.em().createNativeQuery(queryString, Cell.class);
query.setParameter(1, longitude);
query.setParameter(2, latitude);


Q:

InternalOAuthError: Failed to obtain access token

Can anyone help me with what is wrong with the below code in the link GitHub
oauth2-provider server with passport-oauth2 consumer
After I login with http://localhost:8082 and reach my callback URL:
http://localhost:8081/auth/provider/callback, it throws an error
var express = require('express')
  , passport = require('passport')
  , util = require('util')
  , TwitterStrategy = require('passport-twitter').Strategy;

var TWITTER_CONSUMER_KEY = "--insert-twitter-consumer-key-here--";
var TWITTER_CONSUMER_SECRET = "--insert-twitter-consumer-secret-here--";

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});

passport.use(new TwitterStrategy({
    consumerKey: TWITTER_CONSUMER_KEY,
    consumerSecret: TWITTER_CONSUMER_SECRET,
    callbackURL: "http://127.0.0.1:3000/auth/twitter/callback"
  },
  function(token, tokenSecret, profile, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {

      return done(null, profile);
    });
  }
));

var app = express.createServer();

// configure Express
app.configure(function() {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.logger());
  app.use(express.cookieParser());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.session({ secret: 'keyboard cat' }));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

app.get('/', function(req, res){
  res.render('index', { user: req.user });
});

app.get('/account', ensureAuthenticated, function(req, res){
  res.render('account', { user: req.user });
});

app.get('/login', function(req, res){
  res.render('login', { user: req.user });
});

app.get('/auth/twitter',
  passport.authenticate('twitter'),
  function(req, res){
    // The request will be redirected to Twitter for authentication, so this
    // function will not be called.
  });

app.get('/auth/twitter/callback',
  passport.authenticate('twitter', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

app.listen(3000);

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login')
}

InternalOAuthError: Failed to obtain access token

How can I resolve this issue?

A:

I ran into a similar issue trying to get passport-oauth2 working. The error message, as you've observed, is less than helpful:
InternalOAuthError: Failed to obtain access token
    at OAuth2Strategy._createOAuthError (node_modules/passport-oauth2/lib/strategy.js:382:17)
    at node_modules/passport-oauth2/lib/strategy.js:168:36
    at node_modules/oauth/lib/oauth2.js:191:18
    at ClientRequest.<anonymous> (node_modules/oauth/lib/oauth2.js:162:5)
    at emitOne (events.js:116:13)
    at ClientRequest.emit (events.js:211:7)
    at TLSSocket.socketErrorListener (_http_client.js:387:9)
    at emitOne (events.js:116:13)
    at TLSSocket.emit (events.js:211:7)
    at emitErrorNT (internal/streams/destroy.js:64:8)

I found a suggestion to make a small change to passport-oauth2:
--- a/lib/strategy.js
+++ b/lib/strategy.js
@@ -163,7 +163,10 @@ OAuth2Strategy.prototype.authenticate = function(req, options) {

    self._oauth2.getOAuthAccessToken(code, params,
        function(err, accessToken, refreshToken, params) {
-          if (err) { return self.error(self._createOAuthError('Failed to obtain access token', err)); }
+          if (err) {
+            console.warn("Failed to obtain access token: ", err);
+            return self.error(self._createOAuthError('Failed to obtain access token', err));
+          }

Once I did that, I got a much more helpful error message:
Failed to obtain access token:  { Error: self signed certificate
    at TLSSocket.<anonymous> (_tls_wrap.js:1103:38)
    at emitNone (events.js:106:13)
    at TLSSocket.emit (events.js:208:7)
    at TLSSocket._finishInit (_tls_wrap.js:637:8)
    at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:467:38) code: 'DEPTH_ZERO_SELF_SIGNED_CERT' }

In my case I believe the root cause was that the authorization server I was testing with was using a self-signed SSL cert, which I was able to work around by adding this line:
require('https').globalAgent.options.rejectUnauthorized = false;

A:

same here I got the same issue. Finally I found a solution is related with the corporate proxy and you can check it out the workaround here


Q:

postfix header_checks to rename email subject

We have a number of external systems reading from our emails, and some are tripping over others. Basically what I need to do is replace an email subject like:
[RT #179497] Internal: blah blah

with
[RT 179497] Internal: blah blah

So drop the hash. Does anyone know the regex to achieve this with postfix header_checks?

A:

See header_checks(5) for examples and http://www.postfix.org/BUILTIN_FILTER_README.html#limitations for additional information.
Modifying the example in the mentioned man page is not that hard:
/etc/postfix/main.cf:
header_checks = pcre:/etc/postfix/header_checks.pcre

/etc/postfix/header_checks.pcre:
/^Subject: \[RT #(\d)\] Internal: (.+)$/    REPLACE Subject: [RT $1] Internal: $2

It could probably be done more elegant or shorter, but that's your job now.


Q:

How to draw a polygon overlay using MapKit and swift

I am trying to get the following code to draw a polygon on the map but for some reason it doesn't work. What did i go wrong here?
import UIKit
import MapKit

class ViewController: UIViewController {

    @IBOutlet weak var mapView: MKMapView!
    override func viewDidLoad() {
        super.viewDidLoad()
        let initialLocation = CLLocation(latitude: 49.140838, longitude: -123.127886)
        centerMapOnLocation(initialLocation)
        addBoundry()
    }

    func addBoundry()
    {
        var points=[CLLocationCoordinate2DMake(49.142677,  -123.135139),CLLocationCoordinate2DMake(49.142730, -123.125794),CLLocationCoordinate2DMake(49.140874, -123.125805),CLLocationCoordinate2DMake(49.140885, -123.135214)]

        let polygon = MKPolygon(coordinates: &points, count: points.count)

        mapView.addOverlay(polygon)
    }

    let regionRadius: CLLocationDistance = 1000
    func centerMapOnLocation(location: CLLocation) {
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate,
            regionRadius * 2.0, regionRadius * 2.0)
        mapView.setRegion(coordinateRegion, animated: true)
    }

}

func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! {
        if overlay is MKPolygon {
        let polygonView = MKPolygonRenderer(overlay: overlay)
        polygonView.strokeColor = UIColor.magentaColor()

        return polygonView
    }

    return nil
}

A:

It would appear that you've implemented mapView(_:renderFor:) (previously known as rendererForOverlay) as a global function.  The  method must be within the ViewController class definition or, even better, to keep our code nicely organized, within a MKMapViewDelegate extension:
extension ViewController: MKMapViewDelegate {
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        ...
    }
}

Also, make sure that you've defined the view controller to be the delegate of the map view. It's probably easiest to do that in IB, but you can also do it in viewDidLoad:
mapView.delegate = self


Q:

how to zoom in/out cameraview and capture the same zoom in/out picture directly from cameraview?

i can capture image using avfoundation.framework as shown in AVCam Demo
but i want to

zoom in/out the cameraview
save that zoomed in/out view

i can do 1 but unable to save it in zoomed in/out mode it saved only in normal capture view
Please any one know about it help me out
thanks in advance

A:

I have been using the following solution with success when facing similar problems:
Capturing zoomed preview view in AVFoundation


Q:

Refresh WebView every (N) seconds

I am searching for a code thru which I can refresh webView every N seconds. I got few of the brilliant answers but since I am pretty new in iOS development I am not able identify where do I need to place the refresh snippet.
Here is my code:
import UIKit
import WebKit

class ViewController: UIViewController {

    var webView: WKWebView!
    var websites = "www.example.com/start/home.asp"

    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self as? WKNavigationDelegate
        view = webView

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "https://" + websites)!
        webView.load(URLRequest(url: url) as URLRequest)
        webView.allowsBackForwardNavigationGestures = true

    }

    //MARK:- WKNavigationDelegate

    func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
        print(error.localizedDescription)
    }
    func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("Strat to load")
    }
    func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
        print("finish to load")
    }

}

Here is the snippet which I want to add:
[NSTimer scheduledTimerWithTimeInterval:5 target:selfselector:@selector(updateWeb) userInfo:nil repeats:YES];

-(void)updateWeb
{
    [webView reload];
}

Any help would be much appreciated.

A:

You can use NSTimer to call the method every 5 seconds and use -reload method of UIWebview.
override func viewDidLoad() {
    super.viewDidLoad()

    let url = URL(string: "https://" + websites)!
    webView.load(URLRequest(url: url) as URLRequest)
    webView.allowsBackForwardNavigationGestures = true

    Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
}

@objc func update() {
     webView.reload()
}


Q:

Image paths are getting converted to data URI instead of URL

I have a basic React app set up using the Create-React-App tool.
I have an images in my images folder:
/src/img/logo.png
I am including it in one of my component JS files (let's say it's located at /src/Login.js) like this:
import logo from "../img/logo.png";

I am embedding them into my code like this:

When I look at the rendered page, I see that the "src" attribute of this image has a data URI. How can I get the app to generate a URL for this image instead of a data URI?

A:

Why are you importing image with import, you can directly use path or take that path in one variable and than pass it to the src like this:
 var imgUrl = "../img/logo.png";


Q:

onActivityResult executing twice

From HomeActivity Im trying to get a result from CreateProfileActivity. Here what i do to start the activity
Intent createProfile = new Intent(this, CreatePreacherActivity.class);
startActivityForResult(createProfile, 1);

Here the implementation of onActivityResult method in HomeActivity:
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 1)
        {

            Log.d("DEV","HomeActivity is reciving data");
            if (resultCode == RESULT_OK)
            {

                // this code here execute at the second call
                // but why there are two calls when i just call setResult once???

                User user = new User();

                String[] userInfo = data.getStringArrayExtra("preacher");

                //parsing and saving and database code...

                Log.d("DEV","HomeActivity data received->"+user);

                CurrentUser.set(this, user);
                fillCurrentUserInforms();
            }

            // if while searching for the preacher list
            // and none was found on database. Then tell the user
            // to create a new profile
            else if (resultCode == RESULT_CANCELED)
            {
                Intent createPreacherIntent = new Intent( this, CreatePreacherActivity.class );
                startActivityForResult(createPreacherIntent,1);
            }
        }

When im done and press save in CreateProfileActivity here is what I do to send the data back to HomeActivity:
**private void createProfile()
{
   // some parsing and inserting the new data code..
    User u = new User();
    u.setName(newPreacher.getName());
    u.setLastName(newPreacher.getLastName());
    u.setId(newPreacher.getId());
    u.setSex(newPreacher.getSex());
    CurrentUser.set(this,u);
    if (getParent() == null)
    {
        setResult(RESULT_OK,createPreacherDataIntent(newPreacher));
    }
    else
    {
        getParent().setResult(RESULT_OK,createPreacherDataIntent(newPreacher));
    }
    Log.d("DEV","Exiting from CreatePreacherActivity");
    finish();
}**

The setResult method is call one once on CreateProfileActivity but for some unknown reason when the data get to HomeActivity.onActivityResult method, get execute twice. The first result with the requestCode = 0 and the second one with requestCode  = 1. After that,  HomeActivity.onActivityResult gets execute, the CreateProfileActivity apears again since the first call the requestCode was 0.
Why then is onActivityResult executing twice??
What is 0 on the first call and then 1 on the second??
Notes: I've read the following question to see if im doing something wrong but i can see it:
Android onActivityResult is always 0
fragments startActivityForResult always return resultCode 0 and intent null on callback onActivityResult
And more..
UPDATE:
here my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="jwutils.einers.informedeserviciotj" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Activities.HomeActivity"
            android:label="Inform de Servicio" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Activities.inform.InformEditableActivity"></activity>
        <activity android:name=".Activities.preacher.CreatePreacherActivity"
            android:label="Crear publicador"/>

        <activity android:name=".Activities.preacher.PreachersListActivity"
            android:label="Usuarios" />

    </application>

</manifest>

A:

You should try calling this in onResume() instead of onCreate();
Intent createProfile = new Intent(this, CreatePreacherActivity.class);
startActivityForResult(createProfile, 1);

Here, it say "You will receive this call immediately before onResume() when your activity is re-starting." I beleive that the first call of onActivityResult() with result code "0" is triggered when your first activity try to resume.

A:

Remove
super.onActivityResult(requestCode, resultCode, data);
from your activity's onActivityResult method.


Q:

Is there any good desktop/application or command line tool to show two different timezone concurrently?

I want to find a desktop application or command line tool to show two different timezone concurrently under LINUX.
Anyone knows there are such application?
Say i want to know the time at london and USA at the same time. (different time zone)

A:

Assuming you are using Ubuntu 10.10 or previous version .
The GNOME clock applet can show two times in the drop down.

Right click on the clock and select "Preferences." Goto the "Locations" tab and press "add."
Then, select "whatever" from the "Timezone" list.


Q:

How to include OpenStreetMap in my Web app

Well I am looking for a tutorial that tells me how to include OpenStreetMap in my web app. Google have put such a nice tutorial that tells us step by step process on how to include Google Map in our web app. but I have not come across anything like this for OSM. All I came across is how use (edit) the OSM but not how to include it in our app. All I want is, replace my Google map being used in my app with that with OSM.
Anyone please!
Thanks in advance.

A:

You haven't really explained what you actually want to do. For just displaying a map you should read the Using Tiles section on switch2osm and choose either OpenLayers or Leaflet as your preferred JavaScript library.


Q:

biblatex-apa: for citations in text of the same author but different publications: shortauthor every time in [ ]

I am using biblatex-apawith the apa6.cls.
In the text I cite several versions of the DSM (Diagnostic and Statistical Manual for Mental Disorders) by the American Psychiatric Association (APA):
@book{APA1994,
    author={{American Psychiatric Association}},
    shortauthor = {APA},
    year={1994},
    title="{Diagnostic and statistical manual of mental disorders: {DSM-IV}}",
    publisher={Autor},
    edition = {4th ed.},
    address={Washington, DC},
}

@book{APA2000,
    title = {Diagnostic and Statistical Manual of Mental Disorders: {DSM-IV-TR}},
    edition = {4th ed., text rev.},
    publisher = {Autor},
    author = {{American Psychiatric Association}},
    shortauthor = {APA},
    year = {2000},
    address={Washington, DC},
}

@book{APA2013,
    author = {{American Psychiatric Association}},
    shortauthor = {APA},
    address = {Washington, {DC}},
    edition = {5th ed.},
    title = {Diagnostic and statistical manual of mental disorders: {DSM-5}},
    publisher = {Autor},
    year = {2013},
}

When I first cite f. e.
\parencite{APA1994} I get the correct output:

(American Psychiatric Association [APA], 1994)

When I cite that a second time, I get (which is also correct):

(APA, 1994)

However, when I cite another publication with \parencite{APA2000} then after that, I get:

(American Psychiatric Association [APA], 2000)

But, as this publication has the same author as cited before, I want the shortauthor to be put there, like:

(APA, 2000)

How do I achieve that?

A:

For those interested:
A new version of biblatex-apa fixed this issue, thanks to PLK.


Q:

Is this a valid natural deduction?

I'm trying to prove that $\{(p_1\implies p_2),p_1,(p_2\implies p_3)\}\vdash (p_3\vee p_5)$ which seems easy, but I'm unsure about a step in the way.
I did:
$1.\ p_1\implies p_2 \text{  (Pre)}\\2.\ p_1 \text{(Pre)}\\3. \ p_2\implies p_3 \text{(Pre)}\\ 4.\ p_2 \text{ (By 2. and 1.)}\\ 5.\ p_3 \text{(By 4. and 3.)} \\ 6.\ \neg(p_3\vee p_5) \text{ (Assume)}\\ 6.1.\ (\neg p_3\wedge \neg p_5) \text{(By Morgan)}\\6.2. \ \neg p_3\text{ (By 6.2)}\\7. \ (p_3\vee p_5) \text{ (By contradiction of 6.)}$
Is this right?. I'm unsure about the step 6 where $p_5$ comes from nowhere, should I assume $p_5$ first?

A:

There doesn't seem to be anything strictly wrong with your strategy -- assumptions don't have to come from anywhere as long as they get properly discharged.
But it seems to be a detour. Most natural deduction systems have a rule that allows you to infer directly from $P$ to $P\lor Q$. Doesn't yours?
On the other hand, most natural deduction systems don't include De Morgan's rules as primitive inferences. Are you sure your step from 6 to 6.1 is formally allowed?


Q:

compatibility of pdfpages and screenread packages?

Okay everyone, sorry about my original not being up to standard.  A better version follows.
First, here is a MWE:
\documentclass{article}

\usepackage{pdfpages}
%\usepackage{screenread}

\begin{document}

Some text

\includepdf{image}

\end{document}

File image.pdf can be found here:
http://www.mathematrucker.com/image.pdf
(Any small-sized pdf ought to work.)
File screenread.sty can be found here:
https://github.com/bishboria/screen-read-class
So here's my problem: when \usepackage{screenread} is activated, image.pdf disappears from the second page.  My goal is to use screenread to shorten the height of the first page without losing image.pdf on the second page.
Note: if all I needed to do was merge the second page with the first, there would be no issue.  I think it's okay that my MWE didn't include any links though.
Will leave my initial post below in case it contains any useful information.  It will mean a lot to me if anyone can help me solve this problem!  Thanks everyone.
=======================
Part I of my LaTeX document links to Part II using pdfpages and hyperref—the former merges individual pdf pages together to create Part II.
Part I has a whitespace issue due to lots of images.  The screenread package solves this problem beautifully.
Unfortunately, screenread breaks pdfpages.  When I try to use both at the same time, Part I still gets created beautifully by screenread, but Part II consists of a bunch of empty pages. They have the same width as the Part I pages, but since they don't have any content and screenread is still in play, they're only about an inch high.
Ideally there would be some way to "turn screenread off" when it comes time to typeset Part II.
Assuming not, can anyone suggest a workaround?  My main problem is getting the hyperlinks into Part I.  Their number is large (>1000), so I'm really dependent on pdfpages!  Note that I am using pdfLaTeX.
The specific command that's broken is
\newcommand{\pdf}[4]{\includepdf[pages={#1},link,noautoscale,offset=#3in #4in]{#2}}

A:

screenread contains no code to deactivate its settings (but it would be rather easy to extend the package). But you can with the help of geometry restore the "normal" page layout:
\documentclass{article}

\usepackage{pdfpages}
\usepackage{geometry}
\savegeometry{normal}

\usepackage{screenread}

\begin{document}

Some text

\newpage
\loadgeometry{normal}
\EveryShipout{\pdfpageheight=\paperheight
              \pdfpagewidth=\paperwidth}
\includepdf{example-image-letter}

\end{document}


Q:

Generate random numbers with some conditions

I want to hypotize a tournament that originally starts with 9 players with 1500 chips each, then when a player exits the tournament his chips are given to the one that win against him.
Mainly there are double ups/triple ups etc, but there are some other minor exchanges of chips between the players.
How can I generate randomly their chips taking into account that behaviour of chips exchange?
I would just use rand() but that wouldn't work as expected.

For example:
if I have 9 players I don't have any double ups. So the stacks are similar with some variations like:
$stacks = array(1300,1150,1650,1800,1500,1550,1450,1800,1500,1550);

In a scenario with 4 players there would have been 5 double ups:
$stacks = array(7500,1500,1500,1500) or array(4500,3000,3000,1500); //this should be randomized a little bit to

$stacks = array(7800,1350,1250,1950);

I hope I've been clear, if not I will edit back the post!

A:

If I understand your concern correctly, here's one way to do this:
for ($x = 0; $x < $NUMBER_OF_EXCHANGES; $x++) {
  $loser = array_rand($stacks);
  $winner = array_rand($stacks);
  $stacks[$loser] -= 50;
  $stacks[$winner] += 50;
}


Q:

HighStock not Overlapping data

Currently i´m registering every 10 seconds if my services are accessable via netcast command.

nc -zvvw 10 ip port

A success is registered as a 1, otherwise a 0. The format is something like this:

date;server1;server2;serverN+1

But, it seems like Highcharts put some decimal data that i dont know where are from. And the data is not overlapping at all. (The 1 or the 0) Or at least two series than i'm aware of.
Here is an example about i'm trying to explain if my spanish level is not good enough
http://jsbin.com/overlaping/3/
can anybody help me please.
Edit 1:
The data is from a json source, it's looks like this:

var data = {"titulos":["fecha","server1","server2","server3","server4","server5"],"detalles":[[1389495600000,1,1,1,1,1],[1389495600000,1,1,1,1,1]]}

But for an entire day, every ten seconds.
Edit 2:
Wergeld noticed that i having the same timestamp (on ms) for more than a row of data. That was 'cause i was parsing the date without seconds.

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");

But i added the seconds and it is given me different dates for every row (as i should expect), but the problems persist.
The data now looks like this:

{"titulos":["fecha","yelcho","villarica","coya","cunco","culenar"],"detalles":[[1389495606000,1,1,1,1,1],[1389495616000,1,1,1,1,1],[1389495627000,1,1,1,1,1],[1389495637000,1,1,1,1,1],[1389495647000,1,1,1,1,1],[1389495657000,1,1,1,1,1]]}

Edit 3:
it seems to be some kind of behaviour at a large amount of data and trying to display all. If i zoom it enough, it display correctly. There is a way to display it properly even at full zoom out?
Edit 4:
I ended using this code to solve my problem. Thanks to Pawel Fus for his help.
plotOptions: {
    series: {
        dataGrouping: {
            enabled: true,
            approximation: 'open'
        }
    }
},

A:

This is caused by dataGrouping, you can disable it.
However, it may be very slow to display 10 000points (with markers) on a chart width width 1 000px (10 points on a 1 pixel).
Reference.


Q:

Why does my PowerShell script hang when called in PSEXEC via a batch (.cmd) file?

I'm trying to remotely execute a PowerShell script using PSEXEC. The PowerShell script is called via a .cmd batch file. The reason we do this is to change the execution policy, run the powershell script then reset the execution policy again:
On the remote server do-tasks.cmd looks like:
powershell -command "&{ set-executionpolicy unrestricted}"
powershell DoTasks.ps1
powershell -command "&{ set-executionpolicy restricted}"

The PowerShell script DoTasks.ps1 just does this for now:
Write-Output "Hello World!"

Both of these scripts live in c:\windows\system32 (for now) just so they're on the PATH.
On the originating server I do this:
psexec \\web1928 -u administrator -p "adminpassword" do-tasks.cmd
When this runs I get the following response at the command line:
c:\Windows\system32>powershell -command "&{ set-executionpolicy unrestricted}"
and the script runs no further.
I can't ctrl-c to break the script and I just see ^C characters, I can type input from the keyboard and the characters are echoed to console.
On the remote server I see that PowerShell.exe and CMD.exe are running in Task Manager's Process tab. If I end these processes then control returns to the command line on the originating server.
I have tried this with just a simple .cmd batch file with a @echo hello world and it works just fine.
Running do-tasks.cmd on the remote server via an RDP session works ok as well.
The originating server is running Windows 2003 SP2, the remote server is running Windows 2008 SP2.
Why is my remote batch file getting stuck when executing via PSEXEC?

A:

This is a common issue with POSH. The problem is stdin hangs. Try this:
c:\Windows\system32>powershell -command "&{ set-executionpolicy unrestricted}" < NUL

A:

Most of the answers in the forums solve this with a workaround like echoing and piping so that powershell gets some input from STDIN.
But there exits a solution within powershell. Just start powershell with the option -inputformat none like:
powershell -inputformat none -command ...

This solves the hanging issue via psexec for Win2003 and Win2008.

A:

Since the server is running 2k8 I would suspect UAC is causing issues.  I would also suggest using winrm instead of psexec.  Powershell remoting was one of the best new features of powershell 2.0


Q:

Delete Row From Data Table

I want to Delete the Multiple records from the DataTable
For example :
in my case PaperId is Repeating several Times.I want to Delete it all Duplicate records.
i have written code but loop is giving error
        DataSet ds = new DataSet();
        sqlDad.Fill(ds);
        DataTable dt1 = new DataTable();
        ds.Tables.Add(dt1);
        dt1 = ds.Tables[0];
        DataTable dt2 = new DataTable();
        dt2 = dt1;
        List<DataRow> rowsToDelete = new List<DataRow>();

        foreach(DataRow dr in ds.Tables[0].Rows)
        {
            int r = ds.Tables[0].Columns.Count;
            string x =  dr.ItemArray[0].ToString();
            int counter = 0;
            foreach (DataRow dr1 in ds.Tables[0].Rows)
            {

                if (x == dr1.ItemArray[0].ToString())
                {
                    counter++;
                }
                if (counter > 1)
                {
                    rowsToDelete.Add(dr1);
                    foreach (DataRow row in rowsToDelete)
                    {
                        dt2.Rows.Remove(row);
                    }
                    dt2.AcceptChanges();
                    rowsToDelete.Clear();
                }

            }

A:

Using the DefaultView of the DataTable and setting the sort order on the column that you don't want repeats to appear. You could loop over the rows and delete all the rows after the first one
// Work on the first table of the DataSet
DataTable dt1 = ds.Tables[0];
// No need to work if we have only 0 or 1 rows
if(dt1.Rows.Count <= 1)
     return;

// Setting the sort order on the desidered column
dt1.DefaultView.Sort = dt1.Columns[0].ColumnName;

// Set an initial value ( I choose an empty string but you could set to something not possible here
string x = string.Empty;

// Loop over the row in sorted order
foreach(DataRowView dr in dt1.DefaultView)
{
    // If we have a new value, keep it else delete the row
    if(x != dr[0].ToString())
       x = dr[0].ToString();
    else
       dr.Row.Delete();

}
// Finale step, remove the deleted rows
dt1.AcceptChanges();


Q:

What is the difference between properties.OpenWeb() and properties.Web?

I am developing an event receiver, using the ItemUpdating event, and I noticed that the properties parameter has an "OpenWeb" method, with this description:

Retrieves the Web site that is associated with the event that occurred.

while it also has a "Web" property, with this description:

Gets the parent Web site of the list associated with the event that occurred.

what is the difference?

A:

The only difference is that properties.Web is cached for the duration of the event (after the first access to it).
So properties.Web is implemented to check if it has a cached SPWeb if so return that if not call properties.OpenWeb() and cache the result.
Neither of them will cause a memory leak as they are created from an SPSite which is disposed at the end of the event


Q:

What purpose does @param annotation does in symfony2 class file

In the symfony2 and doctrine 2. I have this
 /**
  * Find a user by its username.
  *
  * @param string  $username
  * @return UserInterface or null if user does not exist
  */
function findUserByUsername($username);

Now i want to know that does it solve nay purpose or does it do anything in database with those @param and @return annotation or they just for documentation

A:

@param is explained in the phpDocumentor docs. It has nothing to do with Symfony2.


Q:

WP7 - Adding Settings page. Reading values from a different page?

So I've created a page called "Settings". Obviously in this page is where the settings are for the app. In the Settings page I've added 2 ToggleSwitches and 1 Listpicker. Using the Nokia Developer website on basics of Saving and reading Settings i managed to pull it off so it saves the states of the toggleswitches and listpicker.
The problem i'm having right now is that i need a way to read these saved setting values on the first page when the app starts so it can prepare the app accordingly. Soo far this is what i have in the Settings page:
Imports System.IO.IsolatedStorage
Partial Public Class Settings
Inherits PhoneApplicationPage
Private AppSettings As IsolatedStorageSettings
Public Sub New()
    InitializeComponent()
    AppSettings = IsolatedStorageSettings.ApplicationSettings
    ListPicker1.Items.Add("Saved Notes")
    ListPicker1.Items.Add("Important")
End Sub
Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs)
    Try
        Tg1.IsChecked = CBool(AppSettings("UseAccentColor"))
        Tg2.IsChecked = CBool(AppSettings("GoBack"))
        ListPicker1.SelectedIndex = CByte(AppSettings("StartListFalse"))
    Catch ex As KeyNotFoundException
        AppSettings.Add("UseAccentColor", False)
        AppSettings.Add("GoBack", False)
        AppSettings.Add("StartListFalse", False)
        AppSettings.Save()
    End Try
End Sub
Protected Overrides Sub OnNavigatedFrom(e As NavigationEventArgs)
    System.Diagnostics.Debug.WriteLine("Exiting, so save now")
    AppSettings("UseAccentColor") = Tg1.IsChecked
    AppSettings("GoBack") = Tg2.IsChecked
    AppSettings("StartListFalse") = ListPicker1.SelectedIndex
    AppSettings.Save()
End Sub
End Class

So soo far it saves on exit but i need a way to load these from startup i.e. my MainPage. Like a way to refer to this page and according to these settings change whatever needs to be changed.
How can i do this?
Thanks!

A:

You managed to save Settings to IsolatedStorage, and IsolatedStorage is accesssible from any page of your application. So in MainPage, just read those setting from IsolatedStorage instead of the Settings Page.
EDIT :
You can do it just like in OnNavigatedTo method in Settings Page
Private AppSettings As IsolatedStorageSettings = IsolatedStorageSettings.ApplicationSettings
'Tg1.IsChecked is analog with useAccentColor
Dim useAccentColor As Boolean = CBool(AppSettings("UseAccentColor"))
'Tg2.IsChecked = goBack
Dim goBack As Boolean = CBool(AppSettings("GoBack"))
'ListPicker1.SelectedIndex = startListFalse
Dim startListFalse As Byte = CByte(AppSettings("StartListFalse"))


Q:

4-Sequences {0...9}

My questions are given the set {0,1,2,3,4,5,6,7,8,9},
1) How many 4-sequences are there?
(would this be $10*10 * 10 * 10 = 10,000)? $ since the max possible numbers given to each 4 slots is 10.
2) How many 4 sequences does not begin with 9?
(this would be $9 * 9 * 9 * 9 = 6,561$ since it would be 1 less digit?)
3) How many 4 sequence begin and end with 9?
4) How many 4 sequence do not begin and end with 9?
5) How many 4 sequence do not begin OR end with 0?

A:

In all of them multiply the choices of each slot.  The only issue is to identify which options are available for each slot.
1) all for sequences.
Ergo 10 choices each slot.  Answer: $10*10*10*10 = 10,000$.
2) sequences not beginning with 9.
Ergo 9 choices for first slot and 10 for all others.  Answer: $1*10*10*10 = 1,000$
3) sequences beginning and ending with 0.
Ergo 1 choice for the first and last slot and 10 for all others.  Answer: $1*10*10*1 = 100$.
4) do not begin and end with 9.
Oh.  THis is a little different.  But this is #1) all sequences minus #3) do begin and end with 9.  Answer: 10,000 - 100 = 9,900$.
Another way:
do not begin and end with 9 means.  Does not begin with 9. plus those that begin with nine but do not end with 9.
Those with 9 choices for the first.  Plus those with 1 choice for the first and 9 for the last.
Answer: $9*10*10*10 + 1*10*10*9 = 9,000 + 900 = 9,900$.
5) (Actually easier than 4).  Do not begin or end with 0.
Ergo 9 choices for first and last and 10 for the others.  Answer: $9*10*10*9 = 8,100$.


Q:

CSS, Limit element to 2 lines of text. Issue on iPad

I want to cut a div off after two lines of text. I've got that.
The issue is on the iPad where a div is taller if it has a removed line of text. How can I make them equal height, always?
Here's a demo http://jsfiddle.net/EgLRh/
It looks fine on desktop and iPhone. However the second green box is slightly taller when viewed on the iPad.
    div{
    float:left;
    width:100px;
    background:green;
    overflow: hidden;
    text-align: center;
    margin:5px;
}

a{
    overflow: hidden;
    min-height: 2.4em;
    max-height: 2.4em;
    line-height: 1.2em;
    display:inline-block;
}

    I fit on two lines. See!

    I do not fit on two lines so I am cut off. Cut off!

A:

The only CSS way to combat this is to set a height to the containing divs
DEMO http://jsfiddle.net/EgLRh/5/
div{
    float:left;
    width:100px;
    background:green;
    overflow: hidden;
    text-align: center;
    margin:5px;
    height:40px;
}

The reason for your problem is that the line is being taken into account as it does in fact exist, it just isn't being show. As a result of the you have the extra space being added.


Q:

Segmentation failure

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    int score,i,j;
    int *ptr, *ptr1;
    int over;
    printf("Enter the number of over");
    scanf("%d",&over);
    ptr=(int*)malloc(over*sizeof(int));
    // do the iteration, outer for loop, read row by row...
    for(i=0; i <= (over-1); i++)
        {
            printf("%d%d ", i, ptr[i]);
            // inner for loop, for every row, read column by column and print the bar...
            printf("Enter the number of run per over");
            scanf("%d",&score);
            ptr1=(int*)malloc(score*sizeof(int));
            for(j = 1; j<= ptr1[i]; j++)
            // print the 'bar', and repeat...
                printf("|");
            // go to new line for new row, and repeats...
            printf("\n");
        }
    return 0;
}

A:

You are using
ptr1=(int*)malloc(score*sizeof(int));

inside your for loop. That causes memory leak. You should free the memory.
You also have
 printf("%d%d ", i, ptr[i]);

But ptr[i]  has not been assigned any value, so it just gives garbage value. The same problem occurs in
for(j = 1; j<= ptr1[i]; j++)

So you need to assign some value to them before using them like this.


Q:

Split on multiple characters while keeping the character in the result

I want to split on '0' and '1' while keeping those characters in the split result. How can I do this in C#?
e.g.
"012345" => 0,1,2345

I tried
Regex.Split(number, @"(?=[01])");

but I get "", 0, 12345 as the result
The following seems to work, except for "" in between splits.
Regex.Split(number, @"(0|1)");

A:

You could use LINQ to simply exclude the empty elements using the regex pattern you mentioned in your post:
var results = Regex.Split(number, @"(0|1)")
                   .Where(p => !String.IsNullOrEmpty(p));

This could also work. I'd like to see a more elegant approach, which I feel is what you are seeking, but it gets the job done.
List<string> results = new List<string>();
int curInd = 0;

var matchInfo = Regex.Matches(number, "(0|1)");
foreach (Match m in matchInfo)
{
    //Currently at the start of a match, add the match sequence to the result list.
    if (curInd == m.Index)
    {
        results.Add(number.Substring(m.Index, m.Length));
        curInd += m.Length;
    }
    else  //add the substring up to the match point and then add the match itself
    {
        results.Add(number.Substring(curInd, m.Index - curInd));
        results.Add(number.Substring(m.Index, m.Length));
        curInd = m.Index + m.Length;
    }
}
//add any remaining text after the last match
if (curInd < number.Length)
{
    results.Add(number.Substring(curInd));
}


Q:

function prototype with multiple parameters including void

I have a piece of software in which there is a function ie:
void function_name(structure_t *param1, void *param2){code....}
I am trying to create a function prototype for this function so it can be linked to another function that occurs before it. I have tried the below line with no success, it does not want to compile.
void function_name(structure_t, void);
I have this line below the associated structure but my guess is the problem is related to the void. The function itself takes the void *param2, which to be honest, confuses me but it works.
The compiler gives the error message: "'void' must be the only parameter"

A:

The Function declaration is missing the * to define the arguments as pointers!
void function_name(structure_t *, void *);


Q:

How to use Intellij's jre in ubuntu

I am using Intellij to write code in Java, if I run my software inside Intellij my software works but, if I create a jar file and I try to start it from my terminal it says that the jre version is too old.
My question is, if the JDK includes also the jre and my software works in Intellij, why it doesn't from the Ubuntu's terminal?

A:

Intelij is poiting to a different java version than the one configured in your terminal path.
If you want to keep booth  version the same you can look in Intelij Settings to find out which version it is using, then replace the /usr/bin/java link in your terminal to point to the same java binary.
Or, simply folow these step to just update your teminal version: install-java-ubuntu


Q:

How can I extract/parse from this SOAP envelope using Ruby?

I am using a gem which uses soap/wsdlDriver.
When I post I get back a SOAP response and am unable to easily parse it.
This is the response I get back:
#<SOAP::Mapping::Object:0x159e95faf098 {}id="27b907f8-da51-f611-ab02-4c5f88a8ec8
8" {}error=#<SOAP::Mapping::Object:0x159e95fae33c {}number="0" {}name="No Error"
 {}description="No Error">>

I need to get the entire value in the id="xxxx"
This is what on get on heroku (note: it works locally).  This comes from testing various variations of response.id (where response.inspect is what created the output above)

f"
  {}error=#>
  response[id]
  /disk1/home/slugs/220752_47a08bb_10e7/mnt/app/controllers/sugarcrm_controller.rb
  :77: warning: Object#id will be
  deprecated; use Object#object_id nil
  response.id:
  /disk1/home/slugs/220752_47a08bb_10e7/mnt/app/controllers/sugarcrm_controller.rb
  :79: warning: Object#id will be
  deprecated; use Object#object_id
  23891500658740
  /disk1/home/slugs/220752_47a08bb_10e7/mnt/app/controllers/sugarcrm_controller.rb
  :80: warning: Object#id will be
  deprecated; use Object#object_id this
  is the contact_id: 23891500658740
  events:

A:

Ok, I'm 95% sure that is the output of SOAP::Mapping::Object#inspect and not the actual response.  And from that class it looks you use the [] method to pull out attributes.
So if I am reading that right, then it looks like you might want:
response_id = response_object['id']

Though each attribute being prefaced with {} seems pretty odd.  So if that is actually part of the attribute name, you may need:
response_id = response_object['{}id']

But that seems pretty strange, and may indicate that the SOAP library you are using is not parsing the response properly.
Disclaimer: I've never used this lib before, and posted this from just perusing the docs...  This may or may not be very accurate in the ways using this class is described.


Q:

In VS2012 how to Browse With IE in private mode

I'm using Visual Studio 2012 and when building an ASP.NET MVC4 application I'm able to set the "Browse With" to an internet browser (Immulator/Simulator) of my choosing. For example: Google Chrome, Firefox, Internet Explorer, etc..
Instead of just using the default Internet Explorer I wanted to use Internet Explorer In-Private Mode.
I've tried:

and

It will work the first time but then every subsequent try after that results back to IE in normal mode.
I am able to accomplish this with Chrome in Incognito mode easily. But for some reason it's not working for IE.  I'm using IE10.
Is anyone else able to do this successfully?

A:

You actually have to use the 32-bit version of Internet Exploring for debugging in Visual Studio 2012.  So, if you add a browser with the following path:
"C:\Program Files (x86)\Internet Explorer\iexplore.exe"
and then use the -private argument, it will work correctly.
-Shaun


Q:

What solution of hard alcohol is sufficient to sanitize and infuse something for addition to a fermenting beer?

Context:
I'm brewing into small, split batches lately to test the effects of various additives. I've got some true cinnamon bark and cacao nibs which I am planning on crushing up, letting steep in alcohol (upper-shelf vodka) for a couple of weeks, and then pitching into 1gal batches of stout when I rack them into secondary.
Question:
Since I'm adding these tinctures/flavorings into such small (1gal) batches of beer, I don't want to end up adding too much of the alcohol sanitizing/tincturing agent and messing up the beer. I'm hoping to dilute the alcohol with some water, so that there's enough to immerse (and thus sanitize and start infusing) the crushed-up flavorings without making my beer taste too much like vodka. What is the minimum safe solution of alcohol:water that will still result in

a good, flavor-rich infusion, and
a bacteria-free addition to secondary?

The first point is less important: I can prolong the infusing process for months to get the proper flavor levels if need be, so long as the end product is sanitized.

A:

A few drops of vodka (or higher proof Everclear if you can get it) on top of the spices/additives, just enough to wet them. Let sit for 60 seconds and add to beer.
Realistically, you probably would be fine adding them directly to the beer without sanitizing. Finished beer is aseptic enough to withstand additives without infecting, it's unfermented wort that you really have to be careful with. If you are worried, though, feel free to sanitize as above.


Q:

Convert a Entire Folder To PDF

I want to turn an entire folder(R Tutorial) that is a web site(written in HTML only) that I've already downloaded all the tree to my computer, but I want to turn this into a single PDF. Someone knows how to do this?

A:

merge the HTML files into a single file (e.g. with SoftSnow Merger)
print the HTML to PDF (e.g. with CutePDF Writer)

SoftSnow Merger and Cute PDF Writer are freeware.
nollaig shona dhuit!
Edit: alternatively, try this:
download the web tutorial with Netspider.
then use Multi-HTML Converter to merge the HTML files.
i'm sorry, buti don't really have any further info on this program or where i got it from (i think i found it in an ebook forum a while back), all i have is the little note included in the download:

This program works on multi-html files
  that are a product of some net-spiders
  that will grab page by page htmls and
  bundle them up with the starting file
  that states "start_here.html", but
  will also work with unpacked .epub
  files, merging them into a single html
  with a stylesheet intact. One little
  notice here, though. To be certain
  that the stylesheet stays with the
  html file, be sure its name is
  stylesheet.css or edit that part
  accordingly in the resulting html's
  header.

however, it works fine for me, i use it to merge HTMLs extracted from EPUB containers.
Calibre can also be used to join HTML files.


Q:

How to assign external json file as variable in other file

I currently have some Javascript on a page template which manages some JSON data. The way I have it configured currently, the JSON data is assigned to a variable right on the page template. What I would like to do is move the JSON to an external .json file and still be able to use my variable on the page template. Currently it looks like this:
var data = [{
    "fruit": "Apple",
    "size": "Large",
    "color": "Red"
}];

What I would like to do is create a file called data.json and then assign it as the data variable on my page template.
data.json:
{
    "fruit": "Apple",
    "size": "Large",
    "color": "Red"
}

Page template:
var data = 'data.json';

How can I accomplish this?

A:

Load your json in dynamic way using e.g. fetch

async function start() {
  let url = 'my.json'
  var data = await (await fetch(url)).json();
  // ...
}

start();


Q:

Kotlin coroutine unit test fails with "Module with the Main dispatcher had failed to initialize"

While running unit test for kotlin suspend method which uses withContext(Dispatchers.Main) the test method fails with below exception:
My coroutine lib versions are kotlinx-coroutines-core:1.1.1 and kotlinx-coroutines-android:1.1.1
Example:
suspend fun methodToTest() {
        withContext(Dispatchers.Main) {
           doSomethingOnMainThread()
                val data = withContext(Dispatchers.IO) {
                    doSomethingOnIOThread()
                }
        }
    }

Also, when I remove the withContext(Dispatchers.Main) it works fine.
java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used

at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.missing(MainDispatchers.kt:79)
at kotlinx.coroutines.internal.MissingMainCoroutineDispatcher.isDispatchNeeded(MainDispatchers.kt:54)
at kotlinx.coroutines.DispatchedKt.resumeCancellable(Dispatched.kt:373)
at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:25)
at kotlinx.coroutines.BuildersKt__Builders_commonKt.withContext(Builders.common.kt:152)
at kotlinx.coroutines.BuildersKt.withContext(Unknown Source)

A:

now you can add this to your test :
Dispatchers.setMain(Dispatchers.Unconfined)

or other dispatcher.. it's experimental but it works!

A:

You don't have access to Dispatchers.Main in unit testing
See https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-test/
Dispatchers.Main Delegation part explains in detail what you need to do.


Q:

C# timer function won't allow for int values? Requests System.CompontentModel.IContainer?

I've created the delay function below with the intention of creating a delay within the certain bounds of my "min" and "max" inputs.
    private void delay(int min, int max)
    {
        Random rnd = new Random();
        int timerLength = rnd.Next(min, max);
        Timer timer = new Timer(timerLength);
        timer.Start();
    }

I get an error in the line
Timer timer = new Timer(timerLength);

As the compiler cannot convert timer Length from an int to a "System.ComponentModel.IContainer". I've tried to convert the input values to IContainers but with no success, as the random function only allows int values.
Is there a workaround to this at all, so that the timer function can take an int? Thanks.

A:

From msdn:

The Timer constructor enables you to associate a Timer with any
  Container object. By associating the Timer like this, you hand over
  control of the lifetime of the Timer to the Container. This can be
  useful if you use a number of components in your application and want
  to dispose of all of them simultaneously. For example, if you
  associate a ToolTip, an ImageList, and a Timer with a Container,
  calling Dispose on the Container will force disposal of all of these
  components as well.

So, if I understand you right, you are trying to set the interval for your Timer. In that case you need to use the 'Interval` property:
private void delay(int min, int max)
{
    Random rnd = new Random();
    int timerLength = rnd.Next(min, max);
    Timer timer = new Timer();
    timer.Interval = timerLength; // the value in milliseconds.
    timer.Start();
}


Q:

Look up the user with bearer token with Openiddict Core

I am currently using Openiddict, Identity and Entity Framework to manage my users and assign Bearer tokens to users to protect my API.
My infrastructure is currently using ASP.NET Core Web API in the back end and a separate React application in the front end.  The React application makes HTTP calls to my API to retrieve it's data.  There is no server side HTML rendering at all in the back end.
Everything works as I need it to for the most part.  I can register users and retrieve tokens from the API.  These tokens are included in my HTTP call in the Authorization header.  My AuthorizationController uses this: https://github.com/openiddict/openiddict-samples/blob/dev/samples/PasswordFlow/AuthorizationServer/Controllers/AuthorizationController.cs with a few minor tweaks.  My Startup.cs also uses almost exactly this https://github.com/openiddict/openiddict-samples/blob/dev/samples/PasswordFlow/AuthorizationServer/Startup.cs
In some instances, I need to make API calls to the endpoints that are specific to the user.  For instance, if I need to know if a user has voted on a comment or not.  Instead of passing along the users ID in a query string to get the user details, I would like to use the Bearer token I received that they use to make the API call for that endpoint.  I am not sure how to do this though.
In some research I have done it looks like some samples use ASP.NET Core MVC as opposed to the API to retrieve the user with the User variable as seen here https://github.com/openiddict/openiddict-samples/blob/dev/samples/PasswordFlow/AuthorizationServer/Controllers/ResourceController.cs#L20-L31 however this seems not to apply to my infrastructure.
My question is how do I look up a user based on the Bearer token passed to the API to look up a users details from my database?  I am assuming that all of the tokens passed out by the API are assigned to that specific user, right?  If that's the case it should be easy to look them up based on the Bearer token.

A:

The question is: How with Openiddict can you look up a user based on the token that was assigned to them for API calls? I need to get the user details before anything else can be done with the application first. Is there something baked internally or do I have to write my own support for this?

When you create an AuthenticationTicket in your authorization controller (which is later used by OpenIddict to generate an access token), you have to add a sub claim that corresponds to the subject/entity represented by the access token.
Assuming you use the user identifier as the sub claim, you can easily extract it from your API endpoints using User.FindFirst(OpenIdConnectConstants.Claims.Subject)?.Value and use it to make your DB lookup.


Q:

How to add space between elements in nested arrays using .join method

I'm learning JavaScript and in Arrays part I've got some question when I use .join in array with nested array.
var arr = [1, 2, 3, [4, 5];

console.log(arr.join(', '));

// Output 1, 2, 3, 4,5

How can I get result that include space between 4 and 5?
Like: 1, 2, 3, 4, 5

A:

const myArray = [1, 2, 3, [4, 5]];
const mergedNestedArrays = [].concat.apply([], myArray)

console.log(mergedNestedArrays.join(', '));

First you need to merge/flatten your nested arrays then apply join() method. Hopefully that helps you.


Q:

Work and energy question

An athlete picks up a $20.0\,\mathrm{kg}$ sandbag from the ground and throws t straight up in the air. It leaves her hands $1.50\,\mathrm{m}$ above the ground and reaches a height of $7.00\,\mathrm{m}$

How much work did the athlete do?

So i tried this problem by myself and got the wrong answer.
First, i found the final speed which was $v_f^2 = 2gh = 10.4\,\mathrm{m/s}$
Then, in order to find work i used $W = K_f - K_i$
$W = \frac{1}{2}mv^2 = 1081.6\,\mathrm{J}$
However, the textbook suggests different approach for this problem.
It says that for $W = U_f + K_f = mgh +0 = 1.37\,\mathrm{kJ}$
I'm really confused about this approach, what is $U_f$ and why the formula that I used for Work did not work?

A:

The work that the athlete does is in throwing the sandbag up to a height of 7.00m.
You have calculated the final speed of the sandbag as it reaches the ground again, however once the sandbag reaches the height of 7m, it has no kinetic energy any more and is at rest (with $v_f = 0$).
Now, gravity takes over: the kinetic energy has been completely converted to potential energy $U_f$ when the sandbag reaches $h = 7m$.
In this case, we can say that $K_f - K_i = \frac12 mv_i^2 - 0 = mgh = U_f$ and therefore the work done is $W = U_f + K_f = mgh + 0$


Q:

how to use the addBlock method in templates?

having block declaration from layout , say:
    <block type="core/template" name="top.search" as="topSearch" template="catalogsearch/form.mini.phtml"/>

how can i use addblock in a template for displaying the block
       /* @var $this Mage_Core_Block_Template */
     echo $this->getLayout()->addBlock($block, $blockName)->toHtml() ;

A:

i have found out from how to print a list of available blocks from a template?
that this was working nicely
echo $this->getLayout()->getBlock('top.search')->toHtml();


Q:

Exponentiated Commutation Relations

A proof about the exponentiated commutation relations is mentioned In this book page 285:

The exponentiated momentum operators satisfy:
$(e^{itP_j}\psi)(\textbf{x})=\psi(\textbf{x}+t\hbar \textbf{e}_j)$.
It is then evident that $e^{isP_j}$  commutes with $e^{itP_k} $.

I know that the same operators of different indices commute. But I cannot see (mathematically) the conclusion that the author stated in this particular example.

A:

It is not true that "the same operator with different indices commute". For example, the angular momentum operators in different directions don't commute, i.e., $[\hat{L}_x,\hat{L}_y]\neq 0$, etc. However, of course, what you say is true of momentum operators (and position operators), i.e., $[\hat{p}_x,\hat{p}_y]=0$, etc. (at least in commutative geometries).

Given that $e^{i\hat{P}_jt}\psi(\mathbf{x})=\psi(\mathbf{x}+t\mathbf{e}_j)$, you can see that $$e^{i\hat{P}_kt}e^{i\hat{P}_jt}\psi(\mathbf{x})=\psi(\mathbf{x}+t\mathbf{e}_j+t\mathbf{e}_k)=\psi(\mathbf{x}+t\mathbf{e}_k+t\mathbf{e}_j)=e^{i\hat{P}_jt}e^{i\hat{P}_kt}\psi(\mathbf{x})$$Thus, $[e^{it\hat{P}_j},e^{it\hat{P}_k}]=0$. To directly see that this implies $[\hat{P}_j,\hat{P}_k]=0$, notice that since $[e^{it\hat{P}_j},e^{it\hat{P}_k}]=0$ is generically true, you can take the limit $t\to0$ and write $[1+it\hat{P}_j,1+it\hat{P}_k]=0$, or, $[\hat{P}_j,\hat{P}_k]=0$.


Q:

Exception propagation in java.util.concurrent.CompletableFuture

There are two snippets of code.
In the first one we create the CompletableFuture from the task which always throws some exception. Then we apply "exceptionally" method to this future, then "theAccept" method. We DO NOT assign new future returned by theAccept method to any variable. Then we invoke "join" on original future. What we see is that "exceptionally" method has been invoked as well as the "thenAccept". We see It because they printed appropriate lines in output. But the Exception has not been suppressed by "exceptionally" method. Suppress exception and provide us with some default value instead is exactly what we expected from "exceptionally" in this case.
In second snippet we do almost the same but assign new returned future to variable and invoke "join" on It. In this case as expected exception is suppressed.
From my point of view for the first part the consistent behavior is either not to suppress exception and not to invoke "exceptionally" and "thenAccept" or call exceptionally and suppress exception.
Why do we have something in between?
First snippet:
public class TestClass {
    public static void main(String[] args) {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(TestClass::doSomethingForInteger);

        future.exceptionally(e -> {
                    System.out.println("Exceptionally");
                    return 42;
                })
                .thenAccept(r -> {
                    System.out.println("Accept");
                });

        future.join();
    }

    private static int doSomethingForInteger() {
        throw new IllegalArgumentException("Error");
    }
}

Second snippet:
public class TestClass {
    public static void main(String[] args) {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(TestClass::doSomethingForInteger);

        CompletableFuture<Void> voidCompletableFuture = future.exceptionally(e -> {
            System.out.println("Exceptionally");
            return 42;
        })
                .thenAccept(r -> {
                    System.out.println("Accept");
                });

        voidCompletableFuture.join();
    }

    private static int doSomethingForInteger() {
        throw new IllegalArgumentException("Error");
    }
}

A:

There is no such thing as “suppressing an exception”. When you invoke exceptionally, you are creating a new future, which will be completed with the result of the previous stage or the result of evaluating the function if the previous stage completed exceptionally. The previous stage, i.e. the future you’re invoking exceptionally on, is not affected.
This applies to all methods chaining a depend function or action. Each of these methods creates a new future, which will be completed as documented. None of them affects the existing future you’re invoking the method on.
Perhaps, it becomes much clearer with the following example:
CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> {
    LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
    return "a string";
});

CompletableFuture<Integer> f2 = f1.thenApply(s -> {
    LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(2));
    return s.length();
});

f2.thenAccept(i -> System.out.println("result of f2 = "+i));

String s = f1.join();
System.out.println("result of f1 = "+s);

ForkJoinPool.commonPool().awaitQuiescence(1, TimeUnit.DAYS);

Here, it should be clear that the result of the dependent stage, an Integer, can’t supersede the result of the prerequisite stage, a String. These simply are two different futures with different results. And since calling join() on f1 queries for the result of the first stage, it isn’t dependent on f2 and hence, does not even wait for its completion. (That’s also the reason why the code waits for the end of all background activity at the end).
The usage of exceptionally is not different. It might be confusing that the next stage has the same type and even the same result in the non-exceptional case, but it doesn’t change the fact that there are two distinct stages.
static void report(String s, CompletableFuture<?> f) {
    f.whenComplete((i,t) -> {
        if(t != null) System.out.println(s+" completed exceptionally with "+t);
        else System.out.println(s+" completed with value "+i);
    });
}

CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> {
    LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
    throw new IllegalArgumentException("Error for testing");
});
CompletableFuture<Integer> f2 = f1.exceptionally(t -> 42);

report("f1", f1);
report("f2", f2);

ForkJoinPool.commonPool().awaitQuiescence(1, TimeUnit.DAYS);

There seems to be a widespread mindset of the CompletableFuture chaining methods to be some kind of builder for a single future, which unfortunately is misleadingly wrong. Another pitfall is the following mistake:
CompletableFuture<?> f = CompletableFuture.supplyAsync(() -> {
    LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
    System.out.println("initial stage");
    return "";
}).thenApply(s -> {
    LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
    System.out.println("second stage");
    return s;
}).thenApply(s -> {
    LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
    System.out.println("third stage");
    return s;
}).thenAccept(s -> {
    System.out.println("last stage");
});

f.cancel(true);
report("f", f);

ForkJoinPool.commonPool().awaitQuiescence(1, TimeUnit.DAYS);

As explained, each chained method creates a new stage, so keeping a reference to the stage returned by the last chained method, i.e. the last stage, is suitable to get the final result. But canceling this stage will only cancel that last stage and none of the prerequisite stages. Also, after cancellation, the last stage does not depend on the other stages anymore, as it is already completed by cancellation and capable of reporting this exceptional result while the other, now unrelated stages are still being evaluated in the background.


Q:

counting the number of files containing a given value or term in R

I have a folder holding a set of different data files. I would like to count the number of files that contain a given term, like "25" or "color coding", and if possible, listing the name of those files. Are they any ways to do that in R?

A:

Does this do what you need
findTermsInFileNames <- function(terms, theFolder="path/to/Folder/", extension="R", ignoreCase=TRUE)  {
  # Iterates through all files of type `extension` in `theFolder` and returns a
  #  count for each time one of `terms` appears in a file name
  # Note:  extension should NOT include a dot.  good: "*"  bad: ".*"

  # str_detect is from stringr
  require(stringr)

  # Get list of files
  pat <- paste0("*.", extension)
  filesList <- list.files(path.expand(theFolder), pattern=pat, ignore.case=ignoreCase)

  # Add attribute to terms, whether cAseS should be ignored
  attr(terms, "ignore.case") <- ignoreCase

  # Tabulate all occurrences of temrs in the list of file names
  results <- rowSums(sapply(filesList,  str_detect, terms, USE.NAMES=TRUE))

  # Clean up the table names
  names(results) <- terms

  return(results)
}

Example:
fold <- "~/git/src"
terms <- c("an", "example", "25")

findTermsInFileNames(terms, fold)


Q:

Performing calculations on specific rows in dataframe and using the results to perform additonal calculations

Provided an example table below (In reality, this table would have many more experiments for a given subject, many more samples, and variable numbers of replicates):
SujectID    Experiment    Sample    Results
A               1          neg         1
A               1          neg         2
A               1          test-a      123
A               1          test-a      144
A               1          test-b      43
A               1          test-b      54
B               1          neg         42
B               1          neg         45
B               1          test-a      45
B               1          test-a      54

I need to calculate the mean of the negatives for a given experiment for a given subject. Then I have to subtract this from the means for each test with that experiment for that subject. I'd like to make that a new column in the dataframe where each replicate gets the result of the calculations with the means.
Now the the first six rows of the table would look like this:
SujectID    Experiment    Sample    Results    Adjusted
A               1          neg         1          0
A               1          neg         2          0
A               1          test-a      123        132
A               1          test-a      144        132
A               1          test-b      43         47
A               1          test-b      54         47

I can do some of this using 'groupby' and 'mean', but then I'm unsure how to unpack those values back into this table.
dataframe.groupby(['SubjectId', 'Experiment', 'Sample']).mean()

I can also do this using a python dictionary, but it seems like this is suited for pandas since I have a giant table.

A:

One approach - filter your dataframe to just the negative samples before you do the groupby, then combine back with your larger frame using merge
neg_sample = df['Sample'] == 'neg'
neg_means = df[neg_sample].groupby(['SujectID', 'Experiment']).mean()
neg_means.columns = ['Adj']

df = df.merge(neg_means, how='left', left_on=['SujectID','Experiment'], right_index=True)
df['Adjusted'] = df['Results'] - df['Adj']


Q:

Is there an assert for sublists in Python unit testing?

For Python 2.7:
list1 = [1, 2]

self.assertIn(1, list1)
self.assertIn(2, list1)

Is there a way I can do this easier? Something like:
self.assertIn((1,2), list1)  # I know this is wrong, just an example

A:

Try
self.assertTrue(all(x in list1 for x in [1,2]))

If you can use pytest-django you can use the native assert statement:
assert all(x in in list1 for x in [1,2])

A:

I'm sure you figured it out but you can use a loop for that:
tested_list = [1, 2, 3]
checked_list = [1, 2]

# check that every number in checked_list is in tested_list:
for num in checked_list:
    self.assertIn(num, tested_list)

This fails on a particular number that is missing in tested_list so you immediately know where the problem is.

A:

For stuff like this I particularly like the hamcrest library.
You can write your test something like this:
from hamcrest import assert_that, has_items, contains_inanyorder

assert_that([1, 2], has_items(2, 1)) # passes

assert_that([1, 2, 3], has_items(2, 1)) # also passes - the 3 is ignored
assert_that([1, 2], has_items(3, 2, 1)) # fails - no match for 3
assert_that([1, 2], contains_inanyorder(2, 1)) # passes
assert_that([1, 2, 3], contains_inanyorder(2, 1)) # fails, no match for 3

Slightly more ugly, and less readable, but shows all the missing elements, rather than just the first element to fail:
actual = [1, 2]
expected = set([1, 2, 3, 4])
self.assertEqual(set(actual) & expected, expected)

Outputs:
AssertionError: Items in the second set but not the first:
3
4


Q:

Javascript document.getElementById issue

I am a beginner to javascript, and am trying to learn how to use text boxes because I can't seem to find a page that is simple enough for me. This is what I have, but when I click the button, it just returns [object HTMLInputElement]. Could someone please tell me what i did wrong and help me fix it? Thanks.
<html>
<head>
<script language="javascript">
function displaynumber(){
var number1= document.getElementById("num1");
alert(number1).value
}
</script>
<title>
ok
</title>
</head>
<body>
<form>
Input the first number<input type="text" id="num1">
<input type="button" value="submit" onClick="displaynumber()">
</form>
</body>
</html>

A:

You should correct your typo:
alert(number1).value

to
alert(number1.value)


Q:

Determine which of the following sets is a null set as defined in the question.

A set $X\subseteq \Bbb R$ is said to be a null set if for every $\epsilon\gt0$ there exists a countable collection $\{(a_k,b_k)\}_{k=1}^\infty$ of open intervals such that $X\subseteq \cup_{k=1}^\infty\{(a_k,b_k)\}$ and $\sum_{k=1}^\infty(b_k - a_k)\le \epsilon$. Which of the following sets is not a null set?

Every finite set
$\Bbb Q^c$, the set of irrational numbers
$\Bbb Q$, the set of rational numbers
$\Bbb N$, the set of natural numbers

I haven't been able to grasp the question clearly. What I did notice is that among the sets given, only $\Bbb Q^c$ is uncountable. Is the definition of null set given in this question actually that of a countable set?

A:

You are partially correct.  Any countable set will be a null set.  If your set $X$ consists of just the points $\{x_k\}_{k=1}^\infty$ then for any $\epsilon>0$ you may let: $$a_k=x_k-{\frac\epsilon{2^{k+1}}},\qquad b_k=x_k+{\frac\epsilon{2^{k+1}}}$$
Then for all $k$, we have $x_k\in (a_k,b_k)$.  Thus $X\subseteq \bigcup_{k=1}^\infty(a_k,b_k)$.
Further we have $\sum_{k=1}^\infty (b_k-a_k)=\sum_{k=1}^\infty \frac\epsilon{2^k}=\epsilon$.
We may conclude that a countable subset of $\mathbb{R}$ does indeed satisfy the condition of being a null set.  That is enough to answer the multiple choice question.
However the definition given for null set is not the same as for countable set.  Not every null set is countable.  For example the Cantor set is a null set, but not countable.
That is the Cantor set consists of real numbers in $[0,1]$ which may written out in ternary expansion using only the digits $0$ and $2$.  Clearly this not countable (real numbers in $[0,1]$ may be written out using just two digits in binary).  However the Cantor set may be contained in a union of $2^n$ intervals each of size as close as you like to $\frac{1}{3^{n}}$ for any $n$.  For any $\epsilon>0$ you may choose $n$ sufficiently large that $\left(\frac{2}3\right)^n<\epsilon$, so the sum of the lengths of the $2^n$ intervals will be less than $\epsilon$.


Q:

How do I send values of selected checkbox as an array to the function?

Im fairly new to working with angular and was wondering if there is a simple way to first check if the checkbox is selected. If it is selected, I want to pass it to the saveOptions function. If more than one is selected, I would like to pass them all and save them to an array of options. Can someone help me out?
import { Component } from '@angular/core';
import { forEach } from '@angular/router/src/utils/collection';
import { Options } from 'selenium-webdriver/ie';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  options: any = []

  saveOptions(x:any[]){
     x.forEach(element => {
      this.options.push(element);
    });
  }

}

<input type="checkbox"  id="option-1" value="1" required> Option 1

<input type="checkbox"  id="option-2" value="2" required> Option 2

<input type="checkbox"  id="option-3" value="3" required> Option 3

    <button type="button" (click)="saveOptions();">Submit</button>

A:

One way is subscribing to valueChanges of the form, like this:
export class AppComponent implements OnInit {
  options: any = []
  model = { optionOne: false, optionTwo: false, optionThree: false }
  formChangesSubscription;
  @ViewChild('form') ngForm: NgForm;

  ngOnInit() {
    this.formChangesSubscription = this.ngForm.form.valueChanges.subscribe(x => {
      console.log(x);
    })
  }

  saveOptions(x: any[]) {
    x.forEach(element => {
      this.options.push(element);
    });
  }
}

<form #form="ngForm">

<input type="checkbox" [(ngModel)]="model.optionOne" name="optionOne" id="option-1" value="1" required> Option 1

<input type="checkbox" [(ngModel)]="model.optionTwo" name="optionTwo" id="option-2" value="2" required> Option 2

<input type="checkbox" [(ngModel)]="model.optionThree" name="optionThree" id="option-3" value="3" required> Option 3

    <button type="button" (click)="saveOptions();">Submit</button>

</form>

https://stackblitz.com/edit/angular-j5idkn?file=src%2Fapp%2Fapp.component.ts


Q:

my question was deleted

I asked a question about a film I am looking for and I logged in today to find that it has vanished.
what happened to it? why was i not notified that it was removed?
how can i recover my deleted question? i spent a lot of time writing it and investigating it, now that it's gone i feel like i've been robbed, how can i get it back?

A:

The policy on identification questions is, that they are eligible for deletion when they don't have any upvoted or accepted answers and remained inactive for 4 weeks, as described in the help center and this meta post. Since this policy has recently been updated as described in this meta discussion, there was a recent cleanup session where questions that are thus deletable were acted upon accordingly, yours was one of them.
You might feel like having been robbed and I see that you have put much detail into the question, but such are the rules of this site and they are necessary to tackle the long-term negative impact those inactive identification questions have on the site. If however, you have any new insights or updates to your question that may provide new possibilities for answering, you can add them in and it might get undeleted.

However, I wonder why you haven't been notified of the removal. I thought a deleted question would automatically trigger a user notification. If not, then I see why you were surprised. Thanks for bringing this to notice.

A:

I'm not entirely sure what the relationship between OnlineDevs.com and StackExchange is, but I do know that OnlineDevs.com reposts StackExchange questions (and answers).
So, using a bit of Google, I was able to locate your original question "Blue ant eater people that turn into flying whales either when they die or for some other reason" on the OnlineDevs.com site at this link.
The full text of your question is available there, along with the answer that had been given (no context in terms of users or anything though).


Q:

Show that $\int_{0}^{1}\ln{(1+e^t)}dt\approx\frac{1}{4}+\ln{2}.$

a) Let $$f(x)=\int_0^x\ln{(1+e^t)}dt.$$
Find the McLaurin expansion of the second order, with the remainder term on Lagrangian form.
b) Show that $$\int_{0}^{1}\ln{(1+e^t)}dt\approx\frac{1}{4}+\ln{2},$$
with an error less than $1/8.$

The first sub-problem was easy, just differentiate three times and plug in to the McLaurin formula. I got that $$f(x)=\ln{2}\cdot x +\frac{1}{4}x^2+\frac{e^{\theta x}}{6(1+e^{\theta x})^2}x^3.$$
Using this to show b), I have that
$$\int_{0}^{1}\ln{(1+e^t)}dt\approx\left[\ln{2}\cdot x +\frac{1}{4}x^2+\frac{e^{\theta x}}{6(1+e^{\theta x})^2}x^3\right]_0^1=\ln{2+\frac{1}{4}}+\frac{e^{\theta}}{6(1+e^{\theta})^2}.$$
Here, the difference between what is supposed to be shown and what I have is the last term $e^{\theta}/6(1+e^{\theta})^2.$ This error will attain max value when $\theta=1.$ So I have that
$$\frac{e}{6(1+e)^2}<\frac{e}{6\cdot 8}<\frac{1}{8}.$$
Thus, when using a second order McLaurin expansion, the error can never be greater than $1/8$.
Questions:

Is this solution correct?
Any detail to change in order to improve the mathematical stringency?
In my second equation line, I write that the integral is $\approx$, is this correct or should I use plain $=$?

A:

We have $f(0) = 0$ by definition and $f'(x) = \ln(1+e^x)$ by the FTOC. Therefore
$$ f(x) = f(0) + f'(0)x + f''(0)\frac{x^2}{2} + O(x^3) = x \ln 2 + \frac{x^2}{4} + O(x^3) $$
The definite integral is given by $$ f(1) \approx \ln 2 + \frac14$$
For the error term we have
$$ \left|f(x) - x\ln 2 - \frac{x^2}{4} \right| \le M\frac{x^3}{3!} $$
where $M$ is an upper bound for $|f'''(x)|$ where
$$ f'''(x) = \frac{e^x}{(1+e^x)^2} $$
This is a decreasing function in $[0,1]$ (you can check for yourself). Therefore $f'''(x) \le f'''(0) = \dfrac{1}{4}$ and
$$ \left|f(1) -\ln 2 - \frac{1}{4} \right| \le \frac{1}{24} $$


Q:

drop down options from json using angularjs data type is appending

Populating select with JSON in AngularJS with ng-options,
<select id="routeName-{{$index}}" ng-model="row.routeName" ng-options="routeName.id as routeName.name for routeName in routeNames" ng-change="flowRootChange($index)" style="width: 115px;"></select>

input JSON is below:
scope.routeNames=[{"id":"1","name":"routeName1"},{"id":"2","name":"routeName2"}];

but in html displaying like below:
<select style="width: 115px;" ng-change="flowRootChange($index)" ng-options="routeName.id as routeName.name for routeName in routeNames" ng-model="row.routeName" id="routeName-0" class="ng-pristine ng-valid ng-touched">
   <option label="routeName1" value="string:1">routeName1</option>
   <option label="routeName2" value="string:2">routeName2</option>
</select>

By reading the data using JQuery I'm getting string:2 as output.
console.log($("#routeName-"+rowid +" :selected").val());

I can't use ng-model/$scope.row.routeName because this drop down is in Table.
How can i read selected value(without string:) without using split() method?.
I'm using 'AngularJS v1.4.8' varsion.

A:

You can use ng-repeat instead of ng-options
<select style="width: 115px;" ng-change="flowRootChange($index)" ng-model="row.routeName" >
   <option ng-repeat='routeName in routeNames' label="routeName{{ routeName.id  }}" value="{{ routeName.id }}">{{ routeName.name }}</option>
</select>


Q:

How can I fix "Compilation unit name must end with .java, or one of the registered Java-like extensions"?

This error comes up in an alert box when I try saving my js file in eclipse:

Compilation unit name must end with .java, or one of the registered
  Java-like extensions

In the breakpoints view I see this:
/module-foo/src/main/resources/frontend/foo/foo_base.js [entry] - ___anonymous()

A:

I had an errant breakpoint set in the file. Removing the breakpoint resolved the problem.
The answer comes from a comment in another post, but was a bit obscure in the comments of a lower ranked answer here: JavaScript editor within Eclipse
Hopefully putting it here will make it easier to find as I didn't find much when I was trying to resolve this before.

A:

I also fixed this by removing breakpoints. The interesting thing was, I wasn't able to remove the breakpoint by double clicking on it as you normally would.
I had to go into the Breakpoint View and right click and remove the breakpoint from this file. Directly afterwards, I tried to save again, and it was the first time the task completed.

A:

I came here for help and it was indeed due to a breakpoint in a javascript .js file (JSDT related bug ?). I had the error popup each time I saved in the .js file.
Go to:

Eclipse Debug perspective -> Breakpoints

view and remove the breakpoint from the .js file.
Fixed: You can now save the .js file without the error.


Q:

When to use: htmlspecialchars?

I need to convert my strings to special characters using:
 htmlspecialchars

My question is, should I convert my data before submitting it to a database or should I convert it before I display it?

A:

You should sanitize data before inserting it into a database, and escape it on retrieval.
htmlspecialchars is used for escaping, so it should be after you’ve fetched it from the database.


Q:

Debugging the second time with breakpoints in Haskell?

When setting breakpoints in haskell code form ghci, they only get triggered the first time I do a runthrough of the program.
If I try to run the function again, no breakpoints get triggered.
For example, if I follow the breakpoint tutorial, then calling main the second time, does not trigger any breakpoints (i even tried reloading with :r).
Any ideas?

A:

Use :l to load the haskell file a second time, :reload only loads the file if a change is detected.


Q:

What can I do fix this syntax error that I have in chapter eight of the Rails Tutorial?

I'm going through the Rails Tutorial and am on chapter 8 (where I am working on an authentication system). When I run the test suite that I've prepared so far, I get 8 identical errors with the following information:
rails_projects/sample_app/app/views/sessions/new.html.erb:9: syntax error, unexpected ':'
   ..._buffer.append= ( f.text_field: :email );@output_buffer.safe...

My test code and embedded ruby code is in the following gist: https://gist.github.com/2997168.
Line 9 of new.html.erb is:
<%= f.text_field: :email %>

Any help you can provide would be greatly appreciated!

A:

The error is in your view:
<%= f.text_field: :email %>
                ^-here

Remove the colon and you should be fine.


Q:

How to use image tag and source in django template language system

I have a encoded 64 image in json which going to insert into django html template.
How should I translate this
<img src="R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp(Some 64 bit image);base64 />

into django template?
I have a body tag to receive the data and a style tag to put in css.

A:

What you are looking for is called Data URI and it has following syntax
data:[<media type>][;base64],<data>


Q:

How to use a text file as standard input to test my program in XCode 4.33

I'm having trouble figuring out how to test my program using XCode.  I usually edit in the command line with vim, but am trying to transition to an IDE.  I'm sure there is an easy way to do the equivalent of homework.out < testfile.txt
Thanks!

A:

I haven't tested it, but putting "< testfile.txt" in the scheme's command line arguments may work. Apparently doing something similar worked for an earlier version of Xcode.


Q:

Rxjs map child objects plus parent field

I have this response from a http get
{
    "parents": [{
        "id": 1
        , "children": [{
                "name": "child1"
            }
            , {
                "name": "child2"
            }]
    }, {
        "id": 2
        , "children": [{
                "name": "child1"
        }]
    }]
}

and I have this interface
export interface Child {
    parentId: string
    , name: string
}

Question
Which map should I do to obtain an array of children (in the response of the subscription), with the name and the id of the parent?
getChildren(): Observable<Child[]> {
    return this.http
        .get(API_URL)
        .//map function;
}

Or at least, tell me where to look to find some sort of answer
Thanks in advance.

A:

You can use a single map() operator and then inside it use Array.forEach() and Array.map():
const Observable = Rx.Observable;

data = {
  "parents": [{
    "id": 1
    , "children": [{
      "name": "child1"
    }
      , {
        "name": "child2"
      }]
  }, {
    "id": 2
    , "children": [{
      "name": "child1"
    }]
  }]
};

Observable.of(data)
  .map(data => {
    let results = [];
    data['parents'].forEach(item => {
      results = results.concat(item['children'].map(child => {
        return {
          'parentId': item.id,
          'name': child.name,
        };
      }));
    });

    return results;
  })
  .subscribe(val => console.log(val));

This will print the following (an array containing objects as a single emission):
[ { parentId: 1, name: 'child1' },
  { parentId: 1, name: 'child2' },
  { parentId: 2, name: 'child1' } ]


Q:

jquery scrolling opacity feature

I need to hide a div called "#left_column" while scrolling down a page.
The #left_column should be visible again when you begin to scroll up (not only when you are at the top of the page.)
What I need is exactly what you see here: https://www.ssense.com/women
I found this code but it is only visible again when I am at the top of the page and another issue is when you scroll fast, it does not respond.
var target = $('#left_column'); var targetHeight = target.outerHeight(); $(document).scroll(function(e){
var scrollPercent = (targetHeight - window.scrollY) / targetHeight;
if(scrollPercent >= 0){
    target.css('opacity', scrollPercent);
} });

I would very much appreciate your help on this!
Thanks in advance,

A:

You can Use ScrollTop() function in jquery to handle this job
$('#toTop').fadeIn();
var LastPos = 0;
var CurrentPos = 0;
$(window).scroll(function() {
    CurrentPos = $(this).scrollTop();

    if (CurrentPos > LastPos) {
        $('#toTop').fadeOut();
    } else {
        $('#toTop').show();
    }
    LastPos = CurrentPos;
});

jsfiddle Demo


Q:

Is is possible to make a shaped, alpha-blended dialog?

I'm making a non-rectangular dialog, modelled over an image from Photoshop (the image is the background of the dialog, and the user will see trough the transparent part of the image). I'ts like a dashboard-style window for a media-app with a few custom-drawn controls. Most of the background-image is either opaque or 100% transparent - but in between there is a thin area of partially transparent pixels, ment to blend the image smootly into the background. This works great for web-graphics, but I have not found a way to make this work for Windows windows. I'm using the Windows Template Library (WTL), msvc 2008 - and the app must run on Windows XP as well as Vista and Windows 7.
Currently, I'm simply using the opaque part of the background-image to create a GDI clipping-region, but this gives pretty rough edges.
Does anyone know about any API functions to accomplish this (part of WTL, or reachable from WTL)?

A:

Perhaps you could use layered windows? I haven't tested these with WTL but you should be able to get the effect you want.  To the best of my knowledge I don't think you can add controls to a layered window so you'll need to attach it to another (non-layered) window to use controls.


Q:

Question in proof regarding uniqueness of Hahn Banach extension

proof here
from there http://www.mat.unimi.it/users/zanco/AnFunzionale/pm5_schioppa.pdf

Why is the last equation true? $$\|\frac{f_1+f_2}{2}\|_X=1$$

$f_1$, $f_2$ are extensions of $f$. Does that mean $\frac{f_1+f_2}{2}\Big|_Y=f$? (Is the restriction linear?)
and because $\|f\|_Y=1$ and the norm preserving property of the Hahn Banach extension, we also have $$\|\frac{f_1+f_2}{2}\|_X=1$$
Is this the reason?

A:

$\|\frac {f_1+f_2} 2\|_X \leq \frac {\|f_1\|_X+\|f_2\|_X} 2=\frac { 1+1} 2=1$ and $\|\frac {f_1+f_2} 2\|_X \geq \|\frac {f_1+f_2} 2\|_Y=\|f\|_Y=1$. [The norm on $X$ is greater than or equal to the norm on $Y$: this is immediate from the fact that supremum of a larger set is larger].


Q:

"I very like it" is right or wrong?

I heard a lot of non-native speakers said "I very like it".
I think "very" in this case is adverb and means "extremely" Source.
It can be written as "I extremely like it".
But I heard that people in some forums think it is wrong Forum
I personally prefer to say "I really like it".
SO, "I very like it" is right or wrong?

A:

In general we refer to adverbs as a single category, but it's really three different concepts together: adjective-modifiers, verb-modifiers, and adverb-modifiers. Most adverbs can fill all three of these roles, so in English they're conflated into one group. But here you've stumbled onto one of the exceptions.
"Very", "extremely", and a few others can modify adjectives and other adverbs, but they cannot modify verbs directly. So you could say "I very much like this", or even use a different adjective-derived adverb as in "I certainly like this", but not *"I very like this" or *"I extremely like this".