text:
Q: iOS 11: Update User Location Coordinates In Background on Interval I have recently picked up Swift again and I'm working on an app that requires me to get the user coordinates on an interval for the most accurate pull. My app is authorized to always track the user location. My issue is figuring out how exactly I get the coordinates updates to fire and as well as accepting that into my app running in the background.
I have explored in the AppDelegate file under the background function but I was able to get execute the update location via This Script although it resulting in a very fast pull and the timer adjustments didn't seem to work. It kept the energy impact:High so I would like to find aless impact logic. Hoping some one will be able to assist.
Please see .Swift source below.
//
//  ViewController.swift
//
//
//  Created by Truman  on 10/20/17.
//  Copyright © 2017 . All rights reserved.
//

import UIKit
import Foundation
import CoreLocation
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate {

    @IBOutlet var date: UILabel!
    @IBOutlet var lastLocation: UILabel!
    @IBOutlet var currentLocation: UILabel!
    @IBOutlet var imageConnectionStatus: UIImageView!

    @IBOutlet var lastLocationMap: MKMapView!

    //Get Current Date - Tru
    private let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()

        formatter.dateStyle = .medium
        formatter.timeStyle = .short
        return formatter
    }()

    //Location Declaration
    let locationManager = CLLocationManager()

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

    override func viewDidLoad() {
        super.viewDidLoad()
        // Start View Did Load

        //Setup location manager
        // If location services is enabled get the users location
        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.activityType = .otherNavigation
            locationManager.requestWhenInUseAuthorization()
            locationManager.requestAlwaysAuthorization()
            //locationManager.startUpdatingLocation()
            // Print out the location to the console
        }

        self.date.text = UserDefaults.standard.string(forKey: "savedDate")
        self.lastLocation.text = UserDefaults.standard.string(forKey: "savedLocation")

        var setLocation : String
        var dataLastLocation : String

        //Save device location.
        //saveLocation()

        let initialLocation = CLLocation(latitude: 33.4641856959831, longitude: -111.919245965591)
        centerMapOnLocation(location: initialLocation )
        //End View Did Load
    }

    var activelocation : String = ""

    //Did update locations Method
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){

        let location = locations[locations.count - 1]
        let currentLongitude = location.coordinate.longitude
        let currentLatitude = location.coordinate.latitude

        if location.horizontalAccuracy > 0 {
            locationManager.stopUpdatingLocation()
            currentLocation.text = "\(location.coordinate.latitude),\(location.coordinate.longitude)"

            //print("longitude = \(location.coordinate.longitude), latitude = \(location.coordinate.latitude)")

            // Need to use Current User Location vs Last Seen location in Maps URLS Below
            activelocation =  "http://maps.google.com/?saddr=\(UserDefaults.standard.string(forKey: "savedLocation")!)&daddr=\(currentLatitude),\(currentLongitude)"

            self.locationManager.allowsBackgroundLocationUpdates = true

        }

    }

    //Setting Saved data values--
    func setPersistent(){
        let defaults = UserDefaults.standard

        let when = DispatchTime.now() + 5 // change 2 to desired number of seconds
        DispatchQueue.main.asyncAfter(deadline: when) {

            let oldDate = self.date.text
            defaults.set(oldDate, forKey: "savedDate")
            self.date.text = oldDate
            print(UserDefaults.standard.string(forKey: "savedDate"))

            //locationManager.startUpdatingLocation()

            let oldLocation = self.currentLocation.text
            defaults.set(oldLocation, forKey: "savedLocation")
            self.lastLocation.text = "Saved Location:\(oldLocation)"
            // print("this is the old location:\(oldLocation)")
            print(UserDefaults.standard.string(forKey: "savedLocation"))

            let saveDate = UserDefaults.standard.object(forKey: "saveLast")
            let saveLastLocation = UserDefaults.standard.object(forKey: "saveLastLocation")

        }

    }

    func saveLocation(){

        // print("longitude = \(location.coordinate.longitude), latitude = \(location.coordinate.latitude)")
    }

    //Did Fail Update
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error){
        print(Error.self)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

                //Get Current Date and time.
                func getTodayString() -> String{

                    let date = Date()
                    let calender = Calendar.current
                    let components = calender.dateComponents([.year,.month,.day,.hour,.minute,], from: date)

                    let today_string = String(month)

                    return today_string

                }

                let today : String

                today = getTodayString()
                UserDefaults.standard.set("\(today)", forKey: "saveLast")

                //self.lastLocation.text = "hello"

                self.locationManager.startUpdatingLocation()
                self.setPersistent()

            } else if state == false {

                let when = DispatchTime.now() + 2 // change 2 to desired number of seconds
                DispatchQueue.main.asyncAfter(deadline: when) {

                }

            }

        //    locationManager.startUpdatingLocation()
        let now = NSDate()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMMM d, y hh:mm:ss"
        let month = dateFormatter.string(from: now as Date)
        //self.date.text = dateFormatter.string(from: now as Date)

        //Get Current Date andd time.
        func getTodayString() -> String{

            let date = Date()
            let calender = Calendar.current
            let components = calender.dateComponents([.year,.month,.day,.hour,.minute,], from: date)

            let today_string = String(month)

            return today_string

        }

        let today : String

        today = getTodayString()
        UserDefaults.standard.set("\(today)", forKey: "saveLast")

    }

}


text:
Q: How to use the Google Analytics API v3 > analytics.management.uploads.uploadData methode in api explorer i fill in the needed data:
- accountId: 2465955
- webPropertyId: UA-2465955-20
- customDataSourceId: oI7aVdXXRJa_ZA5QNvLkVQ
Request:
POST https://www.googleapis.com/analytics/v3/management/accounts/2465955/webproperties/UA-2465955-20/customDataSources/oI7aVdXXRJa_ZA5QNvLkVQ/uploads?fields=customDataSourceId&key={YOUR_API_KEY}

i grant the user access to see and edit data in analytics. after this i get the error:
    400

- Hide headers -

cache-control:  private, max-age=0
content-encoding:  gzip
content-length:  160
content-type:  application/json; charset=UTF-8
date:  Wed, 05 Sep 2018 09:01:04 GMT
expires:  Wed, 05 Sep 2018 09:01:04 GMT
server:  GSE
vary:  Origin, X-Origin

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "badRequest",
    "message": "Upload request URL should start with https://www.googleapis.com/upload/analytics/..."
   }
  ],
  "code": 400,
  "message": "Upload request URL should start with https://www.googleapis.com/upload/analytics/..."
 }
}

i dont know how to send a propper request, hope somone can help me!
thx

A: The Uploads: uploadData method is used to Upload data for a custom data source.
You can not use Google apis exploerer to upload files.  It does not have that functionality it is only meant for testing.
You will need to code this yourself here is a nice example in java directly from the documentation
/*
 * Note: This code assumes you have an authorized Analytics service object.
 * See the Data Import Developer Guide for details.
 */

// This request uploads a file for the authorized user.
File file = new File("data.csv");
InputStreamContent mediaContent = new InputStreamContent("application/octet-stream",
    new FileInputStream(file));
mediaContent.setLength(file.length());
try {
  analytics.management().uploads().uploadData("123456",
      "UA-123456-1", "122333444455555", mediaContent).execute();
} catch (GoogleJsonResponseException e) {
  System.err.println("There was a service error: "
      + e.getDetails().getCode() + " : "
      + e.getDetails().getMessage());
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Scaling problem with fontspec package and \footnote. footnote does not scale properly with using fontspec. Any idea how to solve this problem? Already tried realscripts and xltxtra but no luck.
Thanks,
\documentclass[12pt]{article}
\usepackage[english]{babel}
\usepackage{fontspec}
\setmainfont{Times New Roman}
\newcommand{\phont}[1]{\fontspec[Scale=#1]{Times New Roman}}

\begin{document}\noindent

{\phont{1} test\footnote{test}}\\
{\phont{2} test\footnote{test}}\\
{\phont{3} test\footnote{test}}\\
{\phont{1}test\textsuperscript{1}}\\
{\phont{2}test\textsuperscript{2}}\\
{\phont{3}test\textsuperscript{3}}

\end{document}

A: It's "by design". LaTeX's \footnote sets its footnote mark in font \normalfont. However you want the current text font. \textsuperscript keeps the current font except the font size.
The behaviour of LaTeX can be changed by redefining \@makefnmark:
\documentclass[12pt]{article}
\usepackage[english]{babel}
\usepackage{fontspec}
\setmainfont{Times New Roman}
\newcommand{\phont}[1]{\fontspec[Scale=#1]{Times New Roman}}

\makeatletter
\renewcommand*{\@makefnmark}{%
  \hbox{%
    \@textsuperscript{%
      % \normalfont % removed
      \selectfont % added
      \@thefnmark
    }%
  }%
}
\makeatother

\begin{document}

\vspace*{\fill}

\noindent
{\phont{1} test\footnote{test}}\\
{\phont{2} test\footnote{test}}\\
{\phont{3} test\footnote{test}}\\
{\phont{1}test\textsuperscript{1}}\\
{\phont{2}test\textsuperscript{2}}\\
{\phont{3}test\textsuperscript{3}}

\end{document}


text:
Q: Errno::EBADF: Bad file descriptor with ruby net/http What can cause while making an HTTP connection to return EBADF (Bad file descriptor).
Here is my following code wherein the HTTP connection is made. Although the error is very less now(happening very less) but before I put those error on rescue I need to understand what is the reason for the EBADF
def make_http_request(url, headers={})
  uri = URI(url)
  Net::HTTP.start(uri.host, uri.port) do |http|
    req = Net::HTTP::Get.new(uri, headers)
    resp = http.request(req)
    if resp.code.to_i != 200
      logger.error "Retrieve #{resp.code} with #{url} and #{headers}"
      return false
    end
    return resp.body
  end
rescue SocketError, Net::ReadTimeout, Errno::ECONNREFUSED => e
  logger.error "make_http_request #{url} with #{headers} resulted in #{e.message} \n #{e.backtrace}"
  return false
end

I have a feeling that connect syscall is receiving an FD which ain't valid at that given point in time. But still unable to understand how can that happens.
If it helps the code is used in an application that operates with multiple threads.
In a nutshell, the definition of the above method looks like this...
module Eval
  def make_http_request(url, headers={})
    ...
    ...
    ..
  end

  def request_local_endpoint(url, headers)
     response = make_http_request(url, headers)
     response && response.fetch('bravo',nil)
  end

  def request_external_endpoint(url, headers)
    response = make_http_request(url, headers)
    response && response.fetch('token',nil)
  end
end

class RequestBuilder
  include Eval
  attr_reader :data
  def initialize(data)
    @data = data
  end

  def start
    token = request_external_endpoint('http://external.com/endpoint1',{'Content-Type'.freeze => 'application/json', 'Authorization' => 'abcdef'})
    return unless token

    result = request_local_endpoint('http://internal.com/endpoint1',{'Content-Type'.freeze => 'application/json'})
    return result
  end
end

10.times {
   Thread.new { RequestBuilder.new('sample data').start }
}


text:
Q: PrimeNG dataTable rowspan example I am using PrimeNG dataTable.  I would like to have some rows span several columns within the content of the table.  There is a great example for doing this within the headers (http://www.primefaces.org/primeng/#/datatablegroup) but I'm not sure how to do this within the content of the table.  The number of rows will be dynamic (some may have Weather and Rain, others may have Rain, Water Level, and Streamflow).  Can this be done?
visual for rowspan > 1

A: I faced the same problem. I couldn't really figure out a native solution and so I did this.

            <template let-col let-mainVO="rowData">

{{mainVO[col.field].main_title}}

                    {{c.title}}
                    {{c.price}}

Discounts:

                    {{d.title}}
                    {{d.price}}

                </template>

            <template>
                Delete
            </template>

Here is my json:
 this.checkout =
        {
            Message: "CheckoutList",

            items: [
                {
                    mainVO:{

                        main_title: "Value Pack Combo",

                        childVO: [
                            {
                                title: "Financial e-Tutorial",
                                price: "$55"
                            },

                            {
                                title: "e-Tutorial",
                                price: "$75"
                            },
                            {
                                title: "Ratios e-Tutorial",
                                price: "$85"
                            },

                            {
                                title: "economics e-Tutorial",
                                price: "$95"
                            }
                        ],
                        discounts: [
                            {
                                title: "Discount price 1",
                                price: "$120"
                            },
                        ]
                    },

                    quantity: "1",

                    price: "300",
                    currency: "CAD"

                },
                {
                    mainVO:{

                        main_title: "Securities Pack Combo",

                        childVO: [
                        {
                            title: "atios e-Tutorial",
                            price: "$55"
                        },

                        {
                            title: "omicsrial",
                            price: "$75"
                        },
                        {
                            title: "e-Tutorial",
                            price: "$85"
                        },

                        {
                            title: "Micro Tutorial",
                            price: "$95"
                        }
                        ],
                        discounts: [
                        {
                            title: "Discount price 1",
                            price: "$120"
                        },
                        ]
                    },

                    quantity: "1",

                    price: "300",
                    currency:"CAD"
                },
            ],

        }


text:
Q: Can the iPad 2 be used for everyday telephony? Is it possible to use the iPad 2 as a kind of oversized mobile phone for everyday use?

*

*Using the 3G functionality available in some models?

*Using VoIP through WLAN?

*Using other means?

*With or without additional gadgets like headsets

and I mean not just theoretically possible, but really feasible with decent audio quality and a pleasant experience even for long calls.
Does anybody have experience with this?

A: There are numerous possibilities outside Skype.
First; the iPad fully supports the three ring headset that Apple sells. Both the stock Apple Earphones that ship with every iPhone, and even the Apple In-Ear Headphones. Meaning that you can use third ring microphone for any/all input methods. And, of course, all iPads have built-in speakers and microphones, so you can even use it in a "Speaker Phone" style of use.
If you have access to a Asterisk or similar SIP PBX server, then you have access to a myriad of Softphone applications, many of which are very capable and support all the latest features (namely backgrounding) including 3G calling where applicable. Take a gander at AppShopper.com's list of results when searching for "softphone".
While not an official recommendation because I haven't used it personally, I do give a nod to Counterpath's Bria app, because I've used Counterpath's SIP clients on the desktop for years.

A: As long as you restrict yourself to Skype it might just work. The recent Skype update brought Bluetooth support so you could just use a headset to make phone calls.
Ordinary phone calls are not possible though, even on the 3G models (they only support data connections).


text:
Q: PCA to select features for Linear regression in Pipeline I have a dataset with some numeric and categorical variables. I tried to preprocess categorical variables with pandas dummies in order to scale the data with StandardScaler. However, some columns also have missing values (mostly categorical) so I used imputer in the pipeline though it still generates the error:
Input contains NaN, infinity or a value too large for dtype('float64').

My code to preprocess the data is shown below.
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer

y = df["SalePrice"]
X = df.drop(["SalePrice", "PoolQC"], axis = 1)
X_dummies = pd.get_dummies(X)

X_train, X_test, y_train, y_test = train_test_split(X_dummies, y, test_size=0.30, random_state=0)

pipeline = Pipeline([("imputer", SimpleImputer(missing_values='NaN', strategy='most_frequent')), ('scaling', StandardScaler()),('pca', PCA(n_components=157, whiten=True)), ('regr', LinearRegression())])
pipeline.fit(X_train, y_train)

The dataset df has the following columns.
df.info()

Data columns (total 81 columns):
 #   Column         Non-Null Count  Dtype
---  ------         --------------  -----
 0   Id             1460 non-null   int64
 1   MSSubClass     1460 non-null   int64
 2   MSZoning       1460 non-null   object
 3   LotFrontage    1201 non-null   float64
 4   LotArea        1460 non-null   int64
 5   Street         1460 non-null   object
 6   Alley          91 non-null     object
 7   LotShape       1460 non-null   object
 8   LandContour    1460 non-null   object
 9   Utilities      1460 non-null   object
 10  LotConfig      1460 non-null   object
 11  LandSlope      1460 non-null   object
 12  Neighborhood   1460 non-null   object
 13  Condition1     1460 non-null   object
 14  Condition2     1460 non-null   object
 15  BldgType       1460 non-null   object
 16  HouseStyle     1460 non-null   object
 17  OverallQual    1460 non-null   int64
 18  OverallCond    1460 non-null   int64
 19  YearBuilt      1460 non-null   int64
 20  YearRemodAdd   1460 non-null   int64
 21  RoofStyle      1460 non-null   object
 22  RoofMatl       1460 non-null   object
 23  Exterior1st    1460 non-null   object
 24  Exterior2nd    1460 non-null   object
 25  MasVnrType     1452 non-null   object
 26  MasVnrArea     1452 non-null   float64
 27  ExterQual      1460 non-null   object
 28  ExterCond      1460 non-null   object
 29  Foundation     1460 non-null   object
 30  BsmtQual       1423 non-null   object
 31  BsmtCond       1423 non-null   object
 32  BsmtExposure   1422 non-null   object
 33  BsmtFinType1   1423 non-null   object
 34  BsmtFinSF1     1460 non-null   int64
 35  BsmtFinType2   1422 non-null   object
 36  BsmtFinSF2     1460 non-null   int64
 37  BsmtUnfSF      1460 non-null   int64
 38  TotalBsmtSF    1460 non-null   int64
 39  Heating        1460 non-null   object
 40  HeatingQC      1460 non-null   object
 41  CentralAir     1460 non-null   object
 42  Electrical     1459 non-null   object
 43  1stFlrSF       1460 non-null   int64
 44  2ndFlrSF       1460 non-null   int64
 45  LowQualFinSF   1460 non-null   int64
 46  GrLivArea      1460 non-null   int64
 47  BsmtFullBath   1460 non-null   int64
 48  BsmtHalfBath   1460 non-null   int64
 49  FullBath       1460 non-null   int64
 50  HalfBath       1460 non-null   int64
 51  BedroomAbvGr   1460 non-null   int64
 52  KitchenAbvGr   1460 non-null   int64
 53  KitchenQual    1460 non-null   object
 54  TotRmsAbvGrd   1460 non-null   int64
 55  Functional     1460 non-null   object
 56  Fireplaces     1460 non-null   int64
 57  FireplaceQu    770 non-null    object
 58  GarageType     1379 non-null   object
 59  GarageYrBlt    1379 non-null   float64
 60  GarageFinish   1379 non-null   object
 61  GarageCars     1460 non-null   int64
 62  GarageArea     1460 non-null   int64
 63  GarageQual     1379 non-null   object
 64  GarageCond     1379 non-null   object
 65  PavedDrive     1460 non-null   object
 66  WoodDeckSF     1460 non-null   int64
 67  OpenPorchSF    1460 non-null   int64
 68  EnclosedPorch  1460 non-null   int64
 69  3SsnPorch      1460 non-null   int64
 70  ScreenPorch    1460 non-null   int64
 71  PoolArea       1460 non-null   int64
 72  PoolQC         7 non-null      object
 73  Fence          281 non-null    object
 74  MiscFeature    54 non-null     object
 75  MiscVal        1460 non-null   int64
 76  MoSold         1460 non-null   int64
 77  YrSold         1460 non-null   int64
 78  SaleType       1460 non-null   object
 79  SaleCondition  1460 non-null   object
 80  SalePrice      1460 non-null   int64
dtypes: float64(3), int64(35), object(43)
memory usage: 924.0+ KB

Am I on the right way or not? How can I deal with this error? Can I implement it somehow in the pipeline?

A: you can access the pca by pipeline.named_steps['PCA']
I fixed the errors in the pipeline for imputer
Only get dummies the category columns
df_cat=pd.get_dummies(df[cat_columns])            X=pd.concat(Df_numeric, df_cat, axis=1)
   df=pd.read_csv('https://raw.githubusercontent.com/eric-bunch/boston_housing/master/boston.csv')

y = df['MDEV'].astype(float)*1000

X = df.drop(["MDEV"], axis = 1)
#X_dummies = pd.get_dummies(X)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0)

pipeline = Pipeline([("imputer", SimpleImputer(missing_values=np.nan ,strategy='most_frequent')), ('scaling', StandardScaler()),('pca', PCA(n_components=13,whiten=True)), ('regr',LinearRegression())])
pipeline.fit(X_train, y_train)

pca = pipeline.named_steps['pca']

pca.fit(X)
pca_features=pca.transform(X)

xs = pca_features[:,0]

# Assign 1st column of pca_features: ys
ys = pca_features[:,1]

# Scatter plot xs vs ys
plt.scatter(xs, ys)
plt.axis('equal')
plt.show()


text:
Q: Changing tracks to vectors in a grid This is a version of a question that I posted on the GRASS list, but I didn't get any suggestions there. I would like to overlay a grid (cell size about 500 m x 500m) over an animal track created from hourly locations.  For each cell that contains a track segment I want to record a direction vector which represents the direction that the animal was traveling when it passed through that cell.
I tried using the GRASS command "v.to.rast use=dir", which should create a directional vector in every raster cell that the track passes through.  It almost works, but the command does not seem to respect the order of the track.  It seems just as likely to classify a particular segment as having a direction of NE as to classify the same segment as SW (180 degrees opposite) and I couldn't see any consistency to how the directions were chosen, although I may have missed something.  Another challenge is that the animal often re-crossed its own track so that individual grid cells may contain more than one track segment--in those cases I want to sum the direction vectors using regular vector algebra.
I am new to GRASS and a bit overwhelmed, and I would be very grateful for any suggestions that would get me started in the right general direction.


text:
Q: Create a custom event like 'click' for longtap I want to make a custom event which I can use like
$('.entry').on('click', function().......

I need it for detecting a longtap for mobile devices. I want to call it like this:
$('.entry').on('longtap', function().......

I read a lot about creating events but the most ways are with bind and trigger. So is there a way to do this?

A: Here is a way to implement long tap:

var clickStart;

document.getElementById("cool_button").addEventListener('mousedown', function() {
  console.log('mouse down');
  this.clickStart = new Date().getTime();
});

document.getElementById("cool_button").addEventListener('mouseup', function() {
  console.log('mouse up');
  if ((new Date().getTime() - this.clickStart) >= 1000) {
    console.log('this is a long tap');
  }
});
<button id="cool_button">i'm a long tap button</button>

A: *

*You may use one of the handmade solutions, provided here.

*You may attach it as third-party script.

*There is a special taphold event for jQuery Mobile.

A: As said here , you don't need to create a custom event for longtap, you only need js timer and two already exsiting events like mouseup, mousedown:
var pressTimer;

$(".entry").mouseup(function(){
  clearTimeout(pressTimer);
  // Clear timeout
  return false;
}).mousedown(function(){
  // Set timeout
  pressTimer = window.setTimeout(function() {
  console.log("hi!")
  },1000);
  return false;
});

I made an example for you
https://jsfiddle.net/sOoN92/74rbc2ph/


text:
Q: Error in glm.fit when using a tweedie distribution with log link When running glm in R using tweedie and log link, I run into

"Error in glm.fit ... NA/NAN/INF in x"

I have tried using different distributions and links. I have also tried adding 1 to the response because it is insurance data with lots of 0s.
I have already checked for na's, nan's, and inf values and have none in my dataset (or have already corrected for them).
Here is the code I have:
fit = glm(y~x, data=data1,
             family=tweedie(var.power=1.6, link.power=0), weights=weights)


text:
Q: Cordova / Phonegap app (lots of images) dealing with memory warnings I am trying to wrap my website into an app that I made with AngularJS.
I got a website with lots of "cards" divs, and each of them hv an image on them.
you can find the link here: cow.aforadrian.com
screenshot of what i did in the web version
each page will hv about 100 "cards" with each unique image, loading from local JSON file. It went well in the browser
I package all the images locally into an app.
It worked all good on iOS simulator and even on my new iPad Air.
But then I realise it wont work in other devices with lesser memories.
It averagely took up to 260MB ram... and sometimes go way up to 500MB...
I tried to disable all css visual or transformation effects but it didnt help much.
At first I thought it was the size of the images, but I hv checked and try using small thumbnail to test, the memory issue still persists.
so I guess it had to do with how the screen handles the rendering of this amount of images.
I m not very good with angularjs and barely get this site up and running. it got me scratching my head on how to fix this. I never worked with an app before so the memory issue really didnt occur to me and i dun hv a concept of how to deal with this.
Other threads hv talked about similar issues on creating image carousel, that one should lazyload the image before and destroy the image after. Yet I am not sure if this is the right approach for me, and I am not sure how to achieve this.
UPDATE:
I am using ng-repeat to load image links pointing to a local image folder.
Is this the reason why it is using up a lot of RAM/Memory? are there better way to achieve this? will it help if i revamp the website in ionic framework instead of pure Angularjs + Cordova?


text:
Q: How do I convert a string to a symbol for use as a key in the Lisp "assoc" function? I have this association-list in Common Lisp:
(defvar base-list (list (cons 'a 0) (cons 2 'c)))

I have to call assoc when my argument is of type string.
For the pair (A . 0) I have to convert "a" to a symbol, and for the pair (2 . C) I have to convert "2" to a symbol. How can I do that?
This should work like this:
CL-USER 28 : 1 > (assoc (convert-string-to-symbol "a") base-list)
(A . 0)
CL-USER 28 : 1 > (assoc (convert-number-to-symbol "2") base-list)
(2 . C)

I tried using intern but got NIL:
CL-USER 29 : 1 > (assoc (intern "a") base-list)
NIL

A: You were close with intern; you just had the case wrong. Try this:
> (assoc (intern "A") base-list)
(A . 0)

Note that here the name-as-string is capitalized.
Alternately, you could use find-symbol to look for an existing symbol by name:
> (assoc (find-symbol "A") base-list)
(A . 0)

The key here is that when you wrote your original defvar form, the reader read the string "a" and—by virtue of the current readtable case—converted the symbol name to be uppercase. Symbols with names of different case are not equal. It just so happens that at read time the reader is projecting what you wrote (lowercase) to something else (uppercase).
You can inspect the current case conversion policy for the current reader using the readtable-case function:
> (readtable-case *readtable*)
:UPCASE

To learn more about how the readtable case and the reader interact, see the discussion in section 23.1.2 of the Hyperspec.

A: The function you want is called read-from-string:
CL-USER> (read-from-string "a")
A
1
CL-USER> (read-from-string "2")
2
1
CL-USER>

Note that solutions based on using intern or find-symbol would not work for strings representing numbers (e.g., "2") on most implementations.


text:
Q: Omnet++ "Errors Exist in required project(s)" I'm trying to run the network simulation which I have built in omnet++ ver 5.6.2 to gather the data, but every time I try and run it I get the error: "Errors exist in required project(s) inet"
I have got inet open and I have managed to import the inet modules into my simulation so I don't understand how I have got this error coming up especially as I have run the simulation successfully on other machines
error


text:
Q: Item in MemoryCache too big? I'm trying to understand the sizing algorithm of the MemoryCache class in C#.
I was thinking that an item with a short key (a one-character string) and a small value (ie. bool) will occupy a tiny amount of memory, but my tests proved me wrong.
This is the code I used to test it:
Console.WriteLine("Mem before creating Cache:" + GC.GetTotalMemory(true).ToString());
MemoryCache cache = new MemoryCache("testcache");
Console.WriteLine("Mem after creating Cache:" + GC.GetTotalMemory(true).ToString());

long tinyAvg=0;
int sampleSize = 500;
for (var i = 0; i < sampleSize; i++)
{
    var memBefore = GC.GetTotalMemory(true);
    cache.Add(i.ToString() , true, null);
    var memAfter = GC.GetTotalMemory(true);
    var overhead = memAfter - memBefore;
    tinyAvg += overhead;
    //Console.WriteLine("Mem overhead for adding tiny item:" + overhead.ToString());
}
Console.WriteLine("Average for tiny item: " + tinyAvg / sampleSize);

Running this code, I get an average of 129 bytes / item in the cache, which looks to me much too large.
Note that I'm using GC.GetTotalMemory() for profiling. I know it might not give the exact numbers, but a rough estimation is also enough.
Why is the cache item so big for such a small key/value pair? Is there any way of making it smaller?
BTW - I know this is a Micro-Benchmarking, and I know that memory is cheap these days. This is a sample which represents a much larger cache, with huge keys,  millions of items, and limited RAM, so we need to find a solution for this...
Thanks!


text:
Q: Rewrite rule from old link to new link on same domain I tried to make a redirect from:

www.myUrl.nl/my-old-link

to:

www.myUrl.nl/my-new-link

I already added some redirects in my Apache and those are working fine.
I've tried:
RewriteCond %{REQUEST_URI} ^/my-old-link$
RewriteRule (.*) /my-new-link [R=301]

and
RewriteCond %{QUERY_STRING} ^/my-old-link$
RewriteRule (.*) /my-new-link [R=301]

But both don't work. I just stay on www.myUrl.nl/my-old-link.

A: You should only need:
RewriteEngine On
RewriteRule ^/my-old-link /my-new-link [R,L]

If in your .htaccess file ^/my-old-link should be ^my-old-link


text:
Q: Most frequent value per aggregated group or rule in pandas I have the following toy dataset:
mydf = pd.DataFrame({'id':[1,2,3,4,5,6,7,8],
                     'text':['Dax','Dax','Dax','Pau','Tarbes','Tarbes','Tarbes','Muret'],
                     'group':['meme','meme','gif','pic','gif','all','gif','pic']})
mydf
    id  text    group
0   1   Dax     meme
1   2   Dax     meme
2   3   Dax     gif
3   4   Pau     pic
4   5   Tarbes  gif
5   6   Tarbes  all
6   7   Tarbes  meme
7   8   Muret   pic

And I want to aggregate by text selecting only the most frequent value of group, except in the case that group is all, then try to prefer other options instead of all if possible.
This is the expected result:
    text    group
0   Dax     meme
1   Pau     pic
2   Tarbes  gif
3   Muret   pic

I tried this, but it's a little messy (not returning a df) and I don't figure out how to put the all condition:
mydf.groupby(['text'])['group'].max()

text
Dax       meme
Muret      pic
Pau        pic
Tarbes     gif
Name: group, dtype: object

Please any help or guidance will be greatly appreciated.

A: Try with
out = mydf.groupby('text')['group'].agg(lambda x : x.mode().loc[lambda x : x!='all'].iloc[0] if len(x)>1 else x.mode().iloc[0])
Out[111]:
text
Dax       meme
Muret      pic
Pau        pic
Tarbes     gif
Name: group, dtype: object


text:
Q: Ruby on Rails: How to display previous values in select_tag this is my first question on stackoverflow and I'm new to Ruby on Rails, so I'm really sorry if I'm asking the question wrong.
My problem: I have two classes (word and category) and now I try to assign several categories to one word over the variable syntactical_category, for that I use a select_tag. This works nicely, when the user creates a new word as you can see in this snippet from the command line:
Parameters: {
  "utf8"=>"✓",
  "authenticity_token"=>"EwGk/QrOma4JGJhSBjAT6fW9BqvuCJCEPYgNC9i/okOuQZBbh1ArNEfvuHvDRwY0Q2tABYTc/b3n3tAIlQmJRg==",
  "word"=>{
    "name_de"=>"This is a test",
    "description_de"=>"Test Description",
    "syntactical_category"=>"5721e7fa8cc4b3285c000004",
    "semantical_categories_ids"=>["57921a358cc4b36e42000001"]
  },
  "locale"=>"de"
}

But when the user tries to edit a word afterwards, the select_tag ignores the value(s) from the database and only displays the first category of all potential categories and overwrites the old value(s) if the user submits the word again. This is not what i want.
Does anybody have a solution for this problem?
I'm using Ruby 2.2.3, RubyonRails 4.2.4 and MongoDB 3.0.9, Mongoid and haml if this information helps you.
Please find below my code.
word.rb
class Word
  include Mongoid::Document
  include Mongoid::Attributes::Dynamic
  include MultiLanguageText

  belongs_to :syntactical_category, class_name: "Category", inverse_of: nil, :autosave => true
  has_and_belongs_to_many :semantical_categories, class_name: "Category", inverse_of: nil, :autosave => true
  field :name_de, type: String
  field :name_en, type: String
  field :description_de, type: String
  field :description_en, type: String
end

words_controller.rb
class WordsController < ApplicationController
  helper MultiLanguageText

  def index
    @word = Word.all
  end

  def show
    @word = Word.find(params[:id])
  end

  def new
    @word = Word.new
  end

  def create
    @word = Word.new(word_params)

    respond_to do |format|
      if @word.save
        format.html { redirect_to @word, notice: t("word_create_success") }
        format.json { render :index, status: :created, location: @word }
      else
        format.html { render :new }
        format.json { render json: @word.errors, status: :unprocessable_entity }
      end
    end
  end

  def edit
    @word = Word.find(params[:id])
  end

  def update
    @word = Word.find params[:id]
    @word.update_attributes(word_params)

    respond_to do |format|
      if @word.update(word_params)
        format.html { redirect_to @word, notice: t("word_update_success") }
        format.json { render :index, status: :ok, location: @word }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @word = Word.find(params[:id])
    @word.destroy
    flash[:notice] = t(:delete_confirmation)
    redirect_to words_path
  end

  def word_params
    allow = [:name_de, :name_en, :description_de, :description_en, :syntactical_category, {:semantical_categories_ids => []}]
    params.require(:word).permit(allow)
  end
end

words/_form.html.haml
= form_for @word do |w|
  .field
    .input-append
      = select_tag 'word[semantical_categories_ids][]', options_for_select(Category.where(category_type: 'semantic').where(:name_de.exists => true).collect{|c| [c.name_de, c.id]})

Thank you in advance for your help!

A: Just pass @word.semantical_categories_ids after the collection
= select_tag 'word[semantical_categories_ids][]', options_for_select(Category.where(category_type: 'semantic').where(:name_de.exists => true).collect{|c| [c.name_de, c.id]}, @word.semantical_categories_ids)

and I think it should accept multiple values. If yes add multiple: true at the end

A: I think you have multiple selection select_tag
So, you have to do below
= select_tag 'word[semantical_categories_ids][]', options_for_select(YOUR_COLLECTION,ARRAY_OF_SELECTED_VALUES),{multiple: true}
Note: Add ,{multiple: true} to your select_tag

A: i found a solution for my problem. I'm not sure if this is "the way to do it" but for me it works fine.
  - @word['semantical_categories_ids'] = [''] if !@word['semantical_categories_ids'].is_a? Array
  - @word['semantical_categories_ids'].each do |entry|
    = select_tag 'word[semantical_categories_ids][]', options_for_select(Category.where(category_type: 'semantic').where(:name_de.exists => true).collect{|c| [c.name_de, c.id]}, entry)


text:
Q: Arduino: If/Else issues Situation:  I have a webpage that has two buttons on it.  One sends to the PubNub channel a JSON string of {"lightRight":"1"} and one sends {"lightRight":"0"}, regardless of what I do in the Arduino Sketch I cannot make it into the "on" portion of the void light function.
I know from the serial output of the arduino that I am receiving communication from the web page.  If I flip my boolean values to off then I am able to get the "LED HIGH" output but then no longer can I get the "led low".
The code I am trying to adapt can be found here.
https://gist.github.com/ianjennings/ada8fb1a91a486a0c73e

It is very possible I have hacked out to much code from the examples that is why I am including it, but running the stock code I cannot seem to get this to work.
I am not a developer, so I am very sorry if I do not call things as their proper terms.  I will learn from correction.
#include <PubNub.h>
#include <SPI.h>
#include <EthernetV2_0.h>
#include <string.h>
#include <Servo.h>

byte mac[] = { MAC was here };
byte gateway[] = { Gate was here };
byte subnet[] = { Sub was here };

IPAddress ip(IP was here);

char pubkey[] = "Key was here";
char subkey[] = "Key was here";
char channel[] = "Channel was here";

int lightRight = 5;
int lightRoom = 6;
int lightGarage = 7;

int i;

EthernetClient *client;

#define W5200_CS  3
#define SDCARD_CS 4

void setup()
{

  pinMode(SDCARD_CS,OUTPUT);
  digitalWrite(SDCARD_CS,HIGH);

  Serial.begin(9600);
  Serial.println("Serial set up");

  while (!Ethernet.begin(mac)) {
    Serial.println("Ethernet setup error");
                blink(1000, 999999);
    delay(1000);
  }
  Serial.println("Ethernet set up");

  PubNub.begin(pubkey, subkey);
  Serial.println("PubNub set up");

  pinMode(lightRight, OUTPUT);
  pinMode(lightRoom, OUTPUT);
  pinMode(lightGarage, OUTPUT);

//  blink(100, 5);
  reset();

}

//void flash(int ledPin)
//{
//  for (int i = 0; i < 3; i++) {
//      Serial.println("flash");
//    digitalWrite(ledPin, HIGH);
//    delay(100);
//    digitalWrite(ledPin, LOW);
//    delay(100);
//  }
//}

void loop()
{

  Ethernet.maintain();

    PubSubClient *client;

  Serial.println("waiting for a message (subscribe)");
  client = PubNub.subscribe(channel);

  if (!client) {
    Serial.println("subscription error");
    return;
  }

  String messages[10];

  boolean inside_command = false;
  int num_commands = 0;

  String message = "";
  char c;

  while (client->wait_for_data()) {

    c = client->read();

    if(inside_command && c != '"') {
      messages[num_commands] += c;
    }

    if(c == '"') {

      if(inside_command) {

        num_commands = num_commands + 1;
        inside_command = false;

      } else {
        inside_command = true;
      }

    }

    message += c;

  }
  client->stop();

  for (i = 0; i < num_commands; i++){

    int colonIndex = messages[i].indexOf(':');

    String subject = messages[i].substring(0, colonIndex);
    String valueString = messages[i].substring(colonIndex + 1, messages[i].length());
    boolean value = false;

    if(valueString == "1") {
      value = true;
    }

    if(subject == "lightRight") {
      light(lightRight, value);
    }

    if(subject == "lightRoom") {
      light(lightRoom, value);
    }

    if(subject == "lightGarage") {
      light(lightGarage, value);
    }

    if(subject == "blink") {
      blink(100, valueString.toInt());
    }

    Serial.println(subject);
    Serial.println(value);

  }

  Serial.print(message);

  Serial.println();

  delay(2000);

}

void light(int ledPin, boolean on) {
  if(on) {
    digitalWrite(ledPin, HIGH);
      Serial.println("LED HIGH");
  } else {
    digitalWrite(ledPin, LOW);
      Serial.println("led low");
  }

}

void reset() {
        Serial.println("Void reset");
  light(lightRight, false);
  light(lightRoom, false);
  light(lightGarage, false);
}

void on() {
        Serial.println("Void on");
  light(lightRight, true);
  light(lightRoom, true);
  light(lightGarage, true);
}

void off() {
        Serial.println("Void off");
  light(lightRight, false);
  light(lightRoom, false);
  light(lightGarage, false);
}

void blink(int delayn, int count) {

  for (int j=0; j <= count; j++){
    on();
    delay(delayn);
    off();
    delay(delayn);
  }

}

A: That example expects the PubNub publish to be "lightRight:1" and not {"lightRight": "1"}.


text:
Q: Serial key generation xor string encryption When I do an xor on a string I get special characters
private void btnEncryptDecrypt_Click(object sender, EventArgs e)
    {
        byte[] bytes = Encoding.UTF8.GetBytes(keyTextBox.Text);
        textTextBox.Text = string.Empty;

        foreach (byte i in bytes)
        {
            byte c = Convert.ToByte(i ^ Convert.ToByte(textBox1.Text));

            textTextBox.Text = textTextBox.Text + Convert.ToChar(c);

        }

    }

62FA7AC4 1234567890 xor to !%QV VT#7&%$#"! /.'
I want to use it for serial key generation with only alphanumeric characters
I want to pass "62FA7AC4", a date and a number between 0 and 5000 and a few random dummy numbers
Input will be "62FA7AC4"+"2500"+"21/05/2018"
Output should be something like "5QBK-J4D1-8CF6-5MW2-78FZ-2FPL-4S6S-CTGB"
What am I doing Wrong?

A: Try working with numbers, not strings:
  using System.Numerics;

  ...

  // Let's use BigInteger for arbitrary long values
  BigInteger left = BigInteger.Parse("62FA7AC4", NumberStyles.HexNumber);
  BigInteger right = BigInteger.Parse("1234567890", NumberStyles.HexNumber);

  string result = (left ^ right).ToString("X");

  Console.Write(result);

So you have
  1256AC0254

Edit: As far as I can see you want alphanumeric (i.e. Base 36 == 26 letters + 10 digits output). You can use the same approach: operate with integer(s), not string(s)
  private static Random s_Random = new Random();

  ...

  BigInteger value = BigInteger.Parse(
      "0"        +                             // we don't want negative values
      "62FA7AC4" +                             // header
       s_Random.Next(5001).ToString("0000") +  // random in [0..5000] range
       DateTime.Today.ToString("ddMMyyyy"),    // Date like 21052018
    NumberStyles.HexNumber);

Then do any xor (if you like):
 value ^= some_secret_value;

Finally represent the value in base 36:
private static String ToBase36(BigInteger value) {
  List<char> list = new List<char>();

  for (int index = 0; value > 0; value /= 36, index++) {
    if (index > 0 && index % 4 == 0)
      list.Add('-');

    BigInteger v = value % 36;

    list.Add(v < 10 ? (char)('0' + v) : (char) ('A' + v - 10));
  }

  list.Reverse();

  return string.Concat(list);
}

Test:
 BigInteger value = BigInteger.Parse(
    "0" +
    "62FA7AC4" +
    "2500" +
     DateTime.Today.ToString("ddMMyyyy"),
   NumberStyles.HexNumber);

 string result = ToBase36(value);

 Console.Write(result);

Outcome:
2443-WNC5-AVBB-M32W

Edit 2: To restore the original number
private static BigInteger FromBase36(string value) {
  BigInteger result = 0;
  BigInteger power = 1;

  for (int i = value.Length - 1; i >= 0; --i) {
    char item = value[i];

    if (item >= '0' && item <= '9') {
      result += power * (item - '0');
      power *= 36;
    }
    else if (item >= 'A' && item <= 'Z') {
      result += power * (item - 'A' + 10);
      power *= 36;
    }
    else if (item >= 'a' && item <= 'z') {
      result += power * (item - 'a' + 10);
      power *= 36;
    }
  }

  return result;
}

e.g.
BigInteger value = BigInteger.Parse(
    "0"        +
    "62FA7AC4" +
    "2500" +
     DateTime.Today.ToString("ddMMyyyy"),
   NumberStyles.HexNumber);

string result = ToBase36(value);

BigInteger back = FromBase36(result);

Console.WriteLine(string.Join(Environment.NewLine, value, result, back));

Outcome:
467412447575903165554712
2443-WNC5-AVBB-M32W
467412447575903165554712


text:
Q: How to use MDC's tab bar? I want to use this Tab system:
https://material-components.github.io/material-components-web-catalog/#/component/tabs
I read the HTML source code of the above link and implemented a tab bar.
However, how do I switch displayed contents using this tab bar? Do I need to write JavaScript?

A: Yes, it is a JavaScript library.... so you will need to import the JavaScript.
Firstly you need to install the library, installation instructions can be found here.
Next you can proceed to using the tab bar, following these instructions.
Here's a quick working demo to show it's possible, (but I wouldn't recommend using this code)

<link rel="stylesheet" href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css">

        <button class="mdc-tab mdc-tab--active" role="tab" aria-selected="true" tabindex="0">

            favorite

        </button>


text:
Q: Limiting Fps in python i want my program to do a task every x frames. However it does not seem to work, due to the fact that the timer in python seems to be inaccurate. How do i get this piece of code to obey my set framerate?
import time
fps = 5
skipticks = 1/(fps*1.0)
i= 0
nextsnap=time.clock()
print skipticks, fps
while (True):
    tim= time.clock()
    i=i+1
    # this prints the fps
    #'print 'Fps at start',i, 1/(time.time()-tim)
    # this is the sleep that limits the fps
    nextsnap+=skipticks
    sleeptime = nextsnap-time.clock()
    if (sleeptime>0):
        time.sleep (sleeptime)
    else:
        print 'took too long'
    print 'Fps at end:#', i, 1/(time.clock()-tim)

this produces on my computer:
 Fps at end:# 45 4.36627853079
Fps at end:# 46 6.44119324776
Fps at end:# 47 4.53966049676
Fps at end:# 48 4.66471670624
Fps at end:# 49 7.18312473536
Fps at end:# 50 4.34786490268
Fps at end:# 51 6.5263951487
Fps at end:# 52 4.71715853908
Fps at end:# 53 4.59636712435
Fps at end:# 54 6.87201830723
Fps at end:# 55 4.31062740848

Why are there frames that are rendered too fast? And why is the fps count inaccurate?

A: If it's about mesuring the accuracy you can have with time.clock() and time.sleep(), use something as simple as possible like:
import time

fps = 5
time_delta = 1./fps

while True:
    t0 = time.clock()
    time.sleep(time_delta)
    t1 = time.clock()
    print 1. / (t1 - t0)

What is your OS and what is the result of this simple mesure ?
If it's about cleaning your code, I would separate more clearly the FPS evaluation, the processing and the sleep call. Here is an example (the loop #0 frequency displayed should be ignored).
import time
import random
from itertools import count

fps = 5
loop_delta = 1./fps

current_time = target_time = time.clock()
for i in count():
    #### loop frequency evaluation
    previous_time, current_time = current_time, time.clock()
    time_delta = current_time - previous_time
    print 'loop #%d frequency: %s' % (i, 1. / time_delta)

    #### processing
    # processing example that sleeps a random time between 0 and loop_delta/2.
    time.sleep(random.uniform(0, loop_delta / 2.))

    #### sleep management
    target_time += loop_delta
    sleep_time = target_time - time.clock()
    if sleep_time > 0:
        time.sleep(sleep_time)
    else:
        print 'took too long'

Also, you probably want time.time() rather than time.clock(). See time.clock() vs. time.time() - accuracy answer.

A: The python documentation explains why time.sleep is not very accurate.
What os are you using?
If you are using linux, you can use powernap, which uses Linux's real-time clock (RTC) for more accurate timing.


text:
Q: Trigger a File Upload using AJAX without a form nor Jquery this works well when Getting and Sending text in JSON format. It also works well when uploading images using a form an input and a submit button.
function ajaxPromise(url, send) {

    return new Promise( function(resolve, reject) {

    var XHR = new XMLHttpRequest();

    XHR.open('POST', url);
    XHR.onload = function() {
      resolve(XHR.response); // Resolve promise with response
    };

    XHR.send(send);

    });
}

Need help in making it work without activating the submit button, for example, with the change event of the input.
input.addEventListener('change', function(e) {
    ajaxPromise('upload.php', file);
});

A: Can you try the below code
input.addEventListener('change', function(e) {
    // this.files -- Array[Files] // when multiple files are selected.
    // so Pick the first one
    ajaxPromise('upload.php', this.files[0]);
});


text:
Q: Two if statements in a for loop? class Solution:
    def transformArray(self, arr: List[int]) -> List[int]:
        x=arr
        while True:
            f=True
            for i in range(1,len(arr)-1):
                if arr[i-1]<arr[i] and arr[i]>arr[i+1]:
                    f=False
                    x[i]=x[i]-1
                    print(x[i])
                if arr[i-1]>arr[i] and arr[i]<arr[i+1]:
                    f=False
                    x[i]=x[i]+1
                    print(x[i])

            #print(x)
            x=arr
            if f==True:
                break
        return x

In the above code both the if statements don't execute , only the second one does. I have tried using elif but it still doesn't work. What am i missing here?

A: For your code, I considered two types of examples as input for the array list
For example 1, when the arr = [1, 2, 1, 4], the 2nd element is bigger than 1st and 3rd
The first if statement (if arr[i-1]<arr[i] and arr[i]>arr[i+1]:) is working, because both the conditions are met and it gives the output x = [1, 1, 1, 4]
In example 2, when the arr = [3, 2, 3, 4], the 2nd element is smaller than the 1st and 3rd
The second if statement (if arr[i-1]>arr[i] and arr[i]<arr[i+1]:) is working, because both the conditions are met and it gives the output x = [3, 3, 3, 4]
So, the working of if statements largely depends on the elements in the array. Both the if statements' purpose is totally opposite. If one satisfies the condition the other will not.
Hope my answer provides some clarification.


text:
Q: Laravel Form Request validation with custom validation Rule, didn't work to find all space characters This is my register controllers, register method:
public function register(StoreUser $request)
    {
            $user = $this->create($request->all());

            $user = User::findOrFail($user->id);

            Mail::to($user->email)->queue(new EmailVerification($user));

            return view('auth.verify-email');

    }

Here is the StoreUser Request:
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use App\Rules\allAreSpaces;

class StoreUser extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {

        return [
            'email' => 'required|email|max:64',
            'phone' => 'bail|required|numeric|phone_min|phone_max|unique:users|not_in:0',
            'password' => [new allAreSpaces, 'required', 'min:8', 'max:16', 'confirmed'],
            'password_confirmation' => 'required',
        ];

    }

    public function messages()
    {
        return [
            'email.required'     => 'Email address cannot be empty',
            'email.email'     => 'Enter a valid Email address',
            'email.max'     => 'Email address cannot exceed 64 characters',
            'email.unique'     => 'Email already exists',

            'phone.required'     => 'Mobile number cannot be empty',
            'phone.numeric'     => 'Mobile number has to be numeric',
            'phone.phone_min'     => 'Mobile number should contain a minimum 5 characters',
            'phone.phone_max'     => 'Mobile number cannot exceed 11 characters',
            'phone.unique'     => 'Mobile number already exists',
            'phone.not_in'     => 'Enter a valid mobile number ',

            'password.required'     => 'Password cannot be empty',
            'password.min'     => 'Password should contain minimum 8 characters',
            'password.max'     => 'Password cannot exceed 16 characters',
            'password.confirmed'     => 'Password mismatch.Retry',

            'password_confirmation.required'     => 'Confirm Password cannot be empty',
        ];
    }

    public function withValidator(Validator $validator)
    {

        $email = $this->request->get( 'email' );  // Start with

        $user = \App\User::Where('email', $email)->first();

        if($user && $user->activated == 0){

            $row = \App\User::find($user->id);
            $row->delete();

        }else{

            $validator->sometimes('email', 'unique:users', function ($input) {
                return true;
            });
        }

    }

}

Here is that custom Rule named 'allAreSpaces':
<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class allAreSpaces implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {

        if(strlen($value) > 0){
            if (strlen(trim($value)) == 0){
                return false;
            }
        }
        return true;

    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'Password cannot contain space character alone';
    }
}

What i want is if user type only the spaces in all password field, i want to throw the 'Password cannot contain space character alone' message.
It is working when user didn't type anything. if they typed space its not working.
how can i achieve this?
is there any other easy way to show error message if all are spaces?

A: @foo.ar,
In App\Http\Kernel.php, you can see TrimStrings middleware is applied. it will trim all white spaces. if u enter only spaces in any input, it will trim those spaces and u will end up with no values in that input.
so if u want to validate spaces, u have to add the below code in
\App\Http\Middleware\TrimStrings.php
<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;

class TrimStrings extends Middleware
{
    /**
     * The names of the attributes that should not be trimmed.
     *
     * @var array
     */
    protected $except = [
        'password',
        'password_confirmation',
    ];
}


text:
Q: How I can join compiled jasper file and my project in java? I have design my project in iReport and I have compiled successfully. Now I want to add the compiled jasper file to add in my java project. May any one help me?

A: Just add them in some package in your source tree. Your build process or IDE should copy them in your classes directory or in the generated jar file, along with your classes. The reports may then be loaded with Class.getResource() or Class.getResourceAsStream().

A: Here is the code you need in order to get two values from two combo-boxes, add them to a HashMap and pass the map to iReport. These paramaters, for this example "storeName" and "actionCode", are used to specify values for the query which is stored inside the iReport. The report jasper file is "../ireps/AccessCounter.jrxml". The viewer is  a JDialog. If you have no parameters to pass to your report just skip the map.put. con is the connection to the database.
Make sure that you include the necessary jar file to your path.
try {
    String shopName = jComboBox1.getSelectedItem().toString();
    String actionCode = jComboBox2.getSelectedItem().toString();
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("storeName", shopName);
    map.put("actionCode", actionCode);

    URL reportFileURL = getClass().getResource("../ireps/AccessCounter.jrxml");
    File reportFile = new File(reportFileURL.toURI());
    JasperDesign jasperDesign = JRXmlLoader.load(reportFile);
    JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, con);
    JasperViewer jv = new JasperViewer(jasperPrint);
    JDialog viewer = new JDialog(this, "Batch Report", true);
    viewer.setBounds(jv.getBounds());
    viewer.getContentPane().add(jv.getContentPane());
    viewer.setResizable(true);
    viewer.setIconImage(jv.getIconImage());
    viewer.setVisible(true);
} catch (JRException exc) {
   System.out.println(exc.getMessage());
} catch (URISyntaxException exs) {
   System.out.println(exs.getMessage());
}


text:
Q: cache memory performance i just have a general question about cache memory. How would a program perform badly on a cache based system ? , since cache memory stores adresses from main memory that is requested, aswell as adresses that ranges around the same adress as the one copied from the main memory.

A: Read this: What every programmer should know about memory (PDF).


text:
Q: Modal from Dropdown link in Twitter Bootstrap I am trying to have a modal launch from a link that is in my dropdown menu. The modal seems to launch (the site goes grey) but it can't be seen. Modals from regular links not in the dropdown work just fine. I have fooled with the jquery but nothing has worked out since I am new to jquery. Here is my site code.

        My Item

                    ×

Delete My Item?

Are you sure you really want to delete My Item?

                    Delete
                        Item
                    Cancel

Edit Item

Delete Item

And here are the javascript files at the end of the

Here is my rails code just in case.

          <%= @item.name %>

              <%= render "items/delete" %>

<%= link_to 'Edit Item', edit_item_path(@item) %>

<%= link_to 'Delete Item', @item,
                              "data-toggle" => "modal", "data-target" => "#DeleteItem" %>

    ×
    <%= content_tag :h3, "Delete #{@item.name}" + "?" %>

    <%= content_tag :p, "Are you sure you really want to delete #{@item.name}" + "?" %>

    <%= link_to 'Delete Item', @item, method: :delete, :class => "btn btn-primary" %>
    Cancel

A: I believe you may be running into a problem by including the modal div element within the navbar structure.  My intuition is that you should include it somewhere near the end of your markup.


text:
Q: Python multiprocess profiling I want to profile a simple multi-process Python script. I tried this code:
import multiprocessing
import cProfile
import time
def worker(num):
    time.sleep(3)
    print 'Worker:', num

if __name__ == '__main__':
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i,))
        cProfile.run('p.start()', 'prof%d.prof' %i)

I'm starting 5 processes and therefore cProfile generates 5 different files. Each log only shows what happens inside the start method. How can I get logs that profile the worker function (and show that it took approximately 3 seconds in each case)?

A: It's not cool enough having to change your source code for profiling. Let's see what your code is supposed to be like:
import multiprocessing
import time
def worker(num):
    time.sleep(3)
    print('Worker:', num)

if __name__ == '__main__':
    processes = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i,))
        p.start()
        processes.append(p)
    for p in processes:
        p.join()

I added join here so your main process will wait for your workers before quitting.
Instead of cProfile, try viztracer.
Install it by pip install viztracer. Then use the multiprocess feature
viztracer --log_multiprocess your_script.py
It will generate an html file showing every process on a timeline. (use AWSD to zoom/navigate)

Of course this includes some info that you are not interested in(like the structure of the actual multiprocessing library). If you are already satisfied with this, you are good to go. However, if you want a clearer graph for only your function worker(). Try log_sparse feature.
First, decorate the function you want to log with @log_sparse
from viztracer import log_sparse

@log_sparse
def worker(num):
    time.sleep(3)
    print('Worker:', num)

Then run viztracer --log_multiprocess --log_sparse your_script.py

Only your worker function, taking 3s, will be displayed on the timeline.

A: You're profiling the process startup, which is why you're only seeing what happens in p.start() as you say—and p.start() returns once the subprocess is kicked off.  You need to profile inside the worker method, which will get called in the subprocesses.

A: If you have a complex processes structure and you want to profile a particular portion of the code, or maybe the particular working core of the process you can point to the profiler to collect stats there (see enable and disable methods https://docs.python.org/3.6/library/profile.html#module-cProfile). This is what you can do:
import cProfile

def my_particular_worker_code()
    pr = cProfile.Profile()
    pr.enable()

    # Process stuff to be profiled

    pr.disable()
    pr.print_stats(sort='tottime')  # sort as you wish

You can drop the reports to a file as well.


text:
Q: Incorrect syntax in where Below is my query which I am trying to write. but I am getting an error saying incorrect syntax near where
SELECT
    [p.ProjectId],
    SUM(pf.size),
    COUNT(pr.ServerGroupId) AS [UnRestrictedFacility],
    CASE
       WHEN COUNT(ps.CreatedBy) > 0
          THEN 1
          ELSE 0
    END
FROM
    Project p
INNER JOIN
    ProjectFile pf
INNER JOIN
    ProjectPartlink ppl ON pf.ProjectPartlinkId = ppl.ProjectPartlinkid
                        AND ppl.ProjectId = p.projectid
INNER JOIN
    ProjectRestriction pr ON pr.projectid = p.projectid
INNER JOIN
    ProjectPreseed ps ON ps.projectid = p.projectid
WHERE
    p.projectid = @projectid

Can anyone help?

A: here is the error it seems :
From Project p inner join
ProjectFile pf inner join

it should be
From Project p inner join
ProjectFile pf on p.id = pf.id inner join

A: Error is a bit misleading:
From Project p inner join
   ProjectFile pf inner join
   ProjectPartlink ppl

You are missing the ON of the first join.
edit:
You are also using aggregation functions without a group by. Far as I know, that's only allowed by older versions of mysql. If you use aggregation you must use a group by clause to get reliable results. You don't mention what rdbms you use, but this is also a likely cause for the error.

A: First, cleaning up and having a well formatted SQL will help you in the long run.  Always put your "ON" clauses with the respective join so you know you did not forget something and have a Cartesian result down the road.  Also, my personal preference is to always list the ON clause with the leftSideAlias.column = rightSideAlias.column.  It also helps to show the relationship between table A->B->C, etc..  You actually DID have all the pieces to the query, I just reorganized them.  Notice the readability from one table to the next too.
SELECT
      p.ProjectId,
      sum(pf.size),
      count(pr.ServerGroupId) UnRestrictedFacility,
      CASE when count(ps.CreatedBy) > 0 then 1 Else 0 END CreatedCounter
   From
      Project p
         inner join ProjectPartlink ppl
            on p.projectid = ppl.ProjectId
            inner join ProjectFile pf
               on ppl.ProjectPartlinkid = pf.ProjectPartlinkId
         inner join ProjectRestriction pr
            on p.projectid = pr.projectid
         inner join ProjectPreseed ps
            on p.projectid = ps.projectid
   where
      p.projectid = @parmProjectid

Finally, your WHERE clause.  You had @ProjectID which I have known to cause confusion when supplying a variable.  If there is no variable by that name, but there is a column by that name, it appears to resolve to the column name.  To prevent that, I like to explicitly tack-on some sort of prefix, such a above from @ProjectID to @parmProjectID so I KNOW it is coming from some parameter and not a mistaken column name reference.

A: And this should work as well, due to default order of operations
   From Project p
   inner join ProjectFile pf
   inner join ProjectPartlink ppl
   on pf.ProjectPartlinkId=ppl.ProjectPartlinkid
   on ppl.ProjectId=p.projectid

A: You should try :
SELECT
    [p.ProjectId],
    SUM(pf.size),
    COUNT(pr.ServerGroupId) AS [UnRestrictedFacility],
    CASE
       WHEN COUNT(ps.CreatedBy) > 0
          THEN 1
          ELSE 0
    END
FROM
    Project p
INNER JOIN
    ProjectFile pf on pf.Id = p.tId
INNER JOIN
    ProjectPartlink ppl ON pf.ProjectPartlinkId = ppl.ProjectPartlinkid
                        AND ppl.ProjectId = p.projectid
INNER JOIN
    ProjectRestriction pr ON pr.projectid = p.projectid
INNER JOIN
    ProjectPreseed ps ON ps.projectid = p.projectid
WHERE
    p.projectid = @projectid


text:
Q: How to search a document for IP addresses So I have a document (plain text) that I'm trying to extract all of the IP addresses from.  I was able to extract them using regular expressions but it also grabs a large number of version numbers.  I tried using string.find() but it requires that I be able to locate the escape character used for the end of the line (the IP addresses are always the last thing on a line) and the escape character used for the end of the line is unknown to me.  Anyone know how I could pull these addresses out?

A: If your addresses are always on the end of a line, then anchor on that:
ip_at_end = re.compile(r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}$', re.MULTILINE)

This regular expression only matches dotted quads (4 sets of digits with dots in between) at the end of a line.
Demo:
>>> import re
>>> ip_at_end = re.compile(r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}$', re.MULTILINE)
>>> example = '''\
... Only addresses on the end of a line match: 123.241.0.15
... Anything else doesn't: 124.76.67.3, even other addresses.
... Anything that is less than a dotted quad also fails, so 1.1.4
... does not match but 1.2.3.4
... will.
... '''
>>> ip_at_end.findall(example)
['123.241.0.15', '1.2.3.4']

A: Description
this will match and validate ipv4 addresses, and will ensure the individual octects are within  a range of 0-255
(?:([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])

Disclaimer
yes I realize the OP asked for a Python solution. This PHP solution is only included to show how the expression works
php example
<?php
$sourcestring="this is a valid ip 12.34.56.78
this is not valid ip 12.34.567.89";
preg_match_all('/(?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])/i',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>

$matches Array:
(
    [0] => Array
        (
            [0] => 12.34.56.7
        )

)


text:
Q: LUIS List entity I am using "list" entity. However, I do not achieve my expected result.
Here is what I have for LUIS intent:

*

*getAnimal

*

*I want to get a cat**[animal]**.

Here is what I have with LUIS entities:
List Entities [animal]

*

*cat: russian blue, persian cat, british shorthair

*dog: bulldog, german shepard, beagle

*rabbit: holland lop, american fuzzy lop, florida white

Here is what I have with LUIS Phrase lists:
Phrase lists [animal_phrase]

*

*cat, russian blue, persian cat, british shorthair, dog, bulldog, german shepard, beagle, etc

Desired:
When user enters "I want to get a beagle." It will be match with "getAnimal" intent.
Actual:
When user enters "I want to get a beagle." It will be match with "None" intent.
Please help. Your help will be appreciated.

A: So using a phrase list is a good way to start, however you need to make sure you provide enough data for LUIS to be able to learn the intents as well as the entities separate from the phrase list. Most likely you need to add more utterances.
Additionally, if your end goal is to have LUIS recognize the getAnimal intent, I would do away with the list entity, and instead use a simple entity to take advantage of LUIS's machine learning, and do so in combination with a phrase list to boost the signal to what an animal may look like.
As the documentation on phrase lists states,

Features help LUIS recognize both intents and entities, but features
  are not intents or entities themselves. Instead, features might
  provide examples of related terms.

--Features, in machine learning, being a distinguishing trait or attribute of data that your system observes, and what you add to a group/class when using a phrase list

Start by
1. Creating a simple entity called Animal

2. Add more utterances to your getAnimal intent.
Following best practices outlined here, you should include at least 15 utterances per intent. Make sure to include plenty of examples of the Animal entity.
3. Be mindful to include variation in your utterances that are valuable to LUIS's learning (different word order, tense, grammatical correctness, length of utterance and entities themselves). Highly recommend reading this StackOverflow answer I wrote on how to build your app properly get accurate entity detection if you want more elaboration.

above blue highlighted words are tokens labeled to the simple Animal entity

3. Use a phrase list.
Be sure to include values that are not just 1 word long, but 2, 3, and 4 words long in length, as different animal names may possibly be that long in length (e.g. cavalier king charles spaniel, irish setter, english springer spaniel, etc.) I also included 40 animal breed names. Don't be shy about adding Related Values suggested to you into your phrase list.

After training your app to update it with your changes, prosper!
Below "I want a beagle" reaches the proper intent. LUIS will even be able to detect animals that were not entered in the app in entity extraction.


text:
Q: Dehn and the Jordan curve theorem I am looking for a manuscript of Max Dehn entitled "Beweis des Satzes, dass jedes geradlinige geschlossene Polygon ohne Doppelpunkte 'die Ebene in zwei Teile teilt'".
According to Heinrich Guggenheimer [1] the manuscript contains the first complete and correct proof of the Jordan curve theorem. I was unable to find an online version. Apparently, the manuscript is in Box 4RM129 at Briscoe center for American history, somewhere in Texas [2]. But there may be some copy that has circulated
in the seventies. Does anyone has such a copy?
[1] https://www.maths.ed.ac.uk/~v1ranick/jordan/guggenheim.pdf
[2] https://legacy.lib.utexas.edu/taro/utcah/00192/cah-00192.html (Wayback Machine](https://web.archive.org/web/20180531051738/https://legacy.lib.utexas.edu/taro/utcah/00192/cah-00192.html))


text:
Q: mongodb aggregation query, using projection, $size,$split i have to make a query, so in my query i must to show only  when the size is one; and in my projection i show the results , and i have the query but only show all the sizes, but i only need to show when the size is one, i ve no idea how to make it. and i used a projection.
this is a single doc:
document
and my query is this:
db.movies.aggregate([
{"$project":
  {
    "_id": 0,
    "longi":{$size:{ $split: [ "$title", " " ]}}
  }
    }]);

and the result is this:
{ "longi" : 2 }

{ "longi" : 2 }

{ "longi" : 6 }

{ "longi" : 11 }

{ "longi" : 2 }

{ "longi" : 2 }

{ "longi" : 6 }

{ "longi" : 2 }

{ "longi" : 1 }

{ "longi" : 4 }

{ "longi" : 5 }

{ "longi" : 3 }

{ "longi" : 5 }

{ "longi" : 3 }

{ "longi" : 3 }

{ "longi" : 5 }

{ "longi" : 4 }

{ "longi" : 5 }

{ "longi" : 1 }

res
but i just want to show  when the size is one

A: You can use $match after $projetct.
db.movies.aggregate([
{"$project":
  {
    "_id": 0,
    "longi":{$size:{ $split: [ "$title", " " ]}}
  }
 }
 , {$match: {"longi":1 }}
 ]);


text:
Q: Creating unmodifiableSet from unmodifiableSet Collections.unmodifiableSet allows me to create an unmodifiable view of a set. I'm assuming this is done by wrapping the provided set. Will there be any performance problem(s) if unmodifiable sets are created from already unmodifiable sets?
e.g.
Set<String> set = Collections.unmodifiableSet(Collections.unmodifiableSet(Collections.unmodifiableSet(new HashSet<String>())));

A: Collections.unmodifiableSet - just wraps a set with UnmodifiableSet instance, which just proxies all method invocation. Additional finite method invocation sequence is not a subject of performance consideration, sure if you are not talking about thousands of wrappers.

A: The method signature is:
public static <T> Set<T> unmodifiableSet(Set<? extends T> s) {
    return new UnmodifiableSet<T>(s);
}

in the class Collections. Which returns a new instance of object UnmodifiableSet. Now this class is inner static class:
static class UnmodifiableSet<E> extends UnmodifiableCollection<E> implements Set<E>, Serializable

In the class UnmodifiableCollection the methods like add, remove, addAll etc throws UnsupportedOperationException. That is why it is Unmodifiable.
Now if you instantiate thousands time a collection of course it would be issue.


text:
Q: transfer single table data from one Database to other database with same table name? How can i transfer single table data from one Database to other database with same table name?
I have a database with data and other one has no data.
They are not exactly the same as but one table is the same
Thanks

A: There are many ways to export a table. Some are,

*

*Using SELECT INTO Query
Select * into Database1.Department from Database2.Department

*Using SQL Server Export / Import wizard
a. From SQL Server Management Studio, right-click on the database name in the object explorer, then choose Tasks -> Export Data
b. Choose a Data Source and Destination
c. Select the source table and follow the steps and execute the package
For more info, check http://www.sqlshack.com/how-to-copy-tables-from-one-database-to-another-in-sql-server/
Edited Note:
The above methods are for Microsoft SQL Server.


text:
Q: Overwrite the last x days in partitioned table using scheduled query Is there a way i can overwrite only the last x days in a partitioned table with a scheduled query?
The query runs daily and since there might be new records from the previous days i want to overwrite the last days and the earlier ones should remain the same. In the query scheduler i only have the options to append and overwrite the whole table so not sure if this is possible.
Note: initially i tried checking for the recently updated tables, then inserting only the new records from them however the tables are too big and the query doesn't run so i am trying to find a workaround.
Scheduled query:
SELECT parse_date("%Y%m%d", event_date) as event_date
     , event_name
     , id
     , country
     , test_group
  FROM `project.dataset.events_*`
 WHERE _TABLE_SUFFIX between FORMAT_DATE("%Y%m%d", DATE_SUB(CURRENT_DATE(),INTERVAL 7 DAY)' and FORMAT_DATE("%Y%m%d", DATE_SUB(CURRENT_DATE(),INTERVAL 2 DAY))


text:
Q: Combining two custom commands I came across a problem when typing my report. I do not know how to fix this. The problem is as follows:
I have two custom commands defined like this:
\newcommand{\slr}[1][n]{\ensuremath{{\bf SL}(#1,\mathbb{R})}}

\newcommand{\lie}[1][G]{\ensuremath{{\bf L}(#1)}}

So that the first command gives an output like ${\bf SL}(n,\mathbb{R})$ and the second command gives the output like ${\bf L}(G)$. Here $n$ and $G$ are respectively the default arguments.
Now when I use these two commands together, I hope to get
$${\bf L}({\bf SL}(2,\mathbb{R}))$$

However, for some reason what I am getting is
$$ {\bf L}({\bf SL}(2),\mathbb{R})$$

Any ideas of what is going on here?

A: The problem in \lie[\slr[2]] is that the optional argument to \lie is taken to be \slr[2. You can solve the issue with xparse:
\documentclass{article}
\usepackage{amsmath,amssymb,xparse}

\DeclareMathOperator{\slrop}{\mathbf{SL}}
\DeclareMathOperator{\lieop}{\mathbf{L}}

\NewDocumentCommand{\slr}{O{n}}{\slrop(#1,\mathbb{R})}
\NewDocumentCommand{\lie}{O{G}}{\lieop(#1)}

\begin{document}
Here it is: $\lie[\slr]$

With optional argument: $\lie[\slr[2]]$
\end{document}

I removed \ensuremath as I believe that you gain nothing from using \lie in text rather than $\lie$; to the contrary, I firmly believe that the latter form is much better, because math is always treated as math.

A: I cannot see it:
\documentclass{article}
\usepackage{amsmath}
\usepackage{amssymb}
\newcommand\slr[1][n]{\ensuremath{\mathbf{SL}(#1,\mathbb{R})}}
\newcommand\lie[1][G]{\ensuremath{\mathbf{L}}(#1)}

\begin{document}

\[ {\bf L}({\bf SL}(2,\mathbb{R})) \]

\[ \lie[{\slr[2]}] \]

\[ \slr[\lie] \]

\end{document}

You have to put the optional argument into braces: [{\slr[2]}]


text:
Q: How to compare arrays in my case? I am trying to do a mapping in my app.
I have something like
$scope.newProducts = ['123','456','789']

$scope.products = [{'id':'123'}, {'id':'121'}, {'id':'678'}, {'id':'789'}];

I want to be able to identify new product in my products array.
I have something like
$scope.newProducts.forEach(function(id){
    //not sure what is the best way to find new product id in $scope.products
})

I need to identify the new product id in products array. I wonder what the best way is to do it. thanks for the help!

A: You could set a isNew flag on the new products.
$scope.products.forEach(function (product) {
    if ($scope.newProducts.indexOf(product.id) > -1) {
        product.isNew = true;
    }
});

A: Try using a library like underscore which makes these type of operations quite simple.
_.each(products, function(item){
    if (_.contains(newProducts, item.id )){
        console.log(item);
    }
});

Plunker


text:
Q: Finite Unions of Equinumerous Sets Is the following statement provable in ZF?
Assume that $A_1$ and $A_2$ are two infinite sets. If $A_1$ is equinumerous with $B_1$ and $A_2$ is equinumerous with $B_2$, then $A_1 \cup A_2$ is equinumerous with $B_1 \cup B_2$.

A: Assuming that the union is disjoint, this is easy, since the union of the bijections is itself a bijection.
If not, then this is easy to see that if we assume that $|A_1\cup A_2|=|B_1\cup B_2|$, for any two pairs as in your assumption, then taking $A_1=A_2$ and $B_1=A_1\times\{0\}$ and $B_2=A_1\times\{1\}$, we get that $|A_1|=|A_1\times 2|=|A_1|+|A_1|$.
This does not follow from $\sf ZF$, for example, if there are infinite Dedekind-finite sets that is easy, and even if we assume $\sf DC$ or its uncountable versions, there can still be counterexamples to this principle, e.g. sets which are $\aleph_1$-amorphous may exist even if we assume $\sf DC$.
On the other hand, assuming $|A|=|A\times 2|$ for any infinite set $A$, we get that $|A_1\cup A_2|=|A_1\times\{0\}\cup A_2\times\{1\}|$, since we have:
$$|A_1\cup A_2|=|(A_1\cup A_2)\times 2|\geq|A_1\times\{0\}\cup A_2\times\{1\}|\geq|A_1\cup A_2|.$$
Which means that every union can be replaced by a disjoint union, and therefore the equality ensues. Finally, Sageev proved that $|A|=|A\times 2|$ for all infinite $A$ does not imply the axiom of choice, indeed, not even the axiom of countable choice.


text:
Q: Integrating JSP with Apache SOLR Can someone help me with integrating JSP with Apache SOLR? I am new to Apache SOLR and havn't used JSP much in recent years but know the working of it. I have developed the UI in JSP and want to accept the user query from JSP and query them in Apache SOLR. Thanks in advance.

A: A couple of things:

*

*You don't want to host your JSP in the same Jetty that Solr uses. Primarily because you don't want to expose your Solr server to the public internet (it is not secured). So, your JSP should be running on a separate server (Tomcat/Jetty/etc) and talk to Solr

*To talk to Solr you probably will want to use SolrJ client, which you need to keep around in a global pool of some sort

*Or, you could host your JSP views inside Spring container, in which case you could look at Spring Data Solr integration, which will manage the session for you.


text:
Q: Long file names in Google Cloud Storage I'm using App Engine to upload files to Google Cloud Storage via the Blobstore API. The thing is that when I explore the files in the Google Developer Console, this long names appear:

Why is this ? Do am I doing something wrong ?
It's something trivial because I'm able to work perfectly with the files, I was just curious about it.
Thanks in advance !

A: AFAIK, that's the blobstore key of your file. It's totally normal and to be expected.
You can see a user in Google's Public Issue tracker that was asking for a way to rename the file because he found the blobstore name confusing.


text:
Q: One variable for different collections in Jekyll to use in forloop I have several collections on my Jekyll site. I've added post navigation to one of the collections displaying a counter on each post page:
{% assign testimonials = site.testimonials %}
{% assign page_order = 1 %}
{% for node in testimonials reversed %}
  {% if node.url == page.url %}
    {{ page_order }} from {{ forloop.length }}
  {% else %}
    {% assign page_order = page_order | plus: 1 %}
  {% endif %}
{% endfor %}

I would like to make this code work not only for site.testimonials, but for other collections as well. I tried to pass a variable for collections like this:
{% capture label %}{{ page.collection }}{% endcapture %}
{% assign collection = site.collections | where: "label",label | first %}
{% for node in collection reversed %}
  {% if node.url == page.url %}
    {{ page_order }} from {{ forloop.length }}
  {% else %}
    {% assign page_order = page_order | plus: 1 %}
  {% endif %}
{% endfor %}

But it doesn't work. Is there any way to pass a variable for all collections in Jekyll to use in forloop in post navigation?

A: When you access collection with site.testimonials, you get collection's documents array.
{{ site.testimonials | inspect }}

# output >> [#<Jekyll::Document ...>, #<Jekyll::Document ...>, ...]

When you access a collection while looping over site.collection, you receive the collection's object :
{% assign collection = site.collections | where: "label",page.collection | first %}
{{ collection | inspect }}
# output >> { "output": true, "label": "collectionLabel",
              "docs": [ doc1, docs2, ... ], "files": [],
              "directory": "/path/to/collection",
              "relative_directory": "_colectionDirectory" }

In your case, you just have to replace :
{% for node in collection reversed %}

By :
{% for node in collection.docs reversed %}


text:
Q: Getting updated Shared Object data without reopening it I have 2 swf that will be loaded on a website. One suppose to generate a bytearray and being passed over to another swf.
The problem is that when I save the bytearray to a SharedObject in user's local file, the second swf doesn't get the updated variable value from the first swf.
I've set the second swf to retrieve the value every one second and it don't get updated until I reload the page.
I flushed and close the connection to make sure the data is saved on the local path and that is not helping as well.
I also considered using LocalConnection as well but there is a bug in flash player for mac that stopping it to work between swfs on mac. Left me no choice but to use SharedObject for my project.
Do you guys have any solution for this?
Many thanks..

A: I don't think this approach will work (the local SharedObject probably isn't designed with this in mind, and the exact behavior might differ between browsers and flash player versions).
I would try using LocalConnection instead.
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/LocalConnection.html
EDIT: Sorry, I missed this:
"I also considered using LocalConnection as well but there is a bug in flash player for mac that stopping it to work between swfs on mac. Left me no choice but to use SharedObject for my project."
I use local connection on mac all the time, so I'm not sure what you are referring to. I would strongly recommend using a random number that is generated once per page view and send it to the flash (to use as a part of the connection name), to ensure that you don't open several connections with the same name (if the user opens your site several times in different tabs for example).

A: I use this method of communication without problem and it's works fine. Do you call flush after changing the value?


text:
Q: Why is pattern matching different inside package This works fine when put in a notebook:
TestFunction2[x_] := Column[{Head /@ x, Cases[x, _f], MatchQ[_f] /@ x}];
TestFunction2[{f[1, 2]}]

and produces:
{f}
{f{1,2}}
{True}

However if the function is put in a package, for example:
BeginPackage["Test`"]
TestFunction::usage=""
Begin["`Private`"]
TestFunction[x_]:=Column[{Head/@x,Cases[x,_f],MatchQ[_f]/@x}];
End[]
EndPackage[]

and then used from a notebook:
Needs["Test`"];
TestFunction[{f[1, 2]}]

it produces:
{f}
{}
{False}

Why?

Edit:
My example was not detailed enough to explain what I want to achieve. I indeed want to have f that is defined in the context of Test`. This is because I want to use it as a type inside the package Test.
This is for example because I want to distinguish between two different arrays and wrap one of them for example in f[{1,2,3}] and another one in g[{1,2,3,}] and thus make distinction how they should be processed in Test.

A: The problem was that f is created as  Test`Private`f. Modifying the code in the package like this:
BeginPackage["Test`"]
TestFunction::usage=""
f::usage=""
Begin["`Private`"]
TestFunction[x_]:=Column[{Head/@x,Cases[x,_f],MatchQ[_f]/@x}];
End[]
EndPackage[]

will make it work.
Thank you Szabolcs for pointing this out!
Thanks to Kuba for pointing out the linked examples!


text:
Q: What properties of a voting method is best for deciding what movie to watch among a small group of people? Almost every night me and my friends get together to watch a movie.
Current Method:
Each person (<10) picks 5 movies they want to watch and we vote on them. Each person gets around 7 votes which they must use to pick a movie. They are allowed to vote on their own movies. We then tally up the votes and the movie with the most votes wins. In case of a tie (which is common, sometimes with many movies with 2-3 votes each) we redo the vote just with the tied movies and pick the number of votes based on simple intuition (guessing really).
This method of voting is not satisfactory for the following reasons:

*

*Movies that people vote for as a throw away vote sometimes win.

*Ties are common with a large spread.

*It is easy to make dishonest votes in order for your movie to win.

*Sometimes a voter will boycott a movie because how unsatisfied they are with the vote.

My Research:
I was looking at wikipedia for different methods of voting and came across this table:
Table with properties of different voting methods I had a hard time understanding some of the properties and if it would be beneficial or unbeneficial to my scenario.
Scenario:

*

*Each voter picks N (N > 1) movies to vote on

*2-10 voters (usually at least 3)

*There must be one winner

*voters prefer their own movies.

I was wondering given the following scenario What properties of a voting method would be ideal? I would like to maximize the following:

*

*Members of the vote should feel strongly about the winning movie. (perhaps there is a way to quantify this?)

*works well when number of candidates is >= to number of voters.

*Given possibly large number of movies to vote on vote must be relatively quick to complete.

*Gaming the vote is hard to do as an individual.

*Voters only have to vote once.


text:
Q: curl post testing oauth 2.0 not working while the http example does I am trying to understand how Google authentication works with OAuth 2.0. They give some examples at this link.
I am having trouble with one of the first steps. I can execute this http request in a browser:
https://accounts.google.com/o/oauth2/auth?scope=https://www.google.com/m8/feeds&client_id=21302922996.apps.googleusercontent.com&redirect_uri=https://www.example.com/back&response_type=token

and that works fine.
When I try to convert it to a curl GET operation,
curl https://accounts.google.com/o/oauth2/auth?scope=https://www.google.com/m8/feeds&client_id=21302922996.apps.googleusercontent.com&redirect_uri=https://www.example.com/back&response_type=token

I get a response that tells me there is an OAuth 2.0 error: invalid_request.
Converting it to a POST, I can't get this  operation to work.
curl http://accounts.google.com/o/oauth2/auth  -d "scope=https://www.google.com/m8/feeds&client_id=21302922996.apps.googleusercontent.com&redirect_uri=https://www.example.com/back&response_type=token"

The response is that the document has moved.
If I try this, I get similar results.
curl http://accounts.google.com/o/oauth2/auth  -data-urlencode "scope=https://www.google.com/m8/feeds&client_id=21302922996.apps.googleusercontent.com&redirect_uri=https://www.example.com/back&response_type=token"

I have never used curl or OAuth in my code before, so I want to understand some of these basics. Can someone tell me what is wrong with my GET and POST ?

A: I don't have a sure answer for you, but I was working on something similar for Instagram and one thing that stumped me for a while was that my redirect URL looked to be the same as Instagram expected, but I kept getting errors.
Like you, when I 'hand coded' the redirect URL, I got the result I expected, but my automated calls to the authentication URL failed. It turned out my ampersands were a url encoded which Instagram compared to the redirect URL and saw they were not identical. I'm not sure if that will get you closer to an answer, but I thought I'd share my experience since your question reminds me of the situation I was in. Good luck.


text:
Q: Changes are made in all selections, instead of the one I choose Changes are made in all selections, instead of the one I choose. When I check the checkbox in one selection, all the others change. Changing  How can I change that?
applications should change the name to the name of the marked checkbox in each selected selection. However, it changes in all the selections I have.
const handleSelect = (e,id) => {

let newValue = [1];
if (e.target.value.length) {
  newValue = e.target.value.filter((item) => {
    return item > 1;
  });
}

const finalString = newValue
  .reduce((acumulatedFinal, pass) => {
    return acumulatedFinal + ", " + exportOptionNames[pass - 1];
  }, "")
  .replace(",", "")
  .trim();

setSelectedSelections(finalString.length ? finalString : "Export Option");

setExportOption(newValue);
};

                       <FormControl }>
                    <Select  onClick={(e)=> e.stopPropagation()}
                      labelId="label"
                      id="select"
                      value={exportOption}
                      multiple
                      onChange={(e) => handleSelect (e, item.id)}
                     key={item.id}
                      renderValue={() => {
                        return selectedOptionNames;
                      }}
                      input={<BootstrapInput />}
                    >
                      <MenuItem value={1} disabled>
                        Export Report
                      </MenuItem>
                      <MenuItem value={2}>
                        <Checkbox checked={exportOption.includes(2)} />
                        <ListItemText>{exportOptionNames[1]}</ListItemText>
                      </MenuItem>
                      <MenuItem value={3}>
                        <Checkbox checked={exportOption.includes(3)} />
                        <ListItemText>{exportOptionNames[2]}</ListItemText>
                      </MenuItem>
                      <MenuItem value={4}>
                        <Checkbox checked={exportOption.includes(4)} />
                        <ListItemText>{exportOptionNames[3]}</ListItemText>
                      </MenuItem>
                    </Select>


text:
Q: how to load bunch of images to the Image in QML? I would like to load a few images to the Image object in QML. I want to do it one after another in a loop I think with some delay, because it should pretend to look like an animation. Im new in Qt and QML, so can anybody help me how to begin or somethin'? :)

A: The simplest solution, that works in QML 1.x and 2.0, is to use a Repeater and a Timer :
import QtQuick 2.0

Rectangle {
    id: base;
    width: 800;
    height: 600;

    property variant images : [
        "image1.jpg",
        "image2.jpg",
        "image3.jpg",
        "image4.jpg",
        "image5.jpg"
    ];
    property int currentImage : 0;

    Repeater {
        id: repeaterImg;
        model: images;
        delegate: Image {
            source: modelData;
            asynchronous: true;
            visible: (model.index === currentImage);
        }
    }

    Timer {
        id: timerAnimImg:
        interval: 500; // here is the delay between 2 images in msecs
        running: false; // stopped by default, use start() or running=true to launch
        repeat: true;
        onTriggered: {
            if (currentImage < images.length -1) {
                currentImage++; // show next image
            }
            else {
                currentImage = 0; // go back to the first image at the end
            }
        }
    }
}

Should do it, and if you don't want the animation to restart when the last image is reached, just replace currentImage = 0; with stop(); in the timer's onTriggered.
Also, you should possibly have to tweak a little the Image delegate in the Repeater to give it the look you want (size, fill mode, position etc...).

A: If you are using QtQuick 2 then AnimatedSprite is the best way to do this: http://qt-project.org/doc/qt-5.0/qtquick/qtquick-effects-sprites.html
Otherwise, you could use a Timer or NumberAnimation to trigger changing the image source, but there could be unpredictable delays as images load for the first time (caching should solve this after the first loop).  If you only have a few images, you could have three Images and cycle their visibility.


text:
Q: Retrieving results from Cassandra in order I have stored the data in the ComparatorType.BYTESTYPE in the Cassandra database. Now I want to retrieve data in the stored order.
I used the following code in Hector to get data, but the query results seems not sorted.
Keyspace keyspace = HFactory.createKeyspace("ClusterName", cluster);

Map<String, String> resultMap = new HashMap<String, String>();

SliceQuery<String, String, String> query = HFactory.createSliceQuery(keyspace,   StringSerializer.get(), StringSerializer.get(), StringSerializer.get());
query.setColumnFamily("ColumnFamilyName").setKey("RowKey")
.setRange("", "", false, Integer.MAX_VALUE);
QueryResult<ColumnSlice<String, String>> result = query.execute();

for (HColumn<String, String> column : result.get().getColumns()) {
        resultMap.put(column.getName(), column.getValue());
}

what am I missing?? Do I have to use RangeSliceQueries and OrderedRows??
Thanks in advance.

A: It all depends on the comparator you have set for the column names.
If it is BytesType (cassandra's default) as well, then it won't be the order you expect.
if you want alphabetical order you should define your table with something like that in the cassandra-cli:
create column family ColumnFamilyName with comparator = UTF8Type;
or you are still in time maybe to do
update column family ColumnFamilyName with comparator = UTF8Type;

A: Thanks douard for your answer.
But I solved it by changing the collection to a LinkedHashMap instead of a HashMap. As I noticed
    result.get().getColumns()

gives the results in order, but as HasMap doesn't preserve the insertion order, results get unordered.
So the above code works fine when you change the HashMap to a LinkedHashMap.
    Map<String, String> resultMap = new LinkedHashMap<String, String>();