text:
Q: Selection control returning array with undefined values in azure maps   <!DOCTYPE html>

    <title>Selection control - Azure Maps Web SDK Samples</title>

    <link
      rel="stylesheet"
      href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.css"
      type="text/css"
    />

    <link
      rel="stylesheet"
      href="https://atlas.microsoft.com/sdk/javascript/drawing/0/atlas-drawing.min.css"
      type="text/css"
    />

    <link rel="stylesheet" href="./selectionControl.min.css" type="text/css" />

    <fieldset
      style="width: calc(100% - 30px); min-width: 290px; margin-top: 10px"
    >
      <legend>
Selection control
</legend>
      This sample shows how to use the selection control. This control connects
      to a data source and lets you draw polygon areas on the map and retrieve
      all the point shapes in the data source that are within that area. Press
      the pointer button in the top right corner of the map to choose a
      selection mode, then draw on the map. This samples uses the open source
      Azure Maps Selection Control module
    </fieldset>

I'm using the azure maps selection module to filter out a data points based on selection. But console.log (selectedShapes) on "dataselected" event returns a array with undefined values. However the alert shows the number of elements in the array. But they are all undefined. Is there anything that I'm missing ? Thanks.


text:
Q: Eclipse PDT and .yml file, cannot open? I am using Symphony framework and I have the default sandbox inside the Eclipse IDE. When I double click schema.yml instead of open in Eclipse it requests Windows to select a program to choose. I am a Visual Studio guy and I do not understand why it doesn't open in Eclipse, what should I do?

A: Right click on the file, select OPEN WITH>Text Editor and it will open in the IDE

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use WhereIn with Eloquent in laravel? I want to used WhereIn method in Eloquent but it now work as below function
Messages: Call to undefined method Illuminate\Database\Query\JoinClause::whereIn()
 Class Notificatin extends Model{

 public function getNotification($user_id)
    {

        $this->_data = self::select('*')
            ->join('user_permission', function($join){
                $join->on('n_user_id','=','user_id')->whereIn('permission_id',array(90,91,92,93));
            })
            ->get();
        if (count($this->_data)) {
            return $this->_data;
        } else {
            return $this->_data;
        }
    }
   }

A: You need to modify you join query and put whereIn clouse out side like:
$this->_data = self::select('*')
            ->join('user_permission', function($join){
                $join->on('n_user_id','=','user_id');
            })->whereIn('user_permission.permission_id',array(90,91,92,93))
            ->get();

A: Without using Joins :
whereIn / whereNotIn / orWhereIn / orWhereNotIn
The whereIn method verifies that a given column's value is contained within the given array:
$users = DB::table('users')
                ->whereIn('id', [1, 2, 3])
                ->get();

The whereNotIn method verifies that the given column's value is not contained in the given array:
$users = DB::table('users')
                ->whereNotIn('id', [1, 2, 3])
                ->get();


text:
Q: How do i get mapview to plot my raster image with the same colors as plotRGB or plot I have a raster file that I have exported from ArcGIS as a georeferenced tif file.
The raster will be used as a background map in mapview because the mapview background layers CartoDB.Positron,  CartoDB.DarkMatter,  OpenStreetMap , Esri.WorldImagery and  OpenTopoMapdont dont give the required background at the zoom level i need.
First I read my raster brick into R using the raster package and then I plot using plotRGB.
library(raster)
library(mapview)
r<-brick("KYENGERA2.tif")#raster exported from Arcgis read. has 4 bands
r<-subset(r,1:3) #Retain only layers/bands with RGB
plotRGB(r, 1,2,3, stretch='lin')

The result is as expected

I then create a new raster r2 with values 0 - 255 and assign a colortable based on the rgb values in r. I plot it in two difefrent ways and i get the same result.
pct <- rgdal::SGDF2PCT(as(r, "SpatialGridDataFrame"))
r2 <- setValues(raster(r), pct$idx-1) #create a new raster with values 0 - 255
colortable(r2) <- pct$ct #define 256 colors
plotRGB(r, 1,2,3, stretch='lin')
plot(r2)#plot(r2,col=r2@legend@colortable)

Here is the result and it is much better

However when I try mapview, the result is not as expected.
mapview(r2, col.regions = pct$ct,na.col="transparent")

Can anyone help me solve this issue with mapview?
I have taken a look at this but i couldnt figure out a solution.

A: You can simply use mapview::viewRGB()
viewRGB(r, 1, 2, 3, method = "ngb", quantiles = c(0, 1), maxpixels = ncell(r))


text:
Q: bind a polymer template to html5 video.textTracks I try to create a html5 video timeline where all the tracks and the cues are displayed using polymer.
this is the code I have so far, but the binding does not work. It always displays a length of 0:
<polymer-element name="video-timeline">
    <template>
        <video id="testVideo" src="./path/to/video.webm" width="300" controls="controls"></video>
        <button on-click="{{addTrack}}">Add Track</button>
        <template bind="{{$.testVideo.textTracks}}">

Item count: {{length}}

                <template repeat>

{{kind}}

                </template>

        </template>
    </template>

</polymer-element>

a binding would be useful because editing cues and tracks will folow

A: I would suggest something like the following:

<link rel="import" href="//www.polymer-project.org/components/polymer/polymer.html">

<polymer-element name="video-timeline" attributes="src">
  <template>

      <video id="testVideo" src="{{src}}" width="300" controls></video>

    <button on-tap="{{addTrack}}">Add Track</button>

Item count: {{textTracks.length}}

      <template repeat="{{textTrack in textTracks}}">

{{textTrack.kind}}

      </template>

  </template>

</polymer-element>

<video-timeline src="http://v2v.cc/~j/theora_testsuite/320x240.ogg"></video-timeline>

One of the problems with your approach is that Polymer's mutation observers can't detect when textTracks are added to $.testVideo. The syntax you were using for your repeated template was also incorrect.
The approach I went with uses an array defined on the Polymer element (this.textTracks) as a sort of proxy, and updates the contents of the array each time you add a new track.
This should work for your stated use case, with the caveat that if your <video>'s tracks get updated outside of the addTrack() handler, the array won't be updated and the rendered <template repeat="{{}}"> will be inaccurate.


text:
Q: Read data sent from ajax to jsp page using jstl I have an ajax call to a jsp page with certain data.
$.ajax({

    type: "POST",

    url: "jsp/order.jsp",
    data: {
        "dishId"                    :   id,
        "dishPrice"                 :   price,
        "dishName"                  :   name

          },
    success: function(msg) {
        alert(msg);
          }
    });

I want to read the data in the order.jsp using jstl. However I am not able to do that using the following statements.
<c:out value='${dishName}' />
<c:out value='${dishId}' />

I know it can be done using scriptlets but wanted to do it using jstl.

A: All HTTP request parameters are in EL available via implicit ${param} mapping.
So, this should do:
<c:out value="${param.dishName}" />
<c:out value="${param.dishId}" />

See also:

*

*Java EE 5 tutorial - Expression Language - Implicit Objects

Unrelated to the concrete problem, do note that there's quite a difference between "JSTL" and "EL". Those <c:xxx> things are JSTL tags. Those ${...} things is EL. You can also use EL standalone:
${param.dishName}
${param.dishId}

However, that opens a potential XSS attack hole, hence the need for <c:out> to escape it.
And, you'd better use a servlet instead of a JSP to deal with HTTP requests. See also How to use Servlets and Ajax?.


text:
Q: how to use ldid to install invalidly signed app I'm running Windows testing some iOS code from GitHub that other developers have been writing. Up until a few days ago I was using MacBuildServer to build the code and install the app. MacBuildServer had their enterprise cert revoked so now I can only build apps with invalid cert. I'm looking for a way to get this app to run on my jailbroken iPhone only.
How can I use ldid or similar to install and run an application signed with the invalid MacBuildServer enterprise license? Or how can I just build code and run it from my iPhone without using MacBuildServer?
I tried copying the .ipa over to my iPhone and running ldid -S myApp.ipa but that resulted in _assert(0:Swap(mach_header_->magic) == MH_MAGIC). It appears ldid needs a .app but I don't know how to generate that.
When answering keep in mind I don't have a Mac available and getting a hold of Linux will take a decent amount of time so a Windows solution is preferred.

A: You need to sign app binary; ldid is for signing application binaries. ipa is just a zip archive. Extract .app folder from it and sign application binary with ldid.


text:
Q: Google Map in not Visible in android marshmallow? Google Map not showing in marshmallow device when build an app at API level greater than 23 but it showing correctly below marshmallow version.I have used MapView.
Actally i am getting Current lat lang (0,0) in Marshmallow that's why i am facing issue in marshmallow.For getting current lat lang i am using this line:-
private void getCurrentLatLong() {
    try {
        gps = new GPSTracker(getActivity());

        if (gps.canGetLocation()) {

            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();

            System.out.println("latitude print==" + latitude);

            lat = String.valueOf(latitude);
            lng = String.valueOf(longitude);
            System.out.println("lat long check====" + "lati :" + lat + " -- lng :" + lng);

            if (lat.equalsIgnoreCase("0.0") || lng.equalsIgnoreCase("0.0")) {
                getCurrentLatLong();
            } else {
                mMapView.onResume();
                setMap();
            }

        } else {
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            gps.showSettingsAlert();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

A: Grant app permissions first, Setting -> Your App -> Permission -> enabled require permission


text:
Q: Using jq to extract certain info from JSON file I am extracting some info from my json files that are formatted like this:
{
    "name": "value",
    "website": "https://google.com",
    "type" : "money",
    "some": "0",
    "something_else": "0",
    "something_new": "0",
    "test": [
      {"Web" : "target1.com", "type" : "2" },
      {"Web" : "target2.com", "type" : "3" },
      {"Web" : "target3.com", "type" : "3" },
      {"Web" : "target3.com", "type" : "3" }
    ]
}

I am aware that jq -r .test[].Web will output:
target1.com
target2.com
target3.com

but what if I only want to get the values with type is 3 meaning the output will only show target2.com and target3.com

A: $ jq -r '.test[] | select(.type == "3").Web' file.json
target2.com
target3.com
target3.com

This passes the .test[] nodes to select, which filters its input using the .type == "3" selector. Then it selects .Web from the filtered list.


text:
Q: WooCommerce product admin : get product images attachements in edition page not working? I am desperately trying to get back the attached images of a product in the Woocommerce publishing interface but it does not work.
My script works when I am in the editing of a post but not in the "editing of a product" part of Woocommerce.
I think it's related to the fact that a product is a particular post, but I don't see what to change to make it work.
I went through the creation of a plugin in order not to touch the file "functions.php" of my Divi theme.
My code :
global $pagenow;

if (( $pagenow == 'post.php' ) || (get_post_type() == 'post')) {
$postId = $_GET['post'];

$post = array();

$post = get_post( $postId );

$args = array(
    'post_parent'    => $post->ID,
    'post_status' => 'inherit',
    'post_type'      => 'attachment',
    'post_mime_type' => 'image',
    'posts_per_page' => -1,
    'orderby'        => 'menu_order',
    'order'          => 'ASC',
);

$args = apply_filters( 'get_attached_media_args', $args, $type, $post );
$children = get_children( $args );
$images = array();
$images = apply_filters( 'get_attached_media', $children, $type, $post );

var_dump($images);
exit;
Thanks a lot !


text:
Q: Echo the value inside html input type=file I have a html form to upload files. After uploading if user need to edit the details the form is shown again with the data values populated from the database. How could i possibly show previous values of the uploaded files in the input type=file.
To be more specific this is my form:
<form>

    <input id="equipmentname" type="text" value="<?php if(isset($equipment)){ echo $equipment[0]->equipmentname;} ?>" name="equipmentname" />

    <input type="file" id="userfile" name="userfile" size="20" onChange="getImage(event);" />

    <input id="createEquipmentBtnCreate" name="file_upload" type="submit" value="Add" class="btnCreate" onclick="checkEquipmentCreateForm(event);" />
    <input id="createEquipmentBtnCancel" type="button" value="Cancel" class="btnCancel" onclick="closeSitePopUp('EquipmentCreateForm');" />

</form>

Like i have echoed the 'equipmentname' in its textfield How could i possibly show the previous upload file value in its respective inputfield. Any suggestions are welcome. Thanks.

A: You can't pre-populate a file form field.
A possible solution is to have an extra field or bit of html to "show" the value.
For example, assuming your file upload is an image and you are storing the path in your database, add an image element to show the image.
<form>

    <input id="equipmentname" type="text" value="<?php if(isset($equipment)){ echo $equipment[0]->equipmentname;} ?>" name="equipmentname" />

    <input type="file" id="userfile" name="userfile" size="20" onChange="getImage(event);" />

  <?php
  if (strlen($equipment[0]->imagePath) > 0) {
  ?>
  <img src="<?php $equipment[0]->imagePath; ?>" alt="image preview" />
  <?php
  }
  ?>

    <input id="createEquipmentBtnCreate" name="file_upload" type="submit" value="Add" class="btnCreate" onclick="checkEquipmentCreateForm(event);" />
    <input id="createEquipmentBtnCancel" type="button" value="Cancel" class="btnCancel" onclick="closeSitePopUp('EquipmentCreateForm');" />

</form>

If the upload was a doc file, then you could show a thumbnail image that represents a doc file, there are plenty about.


text:
Q: separate string if they had extensions vb net I'm working in a program to download all the attachments linked to one record on database, the record on database is stored like "attach1.pdf attach2.docx".
How could i separate in two differents strings?
Something like this:
string1=Attach1.pdf
string2=attach2.docx

A: Dim fileNames As String() = String.Split({" "c})

Space delimiting file names is incredibly dumb since most filesystems consider the space character to be a valid path character.


text:
Q: JSON schema for XML I am trying to get the JSON structure for this specific xml structure
XML:
<categories>
  <category id="12">Deals</category>
  <category id="15">Navigation</category>
  <category id="16">Personalization</category>
</categories>

If I try JSON structure like this
{
  "categories": {
  {
   "category": "Products and Services",
   "id": "13"
   },
   {
    "category": "Customer Service",
    "id": "913",
    }
  }
}

I get array of categories like this.
<?xml version="1.0" encoding="UTF-8" ?>
<root>
  <categories>
    <category>Products and Services</category>
    <id>13</id>
  </categories>
  <categories>
    <category>Products and Services</category>
    <id>913</id>
  </categories>
</root>

I am trying to get one categories element with arrays for category. I do not want to lose ID nor the value held by category element.
Could you please suggest me how do I get JSON for the given XML without losing the attribute within the element, element value and also without creating multiple categories? Thanks in advance

A: There's no definitive mapping from XML to JSON or vice-versa: there isn't a single right answer to your question. Nor have you really explained what you are trying to achieve.
The most natural way of representing the same information in JSON is probably like this:
[
  { "id":12, "value":"Deals" },
  { "id":15, "value":"Navigation" },
  { "id":16, "value":"Personalization" }
]

and this reflects that fact that in XML, "objects" have to be named but "values" don't, whereas in JSON, "objects" aren't normally named but values always are.
So you can immediately see that no tool is going to be able to automatically convert from the most natural XML representation of the data to the most natural JSON representation, or vice versa, because each representation contains something that is missing in the other.


text:
Q: Laravel facebook-sdk bundle logout not working I am using Facebook-sdk bundle for Laravel and everything works fine, except the logout link. When I click logout, I get redirected and all looks like it is working, but when it loads the page back, I'm still logged in?
Is this a Laravel problem maybe? Does it store sessions differently?
I've built this class, but as I said, I don't think this is a problem because all is working fine, except logout session is not getting cleared.
Code:

class Fb{

    // -----------------------------------------------------------------------
    // Variables

    private $ioc; // IOC container

    public $state; // If logged or not

    public $data; // Data that came from request
    public $settings = array("name,gender");

    // -----------------------------------------------------------------------
    // Logical functions
    public function __construct(){
        $this->ioc = IoC::resolve('facebook-sdk');

        if ($this->getUser()) {
            try {
                $this->request();
                $this->state = true;
            } catch (FacebookApiException $e) {
                error_log($e);
        }
        }else{
            $this->state = false;
        }
    }

    public function getUser(){
        return $this->ioc->getUser();
    }

    public function request(){
        $this->data = $this->ioc->api("/me?fields=".implode($this->settings));
    }

    public function debug(){
        return dd($this->data);
    }

    // -----------------------------------------------------------------------
    // Login & Logout links

    public function login(){
        return $this->ioc->getLoginUrl();
    }

    public function logout(){
        return $this->ioc->getLogoutUrl();
    }

    // -----------------------------------------------------------------------
    // Get data via SDK

    // Name
    public function name(){
        return $this->data['name'];
    }

    // Picture
    public function picture($w=50,$h=50){
        return "https://graph.facebook.com/". $this->data['id'] ."/picture?width=$w&height=$h";
    }

    // Gender
    public function gender(){
        return $this->data['gender'];
    }

}

Thanks for any help!
Cheers!

A: The underlying facebook php sdk uses the built in php sessions (by default) to store persistent information like the authenticated facebook user's id.
However the sdk won't destroy this information on its own since it's difficult to tell when that should happen automatically.
You can clear this persisted information with the destroySession method on the facebook sdk object. The best place to call this method is on the logout url's redirect back endpoint, since that is where the visitor gets directly after facebook done with it's own logout.
This would look like:
// method on Fb class
public function destroySession() {
    // just forward the call down to the sdk object
    $this->ioc->destroySession();
}

You probably want to set up a route where users will arrive after logout and pass it into getLogoutUrl() like this:
// method on Fb class
public function logout(){
    // tell explicity where to send the user when facebook is done, otherwise the current url will be used
    return $this->ioc->getLogoutUrl(array('next' => URL::to_route('after_logout')));
}

And have a route like this:
Route::get('after_logout', array('as' => 'after_logout', 'do' => function() {
    $fb = new Fb();
    // call the session clearing
    $fb->destroySession();
    // send the user to its merry way
    return Redirect::to('/');

}));


text:
Q: Point custom domain to GCP cloud function without Firebase Has anyone found a way to point a custom domain to a GCP cloud function without using Firebase? I have a series of cloud functions in a repo already configured to work with Cloud Build CI/CD. Everything is running great, all I need to add is the vanity domain to mask the default trigger URLs. The last thing I want to do is restructure the whole project to fit in with Firebase's sugary way of doing things just to enable this one little thing.
This is straightforward to do in AWS without having to resort to their "easy to use" abstraction products like EB, so I'm not sure why GCP wouldn't expose this more clearly if it's possible.

A: Looks like there is a way, load balancing to a Cloud Function backend was made possible last year.
https://cloud.google.com/blog/products/networking/better-load-balancing-for-app-engine-cloud-run-and-functions
You need to create a serverless endpoint network group in the process but no big deal.
Would be great if the docs pointed one down this road as well, as opposed to just using Firebase hosting.


text:
Q: debug-on-error vs. debug-on-signal (in json.el in particular) My expectation would be for debug-on-error to trap most anomalous events and show me what went wrong.  However, this is not the case with json.el which uses signal instead of error.
The documentation cautions against using debug-on-signal and my brief experimentation with it pretty much confirms this -- there are signals all over the place, so I would have to trap on just the json-* signals to get anything useful out of this.  But I can't get even that to work.
I was about to submit a bug report for json.el but I feel that I may be missing something.  Is there a good, established reason why json.el prefers signal over error?
Steps to repro:
(require 'json)
(setq debug-on-error t
      debug-on-signal t)  ; "json" ; '("json") ;; Still nothing
(json-read-from-string "")

Somewhat more realistically, you would have an actual, real-life problem when you pass the output from something to json-read (or one of its convenience wrappers json-read-from-string, json-read-file, json-read-object, etc)  and it doesn't contain what you expect.
The result, even with debug-on-signal set to t, is the following text in the *Messages* buffer, and not much else:
with no indication as to the source of the error, or anything.  (In real code with a similar problem, I was seeing if: End of file during parsing .)

A: In fact, the default value of debug-ignore-errors includes end-of-file so you have to remove that to be able to debug this particular problem.
(delete 'end-of-file debug-ignored-errors)

or perhaps more realistically
(let (debug-ignored-errors)
   (json-something))

to temporarily override the value of debug-ignored-errors for the duration of the json-something call.
... and then you don't need debug-on-signal at all.
So my speculation that the use of signal instead of error causes the problematic behavior turned out to be false.


text:
Q: call_user_func_array() errors after migrating site with InstantWP I am setting up a WordPress site locally from a site online. I downloaded the files and database. I used InstantWP to set up the site. I imported the database and moved over the proper files for the local site. When I go to the site, I get these errors:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'wp_maybe_load_embeds' not found or invalid function name in C:\Users\William\Desktop\InstantWP_4.5\iwpserver\htdocs\wordpress\wp-includes\plugin.php on line 525
Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'rest_cookie_collect_status' not found or invalid function name in C:\Users\William\Desktop\InstantWP_4.5\iwpserver\htdocs\wordpress\wp-includes\plugin.php on line 525
Fatal error: Class 'WP_User' not found in C:\Users\William\Desktop\InstantWP_4.5\iwpserver\htdocs\wordpress\wp-includes\pluggable.php on line 38

Can someone explain to me what these are and how I can fix them?

A: This looks like a migration issue. Did you made sure you've updated the link of your local WordPress install to your new URL?
Changing the home and siteurl in your wp_options table is not enough unfortunately. You will still have your post content with your non-localhost URL (http://web.site) causing your website to not display properly on your localhost.
You should have the wp_options table on your localhost copy. Everything should be intact. To make sure exported your database from your live site correctly, please follow these quick instructions provided by WordPress.
Once you've downloaded and imported your database to your localhost. Follow these steps:

*

*Go and download Interconnect IT's Database Search & Replace Script here

*Unzip the file and drop the folder in your localhost where your WordPress is installed (the root) and rename the folder to replace (screenshot)

*Navigate to the new folder you created in your browser (ex: http://localhost/wordpress/replace) and you will see the search/replace tool

*It should be pretty self-explanatory up to this point: enter your old URL in the search for… field and the new URL in the replace with… field

You can click the dry run button under actions to see what it will be replacing before you execute the script. Once you're done be sure to remove the /replace/ folder.

A: The issue was actually with the database.  I had to bring it down and install again and it worked out.  Thanks for the help from everyone.


text:
Q: Reading text file using read_csv with regex dilimiter I've been trying to read a text file university_towns.txt using read_csv, but as shown in the screenshot, on parsing the file using the regex delimiter as shown in the code below , I get an error of :

ParserError: Expected 2 fields in line 89, saw 3. Error could possibly
  be due to quotes being ignored when a multi-char delimiter is used.

Is there any way to fix this, it seems only the double quotes are at fault at one place , also kindly explain why this is happening? I also tried to use the quotechar argument, but didn't understand how to use it.
My code for reading the file is as below:
university_towns = pd.read_csv('university_towns.txt', sep= "\s\(", engine='python', header=None)

university_towns.txt file image
Annville (Lebanon Valley College)[2]
Bethlehem (Lehigh University, Moravian College)
Bloomsburg (Bloomsburg University of Pennsylvania)[2]
Bradford (University of Pittsburgh at Bradford)
California (California University of Pennsylvania)[2]
Carlisle (Dickinson College)
Cecil B. Moore, Philadelphia, also known as "Templetown" (Temple University)
Clarion (Clarion University of Pennsylvania)[2]
Collegeville (Ursinus College)
Cresson (Mount Aloysius College)[2]
East Stroudsburg (East Stroudsburg University of Pennsylvania)[2]
Edinboro (Edinboro University of Pennsylvania)[2]
Erie (Gannon University, Mercyhurst College, Penn State Erie)
Gettysburg (Gettysburg College)[2]
Greensburg (Seton Hill University, University of Pittsburgh at Greensburg)
Grove City (Grove City College)[2]
Huntingdon (Juniata College)[2]
Indiana (Indiana University of Pennsylvania)[2]
Johnstown (University of Pittsburgh at Johnstown)
Kutztown (Kutztown University of Pennsylvania)[2]
Lancaster (Franklin & Marshall)
Carrollton (University of West Georgia)[2]*Dahlonega (North Georgia College & State University)[2]

Above I've pasted some of the lines for the text file. Also, the last line is line 89.

A: Show column 83, some others can be seen here - I think there are two ( - \s\( there. At least that's what this error message means. Other possible problem is that there is strange character there, and the parser is simply lost. I don't think it is possible with university names... Anyway - look into that line. If that is not obvious - share it with us.

A: Your textsampe does not reproduce the error. You can get hints what causes the error by adding some params to the call:
pd.read_csv('university_towns.txt', sep= "\s\(",
            engine='python', header=None ,
            error_bad_lines= False, warn_bad_lines = True)

See pandas.read_csv()

Using
# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html

import pandas as pd

with open( 'university_towns.txt', "w") as f:
    f.write("""Annville (Lebanon Valley College)[2]
Bethlehem (Lehigh University, Moravian College)
Bloomsburg (Bloomsburg University of Pennsylvania)[2]
Carrollton (University of West Georgia)[2]*Dahlonega (North Georgia College & State University)[2]""")

university_towns = pd.read_csv('university_towns.txt', sep= "\s\(", engine='python', header=None)

print(university_towns)

does reproduce your error. Reason being that the last line (which looks as if it should have been seperates line) includes 2 matches for your regex, hence wants to be split into 3 columns where all other rows only got 2 columns. => Error.
To fix it, split the offending line into 2:
Annville (Lebanon Valley College)[2]
Bethlehem (Lehigh University, Moravian College)
Bloomsburg (Bloomsburg University of Pennsylvania)[2]
Carrollton (University of West Georgia)[2]
Dahlonega (North Georgia College & State University)[2]

and it will work.


text:
Q: How to simulate HTTP post request using Python Requests module? This is the module that I'm trying to use and there is a form I'm trying to fill automatically. The reason I'd like to use Requests over Mechanize is because with Mechanize, I have to load the login page first before I can fill it out and submit, whereas with Requests, I can skip the loading stage and go straight to POSTing the message (hopefully). Basically, I'm trying to make the login process consume as little bandwidth as possible.
My second question is, after the login process and the redirection, is it possible to not fully download the whole page, but to only retrieve the page title? Basically, the title alone will tell me if the login succeeded or not, so I want to minimize bandwidth usage.
I'm kind of a noob when it comes to HTTP requests and whatnot, so any help would be appreciated. FYI, this is for a school project.
edit The first part of the question has been answered. My question now is for the second part

A: Some example code:
import requests

URL = 'https://www.yourlibrary.ca/account/index.cfm'
payload = {
    'barcode': 'your user name/login',
    'telephone_primary': 'your password',
    'persistent': '1'  # remember me
}

session = requests.session()
r = requests.post(URL, data=payload)
print r.cookies

The first step is to look at your source page and identify the form element that is being submitted (use Firebug/Chrome/IE tools whatever (or just looking at the source)). Then find the input elements and identify the required name attributes (see above).
The URL you provided happens to have a "Remember Me", which although I haven't tried (because I can't), implies it'll issue a cookie for a period of time to avoid further logins -- that cookies is kept in the request.session.
Then just use session.get(someurl, ...) to retrieve pages etc...

A: In order to use authentication within a requests get or post function you just supply the auth argument. Like this:
response = requests.get(url, auth = ('username', 'password'))
Refer to the Requests Authentication Documentation for more detailed info.
Using Chrome's developer tools you can inspect the elements of your html page that contains the form that you would like to fill out and submit. For an explanation of how this is done go here. You can find the data that you need to populate your post request's data argument. If you are not worried about verifying the security certificate of the site you are accessing then you can also specify that in the get argument list.
If your html page has these elements to use for your web form posting:
<textarea id="text" class="wikitext" name="text" cols="80" rows="20">
This is where your edited text will go
</textarea>
<input type="submit" id="save" name="save" value="Submit changes">

Then the python code to post to this form is as follows:
import requests
from bs4 import BeautifulSoup

url = "http://www.someurl.com"

username = "your_username"
password = "your_password"

response = requests.get(url, auth=(username, password), verify=False)

# Getting the text of the page from the response data
page = BeautifulSoup(response.text)

# Finding the text contained in a specific element, for instance, the
# textarea element that contains the area where you would write a forum post
txt = page.find('textarea', id="text").string

# Finding the value of a specific attribute with name = "version" and
# extracting the contents of the value attribute
tag = page.find('input', attrs = {'name':'version'})
ver = tag['value']

# Changing the text to whatever you want
txt = "Your text here, this will be what is written to the textarea for the post"

# construct the POST request
form_data = {
    'save' : 'Submit changes'
    'text' : txt
}

post = requests.post(url,auth=(username, password),data=form_data,verify=False)


text:
Q: UIView bounds from storyboard are not changing in code I have a UIView which has in the storyboard a width of 250.0 and a height of 135.0. Because of autolayout the values should change when using different devices. But I always get (0.0, 0.0, 250.0, 135.0) whenever I try to print(myUIView.bounds).
Is there a way to get the real value of the bounds?

A: It depends, where are you printing them?  In viewDidLoad, they won't be adjusted for layout yet. In layoutSubviews, after the call to super, the frame should be adjusted.

A: I had the same problem. You need to do it this way:
class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
}

override func viewDidLayoutSubviews() {

// put in your code that needs adjusted layout here

}

}


text:
Q: style.css.erb precompile assets gives undefined method `[]' for nil:NilClass error I have created one file for the fonts in the stylesheets folder in rails application
@font-face {
 font-family: 'MuseoSans500';
 src: url("<%= asset_path('museosans_500-webfont.eot?')%>") format('embedded-opentype');
 font-weight: normal;
 font-style: normal;
 }

@font-face {
 font-family: 'MuseoSans500';
 src: url("<%= asset_path('museosans_500-webfont.woff')%>") format('woff'),
   url("<%= asset_path('museosans_500-webfont.ttf')%>") format('truetype'),
   url("<%= asset_path('museosans_500-webfont.svg#MuseoSans500')%>") format('svg');
font-weight: normal;
font-style: normal;
}

Now When I precompile the assets .. It gives me error on the style.css.erb page.
I have kept trace on the sprockets for the path and I got this file.
The error is
paths  subpath /home/new_app/app/assets/stylesheets/app-theme/themes/default/style.css.erb
rake aborted!
undefined method `[]' for nil:NilClass

(in /home/hbror/applications/survey/app/assets/stylesheets/application.css)

A: You should place your fonts in a new asset directory, for example app/assets/fonts and include it in asset directories by placing this in your application.rb:
# Add the fonts path
config.assets.paths << Rails.root.join('app', 'assets', 'fonts')

# Precompile additional assets
config.assets.precompile += %w( .svg .eot .woff .ttf )

Then it should work fine.


text:
Q: Assign values from one member of a group to another in R I have height data for siblings nested in families of two siblings each:
   ID family sibling height
1   1      1       1    103
2   2      1       2    100
3   3      2       1    102
4   4      2       2     98
5   5      3       1    104
6   6      3       2    100
7   7      4       1     98
8   8      4       2     94
9   9      5       1     95
10 10      5       2    111
11 11      6       1    112
12 12      6       2    113

Using R, in each family, I would like to create a new variable with each sibling assigned the value of his or her co-sibling's height, like so:
   ID family sibling height cosib_height
1   1      1       1    103          100
2   2      1       2    100          103
3   3      2       1    102           98
4   4      2       2     98          102
5   5      3       1    104          100
6   6      3       2    100          104
7   7      4       1     98           94
8   8      4       2     94           98
9   9      5       1     95          111
10 10      5       2    111           95
11 11      6       1    112          113
12 12      6       2    113          112

It is easy to aggregate across the two members of the family, for instance to find the mean height of each family, but I haven't been able to figure out how to assign each individual his or her co-sibling's height.
I suspect it can be done using the reshape or plyr packages, but I have so far had no luck in doing so.
EDIT: Another complication is that in the real data I am working with, occasionally one or both siblings in a family will be missing height data (NA for height). Any solutions that will still work when height is sometimes missing would be very much appreciated.
Thank you!

A: If your data is called dat this works:
dat$cosib_height <- unlist(lapply(split(dat$height, dat$family), rev))

##    ID family sibling height cosib_height
## 1   1      1       1    103          100
## 2   2      1       2    100          103
## 3   3      2       1    102           98
## 4   4      2       2     98          102
## 5   5      3       1    104          100
## 6   6      3       2    100          104
## 7   7      4       1     98           94
## 8   8      4       2     94           98
## 9   9      5       1     95          111
## 10 10      5       2    111           95
## 11 11      6       1    112          113
## 12 12      6       2    113          112

A variant:
dat <- transform(dat, cosib_height = ave(height, family, FUN=rev))


text:
Q: Getting Code onto Arduino Bluetooth I just received my ArduinoBT in the mail, and was a little confused about how to get code onto it. Typically, you can upload it via USB through the Arduino IDE.
I have a vague understanding of what a bootloader is - which comes pre-installed on the ArduinoBT, but I don't understand how I can get the code to the bootloader.
The docs suggest that you can still connect via the IDE and they provide the default name of the device, along with a default password. However, wouldn't I need some sort of BlueTooth receiver on my PC to achieve communication with the ArduinoBT?
Do I have to have an AVR ISP Programmer? Is there another way to get code on the device?

A: The ArduinoBT, after pairing, exposes a virtual serial port that you can use.
After that, you connect to it using the Arduino IDE over that virtual serial port.
So yes, you need a Bluetooth receiver on your PC for this to work, as the virtual serial port used for programming (typically provided by a virtual serial port over USB on a conventional Arduino), is now provided via the Bluetooth connection.  You'll definitely want to use that instead of a ICSP programmer.
If you don't have Bluetooth on your PC, there are addon USB adapters that provide it.

A: To use the bootloader, yes, you would have to connect to it over BlueTooth (wiring a TTL converter in between the BT module and AVR would be tricky).
If you have an ISP, you can skip over everything and directly program the AVR without any bootloaders.  BlueTooth transceivers for computers nowadays are extremely cheap, so I would pick one up to use your ArduinoBT to the fullest, but ISPs are also very handy when things go wrong or you want to graduate from Arduinos.


text:
Q: MVVM binding with Vue.js does not work as expected I'm currently making a dynamic-sized editable list component in a form.
I have at least one input field shown which is responsible for the creation of new fields as you type. If you type anything else than a whitespace character, the value of this field is added to the model and then reseted.
On the next tick, Vue updates the view and create the new input field with the letter you typed in, and I give the focus to this field so the user can continue typing as-if nothing happened for him.
So when the field is created, the model gets a new item which has the letter you typed in as its value. The problem is that when you edit the created field, the model isn't updated.
I made a JSFiddle so you can check it by yourself
itemBlured: function (idx) {
    console.log(vm.songs[idx].name); // Always print the same letter for a given field
}

The final goal of the itemBlured method is to remove the last edited entry in the model if its value is empty. But for now you can see, by opening your dev console that even if you change the value of a field, the Vue model isn't updated.
Any help or idea is welcome :)

A: I found the reason why the binding did not occured.
When dealing with <input> tags, you must use the v-model attribute instead of value to tell Vue.js to bind the input to your model, otherwise it just act as mustache template.
Hope it helps someone one day.


text:
Q: Using recursive properties ASP.NET / C# I'm looking for a way to take a generic result set and turn it into a tree structure with ASP.NET MVC using jQuery Dyantree. I've got a test class like:
public class GenericResults
{
    public string ClaimId { get; set; }
    public string DrugName { get; set; }
    public int PatientId { get; set; }

    //simulates database call, this could be any type of result set
    public static List<GenericResults> MockDatabaseCall()
    {
        return new List<GenericResults>()
        {
            new GenericResults { ClaimId = "abc", DrugName="Drug 1",  PatientId=1 },
            new GenericResults { ClaimId = "bcd", DrugName="Drug 2",  PatientId=1 },
            new GenericResults { ClaimId = "def", DrugName="Drug 3",  PatientId=1 },
            new GenericResults { ClaimId = "fgi", DrugName="Drug 4",  PatientId=1 },
            new GenericResults { ClaimId = "ijk", DrugName="Drug 5",  PatientId=2 },
            new GenericResults { ClaimId = "klm", DrugName="Drug 6",  PatientId=2 },
            new GenericResults { ClaimId = "mno", DrugName="Drug 7",  PatientId=2 },
            new GenericResults { ClaimId = "pqr", DrugName="Drug 8",  PatientId=2 },
            new GenericResults { ClaimId = "qrs", DrugName="Drug 9",  PatientId=2 },
            new GenericResults { ClaimId = "stu", DrugName="Drug 10", PatientId=2 },
        };
    }
}

The structure the data needs to be in for Dynatree is like:
public string Title { get; set; }
public List<TreeView> Children { get; set; }
public bool IsFolder
{
    get
    {
        return this.Children.Count > 0;
    }
}

In this example, we really don't need the ClaimId property, but I want to reuse stored procedures I've already written to feed to the trees so I wanted to include it. I need what has been grouped on to become its own TreeView object, and the Children property to be all the records that have the value of what was grouped on.  So far the MockDatabaseCallMethod, if I grouped on PatientId I would need two  TreeView objects: one for each unique PatientId.  I would like to be able to do this recursively, but not sure how because some items will be leaves (no children) and that's fine.  Here's my attempt:
public class TreeView
{
    public string Title
    {
        get;
        set;
    }

    public List<TreeView> Children { get; set; }

    public bool IsFolder
    {
        get
        {
            return this.Children.Count > 0;
        }
    }

    //made void for the time being to limit compilation errors
    public static void ListToTree(string displayName,string groupedOn)
    {
        //seed data
        List<GenericResults> results = GenericResults.MockDatabaseCall();

        //"group" on the property passed by the user
        var query = results.Select(x => x.GetType().GetProperty(groupedOn).GetValue(x,null)).Distinct();

        foreach (var i in query)
        {
            var treeView = new TreeView();
            treeView.Title = displayName;

            //iterate over results, if object has the property value of what's currently being iterated over
            //create a new TreeView object for it
            treeView.Children = results.Where(x => x.GetType().GetProperty(groupedOn).GetValue(x, null) == i)
                                       .Select(n => new TreeView
                                                    {
                                                        Title = displayName,
                                                        Children = x <--no idea what to do here
                                                    });
        }
    }
}

Ideally, I'd like a ToTree extension method, but at first I'd like to get some pointers on this.  Thanks :)

A: I'm not sure if I understood you correctly but if I did I would suggest the following solution:
-) In TreeView change the property public List<TreeView> Children { get; set; } to public IEnumerable<GenericResults> Children { get; set; }.
-) Replace your void ListToTree(string displayName method with the following one:
public static List<TreeView> ListToTree(string displayName, string groupedOn)
{
    //seed data
    List<GenericResults> results = GenericResults.MockDatabaseCall();

    List<TreeView> trees = new List<TreeView>();

    //"group" on the property passed by the user
    var query = results.Select(x => x.GetType().GetProperty(groupedOn).GetValue(x, null)).Distinct();

    foreach (int i in query)
    {
        var treeView = new TreeView();
        treeView.Title = displayName;
        treeView.Children = results.Where(x => ((int)x.GetType().GetProperty(groupedOn).GetValue(x, null)) == i);

        trees.Add(treeView);
    }

    return trees;
}

I'm not sure however, if I understood you correctly ;-)


text:
Q: Show
* from bottom to top excuse my English if I have a mistake.
I want to show a list like this in HTML5:

It works perfectly, but I want to start showing the list from bottom to top, like "Watsap" messages.

A: Try position: absolute with bottom: 0
http://jsfiddle.net/FBzg7/


text:
Q: XElement descendant not working \ XElement.Parse() Here is the (simplified) XML I am currently working with:
<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="242.359" height="557.669" id="svg2" version="1.1" xmlns="http://www.w3.org/2000/svg">
    <g transform="translate(71.9446563720703,1057.6692276001)">
        <!--nodes-->
        <polygon stroke="#454545" stroke-opacity="1" stroke-width="1" fill="#00ff00" fill-opacity="1" points="11.35 -859.014 75 -822.719 138.65 -859.014 75 -895.31" />
        <text x="51.175" y="-852.249" font-family="Arial" font-size="16" fill="#121212">Node1</text>
        <ellipse fill="#00ff00" fill-opacity="1" stroke="#454545" stroke-opacity="1" stroke width="1" cx="0" cy="-571.945" rx="69.945" ry="69.945" />
        <text x="-61.945" y="-565.179" font-family="Arial" font-size="16" fill="#121212">Node2</text>
    </g>
</svg>

At a basic level, what I'm trying to accomplish is to get all of the "text" elements, not the shapes. Something as simple as:
List<XElement> textList = xml.Descendants("text").ToList();

But, this does not work. It has occurred to me that the XML may not have been serialized correctly, but I do not think this is the case. The XML is currently created with XElement.Parse() from a string. Specifically, the string is actually a SVG file, but I don't see how this would affect it's ability to act as XML. If this is why it isn't working it would be great to know that.


text:
Q: how to generate random tuples with a string included My goal is to be able to generate random tuples consisting of 3 variables. 2 be float(x,y coordinates ) and the last one a string. Each tuple should have the format of (float, float, string). I'm pretty sure the x,y is easy but i'm unsure if its possible to generate a string as the third parameter. The string should be a random choice of within a set.
For example say I have a list of strings ["one", "two" , "three"]. I would want my generated tuple to consist of two random floats and one of the strings within that set. I was thinking something similar to this code below
[(randint(0, 180), randint(0, 180)) for _ in range(100)]

Once again just to clarify i am just trying to figure out if its possible to add one the strings from the set as my 3rd variable in my tuple

A: Use random.choice
import random
strings = ['one', 'two', 'three']
[(random.randint(0, 180), random.randint(0, 180), random.choice(strings)) for _ in range(100)]

A: [(randint(0, 180), randint(0, 180)) for _ in range(100)]

This does not generate random floats, it insteads generate random integers as evident by the function name.
Instead:
[(uniform(0, 180), uniform(0, 180), choice(["one,"two","three"]) for _ in range(100)]

Note:
random.uniform generates a random float within range(0,180)
random.choice selects a random element from ["one","two","three"]

A: You could get random number for the index of the list of strings and use that to get the random string
list_of_strings = ["one", "two" , "three"]

print [(randint(0, 180), randint(0, 180), list_of_strings[randint(0, len(list_of_strings) -1 )]) for _ in range(100)]


text:
Q: Prove there exsits some $k\in \Bbb R$ such that $k^4+4t^2+5\lt0$. Deduce whether the statement is true or false.
N: If (for any $s,t \in \Bbb R, s^5-st+t^2\geq0$) then (there exsits some $k\in \Bbb R$ such that $k^4+4t^2+5\lt0$).
I'd like to ask isn't it always true that $k^4,t^2$ must be positive for any real $k$? Then $k^4+4t^2+5\lt0$ is false. But why does the question give me $s^5-st+t^2\geq0$? How is this related to the second part of the statement?
Thanks.

A: The statement in the question, for which it is asked to determine whether it is true or false, is of the form $$P \implies Q,$$ where $P,Q$ are two (simpler) statements. Thus if it happens that $P$ is false, one can conclude the statement in the question is true, independently of whether or not $Q$ is true. As noted in the OP, it happens here that $Q$ is false. I claim that $P$ is false, so no need to consider $Q$ anyway.
Now $P$ says that, for any two real numbers $s,t,$ one has $$s^5-st+t^2 \ge 0.$$
But then $P$ is false, because taking $s=-1,t=0$ this last is $(-1)^5-(-1)\cdot 0 +0^2 \ge 0,$ which computes to $-1 \ge 0,$ a false statement.


text:
Q: Match text before colon/hypen I have strings that can be in following format:

*

*A: B: C

*A - B - C

*A - B: C

*A: B - C

In all cases, I need to extract everything until B, including the colon/hypen and the space following it, so for the examples, that would be following:

*

*A:

*A -

*A -

*A:

For example 1, ^[^:]*:\s* would work
For example 2, ^[^-]*-\s* would work
For example 1, 2 and 3, ^([^-]*-|[^:]*:)\s* would work
I would like something that would give me the desired match for all examples.

A: Note that you can negate multiple characters in square brackets, so just combine your examples 1 and 2
^[^:-]*[:-]\s*

Matches any characters at the beginning that are no hyphen or colon followed by colon or hypen and spaces, if there are any
https://regex101.com/r/cK6hC7/1

A: I would make sure to avoid using * as to avoid cases with missing starting letters, and make sure to that the regex avoids both : and -
^([^:-]+[:-]\s+)
https://regex101.com/r/sX0zO0/2


text:
Q: How to scrape data that is available after events of clicks I can pull down an HTML page, but not sure how to reach text data hidden under a button click, as the data is nowhere in the page source.
from requests import get

URL = 'https://melvyl.on.worldcat.org/oclc/1076548274'
step1 = get(URL)

print(steps.text)
# how do I navigate to `Check Availability`?

I will like to get the data that is displayed interactively when you click Check Availability next to where it says UC Berkeley Libraries. That opens a box that contains the call number I'm looking for (e.g. "DT157.675 .M37 2019").

A: When you monitor Network traffic [In your browser go to More Tools > Developer Tools > Network or press Ctrl + Shift + I in for chrome browser, and select Network, and filter XHR], you will see that when you click Check Availability, the browser makes a get request to another URL to get the data.
from requests import get
from bs4 import BeautifulSoup

# Monitor Post Requests
id_ = 5689
URL = f'https://melvyl.on.worldcat.org/ajax/availabilityFulfillment/oclc/1076548274/registryId/{id_}'
params = {'editionclusteroclcnumbers': 1076548274}

response = get(URL, params=params)

soup = BeautifulSoup(response.text, 'html.parser')
class_name = "availability_call_number_cell availability_left_hand_cell"
results = soup.find('td', class_=class_name).get_text(strip=True)

print(results)
#'DT157.675 .M37 2019'

Example

Trying different places, it appears the only thing that change is id_. If you know the ids, then we can collect all data with a loop:

# Monitor Post Requests

# Lets get all ids

URL = 'https://melvyl.on.worldcat.org/ajax/availabilityFulfillment/oclc/1076548274'
params = {'editionClusterOclcNumbers': '1076548274%2C1130899029%2C1126209791'}
response = get(URL, params=params)
soup = BeautifulSoup(response.text, 'html.parser')
id_s = [item['id'].split('_')[-2] for item in soup.find_all("button", {"title":"Check Availability"})]

# get data for all ids
data = []
class_name = "availability_call_number_cell availability_left_hand_cell"
for id_ in id_s:

    URL= f'https://melvyl.on.worldcat.org/ajax/availabilityFulfillment/oclc/1076548274/registryId/{id_}'
    params = {'editionclusteroclcnumbers': 1076548274}

    response = get(URL, params=params)

    soup = BeautifulSoup(response.text, 'html.parser')

    data.append(soup.find('td', class_=class_name).get_text(strip=True))

print(data)


text:
Q: Openlayers2 proxy.php cURL settings for GeoServer We have to use a proxy to send a request to GeoServer. I created a PHP file like this.
OpenLayers.ProxyHost = "proxy.php?url=";

is Openlayers settings.
localhost/myapp/proxy.php

is my proxy adress. Proxy content is like this.
<?php
$headers = array(
    "Content-type: application/xml",
    "Content-type: text/xml",
);

 $ch = curl_init($_GET['url']);
 curl_setopt($ch, CURLOPT_HEADER, 1);
 curl_setopt($ch, CURLOPT_HTTPGET, 1);
 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
 $output = curl_exec($ch);
 curl_close($ch);
 echo $output;
?>

I am using this proxy like:
http://localhost/myapp/proxy.php?url=http://somedomain.com
Which works, such that a web page is opened.
But when I try a GeoServer WMS get query, it gives a NullPointerException error. For example:
http://myip/geoserver/app/wms is returning admin page, but
http://localhost/myapp/proxy.php?url=http://myip/geoserver/app/wms is returning:
HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Content-Type: application/xml Transfer-Encoding: chunked Date: Wed, 03 Sep 2014 14:18:11 GMT java.lang.NullPointerException null
http://myip/geoserver/app/wms?request=GetCapabilities is returning an XML page, but
http://localhost/myapp/proxy.php?url=http://myip/geoserver/app/wms?request=GetCapabilities
is returning plain text result.


text:
Q: Settings in Ubuntu 17.10 don't work I updated 17.04 to 17.10 and some settings just plain don't work. One of my problems are settings for touchpad — I want to inverse the scroll method and I want the touchpad to be disabled while I'm typing. Another problem is login screen on startup — I don't want it, and it's there. No matter what I do regarding those settings in either gnome-control-center or dconf-editor, nothing changes — I'm still stuck with inverted scrolling, login screen on startup and touchpad not being disabled while I'm typing.

A: I can partially answer some of your questions.
To try and enable "Natural Scrolling" on the touchpad, open the Settings control panel and look to see if this setting is available for your touchpad...

To disable the login screen, open the `Settings -> Details -> Users', and change the following item...

To disable the touchpad when typing, I like Touchpad Indicator GNOME Shell extension.
Find it at https://extensions.gnome.org/extension/131/touchpad-indicator/


text:
Q: Get value from KVO - returning NSConreteValue I have the following KVO observer:
 override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        if context == &kvoContext {
            if (keyPath == "transform") {
                if let transform = change![NSKeyValueChangeNewKey] {
                    print("transform: \(transform)")
                    overlay.transform = transform as! CGAffineTransform
                }
            }
        }
    }

Which prints out:
transform: CGAffineTransform: {{1, 0, 0, 1}, {0, 0}}

However, in my variable window I see transform as an NSConcreteValue:

And I crash on that last line trying to set overlay.transform:
fatal error: unexpectedly found nil while unwrapping an Optional value

How do I retrieve that value?

A: Your transform is being automatically boxed into an NSValue object. You'll need to access it like
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
  if context == &kvoContext {
    if (keyPath == "transform") {
      if let transform = change?[NSKeyValueChangeNewKey] as? NSValue {
        overlay.transform = transform.CGAffineTransformValue()
      }
    }
  }
}


text:
Q: Call a WCF Service from client side I am going to create a WCF service(IIS host) and it will be called from client side javascript code.
When I call a WCF from client side, is the WCF a WCF library or WCF application type?
For example:
I have the javascript below.
function AddFunds() {
    var postObject = {
        myID: myObject.myIDNumber,
        LocationID: myObject.LocationID,
        fundsToAdd: CurrencyFormatted($("#txtAddFunds").val())
};
    $.post('/OrServices/myService.svc/AddFunds',
        JSON.stringify(postObject)
        ).success(AddFundsResult);
}

In the beginning, I have to create WCF Service "myService.svc", but I am not sure if it is a library or application or doesn't matter.

A: this answer describes the difference:

A service application includes a website host already setup for you. A service library is a library of services that a host can reference and startup.
If you start with a service library (recommended) you can then choose
  any host you wish (a windows service, IIS/ASP.NET, or even a console
  application) and you'd just reference your library from your new host.
  Choosing a Service Application limits your host to just IIS/ASP.NET
  (though this might be ok for your purposes, but will limit the
  protocols you can use).
Edit: Changes in IIS since I wrote this allow for a wider variety of
  protocols on ASP.NET activated services, so choosing a service
  application is much less limiting than before.

if your only going to host in IIS then I would recommend to just use a Service Application. As a lot of the work is done for you.


text:
Q: How to get the modified content from google sheets? I am trying to get the modified content after the given time from google sheets. Nowhere I can found the api to get the data. What i can see is getting modified date alone from the drive Api. How can I get the data using Drive or Sheets Api? Give me the suggestions if Possible

A: Google Drive keeps a track of revision history of files that are contained on it. There is however, no way to obtain the revisions from a request alone.
Google allows for you to receive email notifications whenever a user makes an edit to your sheet, which you can set up by completing the following steps:

*

*In the Spreadsheet's web view, click Tools -> Notification rules...

*Under Notify me at myemail@address.ext when... select Any changes are made

*Under Notify me with... select Email - right away

*Click Save.

You should also be aware that you will not get a notification for edits made to the sheet by you - notifications are only received when another user edits the sheet. Whenever you get an email notification, you will receive a link to view the changes to the spreadsheet in the form of a read-only web view link.
You can work around this programatically, though there isn't one right way and it can be quite complicated. You can use the Revisions: list method of the Drive REST API to get the information about the user that made an edit, as well as a list of links which you can use to export that revision of the sheet to another MIME Type, as shown below in the request response.
Requesting:
GET https://www.googleapis.com/drive/v3/files/SPREADSHEET_ID/revisions

with revisions/exportLinks,revisions/lastModifyingUser/emailAddress as the fields field and replacing SPREADSHEET_ID with the ID of the spreadsheet will give you a 200 response:
{
 "revisions": [
  {
   "lastModifyingUser": {
    "emailAddress": "username@domain.ext"
   },
   "exportLinks": {
    "application/x-vnd.oasis.opendocument.spreadsheet": "https://docs.google.com/spreadsheets/export?id=SPREADSHEET_ID&revision=revisionNumber&exportFormat=ods",
    "text/tab-separated-values": "https://docs.google.com/spreadsheets/export?id=SPREADSHEET_ID&revision=revisionNumber&exportFormat=tsv",
    "application/pdf": "https://docs.google.com/spreadsheets/export?id=SPREADSHEET_ID&revision=revisionNumber&exportFormat=pdf",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "https://docs.google.com/spreadsheets/export?id=SPREADSHEET_ID&revision=revisionNumber&exportFormat=xlsx",
    "text/csv": "https://docs.google.com/spreadsheets/export?id=SPREADSHEET_ID&revision=revisionNumber&exportFormat=csv",
    "application/zip": "https://docs.google.com/spreadsheets/export?id=SPREADSHEET_ID&revision=revisionNumber&exportFormat=zip",
    "application/vnd.oasis.opendocument.spreadsheet": "https://docs.google.com/spreadsheets/export?id=SPREADSHEET_ID&revision=1&exportFormat=ods"
   }
  }
 ]
}

With the links to individual changes, you can fetch and compare the different versions of the Sheet using Apps Script, and output A1 notation of the cells that have different values between versions. This, with the email address from the original Revisions: list request, is enough to compile a file or a log containing.
You can put this into a simple onEdit() trigger bound to the sheet will allow you to automatically get the changes each time a user edits the sheet.


text:
Q: Change the default sorting order in Thunderbird Thunderbird (2.something here as 3 is still not stable and had some nasty bugs last I tried) sorts mails by date by default. This is fine, however, it sorts them so that the newest ones are at the bottom of the list, which ... is not fine. Since Thunderbird saves its sort settings on a per-folder basis (and I have many folders) I regularly run into folders I've rarely or never been in which still have the old sorting order.
Is there any way to globally change the default sorting order to "Threads, newest messages at the top" (or anything else, which, I assume might be possible as well then)?

A: Finding this in 2020, just in case someone else finds this, there is an alternative to the above methods to set an ordering and apply it to all of the folders:

*

*Go into one folder (eg: Inbox) and set the date ordering by clicking on the "Date" heading.

*Right click on the "Date" heading (or any of the other headings, actually) and select "Apply columns to" > "Folder and its children" > [Your mailbox name] > [Your mailbox name (top item in the list).

... this will apply the sorting to all folders, and has the advantage of not requiring you to edit config files.
Bonus/Warning:  This will also apply reordering of columns, additions of columns, etc... to those folders, too (but that was desired in my case).

A: In Thunderbird 45.8.0 the Config Editor (also known as about:config) can be open via
Edit → Preferences → General → Config Editor...
The option is still called mailnews.default_sort_order and is set to 1 by default.

A: Open the Config Editor from the following menu options:

Preferences > General > Config Editor

You might also find it at:

Tools > Options > Advanced > General > Config Editor

Or if you are using an older version of Thunderbird:

Preferences > Advanced > General > Config Editor

Type mailnews.default in the Filter bar to bring up a small list of preferences to configure. It will display similar to below:
Preference Name                      Status       Type        Value
mailnews.default_news_sort_order:    default      integer     x
mailnews.default_news_sort_type:     default      integer     y
mailnews.default_sort_order:         default      integer     x
mailnews.default_sort_type:          default      integer     y

In the above, replace the x and y of the value by double-clicking the name of the preference and replacing it with one of the following values as required:
x (see https://developer.mozilla.org/en/nsMsgViewSortOrder)
1 = Ascending
2 = Descending

y (see https://developer.mozilla.org/en/nsMsgViewSortType)
17 = None
18 = Date
19 = Subject
20 = Author
21 = ID (Order Received)
22 = Thread
23 = Priority
24 = Status
25 = Size
26 = Flagged
27 = Unread
28 = Recipient
29 = Location
30 = Label
31 = Junk Status
32 = Attachments
33 = Account
34 = Custom
35 = Received

So if you wanted to sort all mail by Thread, Descending (newest at top), the preferences in the config editor will look like this:
mailnews.default_sort_order:    default     integer      2
mailnews.default_sort_type:     default     integer     22

There are also default_(news_)view_flags settings (for mail and news), which allow to turn on the "Threaded" flag:
view_flags -- the second group of values can be added to one of the first group to combine effects, with several limitations:
  Unthreaded       0
  Threaded         1
  Grouped         64  [mail only (?)]

  ShowIgnored      8  [news only]
  ShowUnreadOnly  16
  ShowExpanded    32  [doesn't seem to work]
ShowUnreadOnly will check the View|Threads|Unread menu; this will cause only
unread items to be seen, but doesn't force a threaded view.

(See also: https://bugzil.la/86845#c74)

A: A simpler solution : Using the Thunderbird SortPref module.

Provides settings to control which order messages are sorted initially and by which field as well as whether to display in threaded mode. Please note this data ends up stored in each folder, so changing control values only affect new folders or those with a rebuilt index. The mechanics are described in https://bugzilla.mozilla.org/show_bug.cgi?id=86845 - this extension merely adds gloss to somebody else's actual code.

A: Using about:config (under Preferences -> Advanced -> General)
mailnews.default_news_sort_order: news sort order
mailnews.default_news_sort_type: news sort column
mailnews.default_sort_order: mail sort order
mailnews.default_sort_type: mail sort column
had this saved in a text file, got it from an article a long time ago don't remember where, but those are the values that will flip sort order.

A: Actually, in version 17.08, you just need to go to Menu > View > Sort by > Date > Descending, and voilà.

A: This is just an extension to the accepted answer, since unfortunately such types of edits are not accepted.
The only problem that the answer doesn't address is getting this applied everywhere, not only to the folders that were first opened after the change. Thanks Danation for providing the idea.

*

*Close Thunderbird

*Locate your Thunderbird profile folder (mine was under /home/my_user_name/.thunderbird)

*cd to that folder

*Run find . -name '*.msf' -print0 | xargs -0 rm

*Open Thunderbird

A: I had this same problem. I solved it by:
Clicking on the drop down menu titled as "select columns to display" when you hover over it. The menu icon is on the right of the inbox - it looks like a picture of two columns.
Tick the option "Order recieved".
This adds a new column to your inbox titled "order recieved". When you click on this title, the order of mail received will change so that newest emails are at the top of the inbox. When you're done just untick "order recieved" from the list of optional columns.


text:
Q: What happens when the average number of answers per question drops below 1? Looking at Greg Hewgill's stats graphs the number of answers per question is slowly trending downwards:

Is it going to stabilise at some point so that (on average) questions receive one answer or will it drop below 1 so that questions are no longer statistically likely to receive at least one answer? How would that affect the site and is there anything that can be done about it?

A: For it to drop (significantly) below one would imply that most questions only receive one answer and some large fraction are considered unanswerable.  There are a number of truly unanswerable questions -- questions without enough data to make even a guess as to the problem, questions on esoteric technologies with few or no other users, etc., however I don't foresee this becoming a problem in the general case.  Given the drive for reputation, I expect that the majority of questions will always have at least one answer, the fraction of unanswered questions will remain low, and there will be enough questions with multiple answers to keep the average number of answers well above one.  In the grand scheme of things, we only need one answer -- the "right" answer -- on each question for the site to work.

A: <hangs head in shame>
I'll just have to try harder.

A: I think what people don't take into account when looking at questions and answers per question may be trends in terms of industry as far as what new technologies are being released at what times.
Example: When MVC is first released, it is likely that there is a lot more activity in questions and answers due to its newness. But when there is nothing new being put out at the time, you are going to undoubtedly have a lot more esoteric or very domain specific questions which the potential audience for is limited, which will cut down on the number of answers.
I would not be surprised if when Windows 7, Visual Studio 2010, and other new things become full blown releases you will start to see an uptick in questions which the audience may be greater, leading to more answers per question.

A: The problem is that it is hard to tell (looking at the data en-masse) if 1 answer is enough. If every question was solved with just one answer, I'd consider that good (although a second/third perspective is obviously very welcome). So perhaps to understand the data we'd need to separate out the questions which are ticked, or have no tick but a highly-rated answer (most likely: the right answer, but to a drive-by user who didn't mark it complete and is now deleted through age).
You might also need to exclude CW questions, as these tend to get more than average replies; and we used to get a lot more of the "what is your favorite *" questions. I wonder if this is also skewing the answers? Most "real" questions get (from what I see) < 5 replies, in part because we've actually got some clever people on the site who have given the right answer already.
So an average of, what, 2.5 answers/question doesn't concern me.

A: I notice this a lot on Superuser, where often only one good post is needed to either answer the question or let it be known it's not possible.
"Luckily" there are still topics where there are different points of view or alternative solutions, so there will always be some distribution.
BTW: you should check how many of those questions are also accepted as the correct answer, in which case it's not necessarily bad if they are answered within one answer

A: *

*Low-hanging fruit got picked up

*More controversial/discussion-y questions got asked a year ago

I suspect TXI is correct, in that after a while, spikes of usage will show up when new ponies software versions are released into the wild.

A: It doesn't look to me like it's steadily going downward. It looks to me like it's converging to 2.5.


text:
Q: TemplateURL not working - request is not sent The template does not even appear to be being requested. I tried an absolute URL, a relative URL, and even the full-length URL.
The template is not being requested at all, I've checked.
Here is the code:
app.directive('field', function () {
    return {
        restrict: "E",
        templateURL: "http://192.9.200.62:8080/templates/field.html",
        scope : {
            field: "=name",
            ops: "=options"
        }
    };
});

Other URLs I've tried include templates/field.html and /templates/field.html and ../../templates/field.html.
The template works fine if I build it as a string in JS.

A: There are a couple things here.  First, the template path is always relative to the root.  So, if your templates directory is off the root, then this should work:
/templates/field.html

Second, the property is named templateUrl, the case matters here.  So, you need to rename templateURL to templateUrl.
Here is the documentation showing the templateUrl property.

A: I believe it should be templateUrl, not templateURL.
As far as the correct URL to use, what is the folder structure?


text:
Q: highcharts reset zoom on master detail graph I've set up a master detail chart that doesn't verge too far from the example on the highcharts api demo site (http://www.highcharts.com/demo/dynamic-master-detail).
When adding:
resetZoomButton: {
                    position: {
                        x: 0,
                        y: -15
                    }
                 }

to the detail chart, it fails to bring up a reset zoom button.  Is there a way of resetting the zoom on a master-detail graph?
my JSFiddle is here: http://jsfiddle.net/sBEMS/2/

A: You can prepare your own button with position absolute and appropriate coordinates. Then fire click event and set appropriate range by setExtremes() function.
http://api.highcharts.com/highcharts#Axis.setExtremes()


text:
Q: Safest Sister of Eve Level 4 Security Missions I'm doing Level 4 SoE for now. I got ganked in Langisi. Moved to Apanake and it seems to be a nice place. I'm thinking about moving to Osmon because it's near Jita. Which system is the safest for L4 SoE missions? Langisi, Apanake, or Osmon?
I'm using a Rattlesnake with 1.5 Bils fit. Not really blingy.

A: To strictly answer the question you asked, Osmon is sec0.7 compared to Lanngisi and Apanake which are sec0.5, meaning the concord response times are "roughly 10" resp. "19 seconds" according to this page on wiki.eveuniversity. If you can use this to your advantage and can confidently build a gank-proof rattlesnake, go there.
On the other hand, if you were to look on dotlan maps or the in-game galaxy map statistics overview by pod/player kills you'd see that (at the time of writing this answer as an example) Osmon might be the least safe system due to 4x as much traffic and 4 pod kills as opposed to none in Apanake but this does not account for faction warfare, people bullying miners, and what ever other business someone might think is a good idea to conduct.
It is also wise to look into mobile depots and figuring out how quickly you can refit yourself to maximum warp stabilizers should you get unwelcome guests (in which case the general advice is "don't shoot at yellow skulls").
All in all, the safest place to grind missions is the least convenient, your safety is ultimately an illusion, and you should always make sure that either you or someone in your crew can see a big enough picture such as map statistics (whether people are ganking missioneers), purpose of traffic and attention to local (so you can tell passers by and benign locals apart from everyone else), interceptors on d-scan, and generally just being able to gauge what business people have in your part of the galaxy.
tl;dr:
There are 3 "safe" systems, as in actually in hi-sec.

*

*Osmon is closest to jita so that one's obviously targeted by gankers.

*Lanngisi is furthest from jita (22 jumps), meaning it's the least
convenient place to gank mission runners, meaning sadly that's where
you're expected to go so that's where I'd look for an easy target.

*This leaves Apanake and it's accessible next-door industry hub which would probably attract more clueless targets.

I would advice Apanake simply because it has worked so well for me before but as always maybe I was just lucky.


text:
Q: JavaScript object literal length === undefined? I am working on this animation function but I have a problem. I can't seem to perform what should be an easy task, I can not get the length of an object. If you check out that jsFiddle you can see that I am running alert(properties.length); and it is returning undefined. Can anyone see why this might be?

A: This is supported in node.js and newer environments.
var obj = {a: "a", b: "b"};
Object.keys(obj).length // 2

A: JavaScript object simply do not have a length property, only Arrays do. If you want to know the number of properties that are defined on a object, you have to iterate over them and count them.
Also, your for in loop is prone to bugs due extension of Object.prototype since in will traverse the complete prototype chain and enumerate all the properties that are on the chain.
Example
// Poisoning Object.prototype
Object.prototype.bar = 1;

var foo = {moo: 2};
for(var i in foo) {
    console.log(i); // logs both 'moo' AND 'bar'
}

You have to use the hasOwnProperty method on the object in order to filter out those unwanted properties.
// still the foo from above
for(var i in foo) {
    if (foo.hasOwnProperty(i)) {
        console.log(i); // only logs 'moo'
    }
}

Many JavaScript frameworks out there extend the prototype, not using hasOwnProperty often leads to horrible bugs.
Update
Concerning the actual problem that your code is not animation both properties.
for(var p in properties) {
    ...
    for(var i = 0; i <= frames; i++)
    {
        setTimeout((function(exti, element) {
            return function() {

                // p gets overriden by for outer for in loop
                element.style[p] = original + (pixels * exti) + 'px';
            }

        // you need to pass in a copy of the value of p here
        // just like you do with i and element
        })(i, element), i * (1000 / 60), element);
    }
    ....
 }

A: If you are using Underscore.js, you can use _.size():
_.size({one : 1, two : 2, three : 3});
=> 3

A: Objects have no length, you'll need to use an array if you want that.
If you have to find the number of properties in an object there is only one way:
var length =0;
for(var i in obj) length++;

A: Here's @Junaid Qadir Shekhanzai's general function for "finding the length of an object" (which as we're told, should properly be called "counting the properties of an object"). It combines solutions from @Ivo Wetzel and @Martin Jespersen:
function countProperties(myObj){
    var length = 0;
    if(typeof myObj != 'object'){
        return false;
    }
    for(var i in myObj) {
    length++;
    }
    return length;
}


text:
Q: What does it mean by $x \not\in A \smallsetminus B$ when $B \subset A$? Let $B \subset A$. Then by set definition $x \not \in A \smallsetminus B$ implies $x  \not \in A$ and $x \in B$. But to me this is absurd. What is happening when $x  \not \in A \smallsetminus B$ when $B \subset A$? Thanks.

A: $x \in A \setminus B$ means $x \in A$ and $x \not\in B$. So $x \not\in A
\setminus B$ is the negation of that: $x \not \in A$ or $x \in B$.


text:
Q: Can someone walk me through how this expression simplifies to y/x? I am just wondering how this equation comes to be: it is from an economics problem involving marginal utilities. I have my two variables, $x$ and $y$.
Intuitively, how does $$\frac{0.5\times x^{-0.5}\times y^{0.5}}{0.5\times x^{0.5}\times y^{-0.5}}= \frac{y}{x}?$$
I'm guessing that the $0.5$ and $(1/2)$ both cancel out, but I am not sure what happens next.
Thank you!

A: Hint: $\frac{x^{-0.5}}{x^{0.5}}=x^{-0.5-0.5}=x^{-1}=\frac{1}{x}$ and $\frac{y^{0.5}}{y^{-0.5}}=y^{0.5-(-0.5)}=y^{0.5+0.5}=y^1=y$

A: Hint: $$x^{-0.5}=\frac{1}{x^{0.5}}=\frac{1}{\sqrt{x}}$$ and similarly $$\frac{1}{y^{-0.5}}=\frac{1}{\frac{1}{y^{0.5}}}=y^{0.5}=\sqrt{y\phantom{!}}$$ Now $$x^{0.5}\times x^{0.5}=x^{0.5+0.5}=x^1=x$$

A: $x^{0.5}=\sqrt{x}$ and $x^{-0.5}=\dfrac{1}{\sqrt{x}}$
So $(0.5x^{-0.5} \times  y^{0.5})/(0.5x^{0.5} \times  y^{-0.5}) =\dfrac{\frac12 \times \frac{1}{\sqrt{x}}\times {\sqrt{y}}}{\frac12 \times {\sqrt{x}}\times \frac{1}{\sqrt{y}}}$.
Multiply numerator and denominator by $2 \times {\sqrt{x}}\times \sqrt{y}$ to get the result.

A: Let me show you. It's just the "Multiply by one" trick:
$\frac{0.5 x^{-\frac{1}{2}} y^\frac{1}{2}}{0.5 x^\frac{1}{2} y^{-\frac{1}{2}}} \cdot 1 \cdot 1 = \frac{0.5 x^{-\frac{1}{2}} y^\frac{1}{2}}{0.5 x^\frac{1}{2} y^{-\frac{1}{2}}} \cdot \frac{y^\frac{1}{2}}{y^\frac{1}{2}} \cdot \frac{x^\frac{1}{2}}{x^\frac{1}{2}}$
You know, of course, that $a^p a^q = a^{p+q}$:
$\frac{0.5 x^{-\frac{1}{2}+\frac{1}{2}} y^{\frac{1}{2}+\frac{1}{2}}}{0.5 x^{\frac{1}{2}+\frac{1}{2}} y^{-\frac{1}{2}+\frac{1}{2}}}=\frac{0.5x^0 y^1}{0.5x^1 y^0} = \frac{y}{x}$
And there you have it :)


text:
Q: why float followed by clear What does it mean to float left, then clear left. Or float left, then clear right? Can anyone help me understand this. I'm not a CSS guy, but need to understand some of the CSS I'm working with.
#elem1{
    float:left;
    clear:left;
}

#elem2{
    float:left;
    clear:right;
}

A: If you float two elements together, they will align on the same horizontal axis if you don't apply clearing.
By telling a floating element to clear, it clears any floats that come before it, then floats itself wherever the designer intends to float it. It will go on a new line, or not, depending on the direction of the clear.
See this jsFiddle example for a visualization. The first two
s don't clear anything, while the last two
s are set to clear both left and right floats.

A: clear means to position the element below any previous floating elements, to "clear the line".
Usually floating elements pile up on the same line like this:
--- --- ---
| | | | | |
--- --- ---

Making them clear any previous floating elements will make them arrange like this:
---
| |
---
---
| |
---
---
| |
---

A: Here is a clearer view of why a clear is needed.  http://www.quirksmode.org/css/clearing.html


text:
Q: Mule 3.9 Bulk update in batch commit failing all records even if one update fails My process reads a csv file and updates the DB with the data from CSV. I want to do a bulk update but if I am using batch commit in batch process, and set commit size to 50, it works fine for success records. But if DB update statement fails for even one record, the whole commit size (50 records) are failing to update in DB. I read in mule documentation that some connectors have the ability to handle record-level errors without failing the whole batch(i.e. upsert) and Database connector is one of them. Not sure if this scenario falls under it or not. Did anyone face this kind of issue? Is there a work around this issue without doing record by record update. I would appreciate any thoughts around this issue.

A: The documentation for database bulk operations says it is up to the JDBC driver

It may happen that while some statements in the bulk operation can be
successfully executed, some may result in an error. When this occurs,
it will be up to the driver to either:

*

*Stop execution immediately and ignore all remaining operations, or

*Continue to execute the remaining statements.


text:
Q: Getting error: An expression of non-boolean type specified in a context where a condition is expected, near ',' select
DISTINCT
       mp.[DocumentGuid]
      ,mp.[CustomerSpecifcation]
      ,mp.[Pre-CleaningMeth]
      ,mp.[ComponentSurfaceCondition]
      ,mp.[CurrentType]
      ,mp.[ParticleType]
      ,mp.[Color]
      ,mp.[Type]
      ,mp.[Natural]
      ,mp.[Consumables]
      ,mp.[Examination Area/Weld]
      ,mp.[Description-Remarks]
      ,mp.[Accept]
      ,mp.[TypeOfInsp]
from
[dbo].[Magnetic Particle] mp
left join Answer a
on mp.CurrentType = a.QuestionGuid
WHERE
    (@CUSTOMERSPEC IS NULL OR REPLACE(LOWER(mp.[CustomerSpecifcation]),' ','') = REPLACE(LOWER(@CUSTOMERSPEC),' ',''))
AND (@PRECLEANINGMETH IS NULL OR (mp.[Pre-CleaningMeth] IN (@PRECLEANINGMETH) or '<[PARAMETER_EMPTY]>' in (@PRECLEANINGMETH)))
AND (@COMPSURFCONDN IS NULL OR REPLACE(LOWER(mp.[ComponentSurfaceCondition]),' ','') = REPLACE(LOWER(@COMPSURFCONDN),' ',''))
AND (@PARTICLETYPE IS NULL OR (mp.[ParticleType] IN (@PARTICLETYPE)  or '<[PARAMETER_EMPTY]>' in (@PARTICLETYPE)))
AND (@COLOR IS NULL OR REPLACE(LOWER(mp.[Color]),' ','') = REPLACE(LOWER(@COLOR),' ',''))
AND (@NATURAL IS NULL OR REPLACE(LOWER(mp.[Natural]),' ','') = REPLACE(LOWER(@NATURAL),' ',''))
AND (@CONSUMABLES IS NULL OR REPLACE(LOWER(mp.[Consumables]),' ','') = REPLACE(LOWER(@CONSUMABLES),' ',''))
AND (@EQUIPMENTTYPE IS NULL OR REPLACE(LOWER(mp.[Type]),' ','') = REPLACE(LOWER(@EQUIPMENTTYPE),' ',''))
AND (@CURRENTTYPE IS NULL OR (a.ValueAsString IN (@CURRENTTYPE) or '<[PARAMETER_EMPTY]>' in (@CURRENTTYPE)));

Below error is returned when the query is processed in Report Builder. I know for sure that this problem is with 'where in' clause but I unable to figure out the rectification.


text:
Q: How can I make my IP address appear to be from another country to watch iPlayer?
Possible Duplicate:
Make my IP address appear to be from another country

I live in Bermuda – people seem to be able to use iPlayer, which is offered by the BBC (United Kingdom). Can you help?

A: I am not really familiar with iPlayer but it is a very common thing.
If you really want to make application you connect to see your IP as address from some other country - say "United Stated" then you should connect via an intermediary server that is located in US, which will redirect the traffic back and forth.
2 options there:

*

*Proxy server, but they may not work as an application itself should
support it.

*VPN - Virtual Private Network - it will seemlessly make you appear as a part of some other network (say located in US) and it will apply encryption too.

Try google: Search for "US vpn"
Read abou VPN: VPN at Wikipedia


text:
Q: Passing nested JSON as variable in Machinebox GraphQL mutation using golang Hi there Golang experts,

*

*I am using the Machinebox "github.com/machinebox/graphql" library in golang as client for my GraphQL server.

*Mutations with single layer JSON variables work just fine

*I am, however, at a loss as to how to pass a nested JSON as a variable

*With a single layer JSON I simply create a map[string]string type and pass into the Var method. This in turn populates my graphql $data variable

*The machinebox (graphql.Request).Var method takes an empty interface{} as value so the map[string]string works fine. But embedded json simply throws an error.
code:
func Mutate(data map[string]string, mutation string) interface{} {
    client := GQLClient()

    graphqlRequest := graphql.NewRequest(mutation)
    graphqlRequest.Var("data", data)

    var graphqlResponse interface{}
    if err := client.Run(context.Background(), graphqlRequest, &graphqlResponse); err != nil {
        panic(err)
    }

    return graphqlResponse
}

Mutation:
    mutation createWfLog($data: WfLogCreateInput)
        {
        createWfLog (data: $data){
            taskGUID {
                id
                status
                notes
            }
            event
            log
            createdBy
            }
        }

data variable shape:
{
  "data": {
    "event": "Task Create",
    "taskGUID": {
      "connect": {"id": "606f46cdbbe767001a3b4707"}
    },
    "log": "my log and information",
    "createdBy": "calvin cheng"
  }
}

As mentioned, the embedded json (value of taskGUID) presents the problem. If value was simple string type, it's not an issue.

*

*Have tried using a struct to define every nesting, passed in struct.

*Have tried unmarshaling a struct to json. Same error.

Any help appreciated
Calvin

A: I have figured it out... and it is a case of my noobness with Golang.
I didn't need to do all this conversion of data or any such crazy type conversions. For some reason I got in my head everything HAD to be a map for the machinebox Var(key, value) to work
thanks to xarantolus's referenced site I was able to construct a proper strut. I populated the strut with my variable data (which was a nested json) and the mutation ran perfectly!
thanks!


text:
Q: Jade_Mixin is not a function, Windows environment I've been having an error exclusively in a Windows (8) environment with Jade; Jade will not compile because it does not recognize my mixin. The mixin is being called as such:
+MyMixin(true)
I keep getting the error that my mixin is not a function. I don't get this error in a Mac environment with the same exact code and file structure, which is why I'm confused. Jade is the latest version.

Update:
Here is the error message I get in the windows command line (terminal). I've changed the code a bit for confidentiality, however the syntax is unchanged.
[10:59:04] gulp-notify: [Gulp Error] Check your terminal
TypeError in plugin 'gulp-jade'
Message:
    C:\Users\Me\project_path\_jade_file.jade:25
    23|         -some code
    24|         -some code
  > 25|         +MyMixin
    26| // commented out
    27| more.code
    28|         -some more code

jade_mixins.MyMixin is not a function
Details:
    path: C:\Users\Me\project_path\_jade_file.jade:25


text:
Q: Terminal Server connection displays lock screen after unlocking local machine In my environment, all my users log in to their Windows 7 computer and then immediately initiate a remote session to a virtual desktop on a Server 2012 machine. All their work is done on the remote desktop; nothing run on the local machine except the RDP session. All users are in a Users OU, the local machines are in a Computers OU, and the server is in a Server OU.
Thanks to SOX compliance, I had to enable a password protected screensaver on teh local machines. No problem: just create a GPO to enable the screen saver and apply it to the Users OU. We don't want the screen saver to show up on the TS session. Again, no problem: create a loopback policy to disable the screen saver, set it to merge, and apply it to the Server OU.
The problem is that now when a user comes back from lunch or break or even just starring into space for 15 minutes, they have to log in to their local machine AND ALSO the remote session. How can I disable locking the remote session?


text:
Q: How can I improve this mysql query for fulltext search? I use the following query for searching my table. But it is very slow, how can fast or improve it?
    if ($stit0 || $sabst0 || $saut0 || $saffl0){
      $qt = "SELECT * FROM mytable WHERE (";
      if ($stit0){ $qt.="(MATCH(title) AGAINST('$stit0' IN BOOLEAN MODE))"; }
      if ($saut0){ $qt.=" AND (MATCH(authors) AGAINST('$saut0' IN BOOLEAN MODE)) "; }
      if ($sabst0){ $qt.=" AND (MATCH(abstract) AGAINST('$sabst0' IN BOOLEAN MODE))"; }
      if ($saffl0){ $qt.=" AND (MATCH(affiliation) AGAINST('$saffl0' IN BOOLEAN MODE))"; }
      if ($_GET[filter]){ $qt.=" AND (pubtype='$_GET[filter]')"; }
      $qt.=") ORDER BY year + pubdate DESC";
      $qt = str_replace("WHERE ( AND", "WHERE (", $qt);
      $qt1 = mysql_query($qt);
      $nqs = mysql_num_rows($qt1);
    }`

A: Did you declare your full-text indices? The query seems simple, so maybe an unindexed search cripples your database.
As for the query itself, I prefer forming the WHERE clause this way, saves a lot of hassle. And the query is much more readable.
// Define a list of constraints, put a default constraint on record types or whatever.
$conditions = array("someColumn = 1");
// Start collecting constraints based on already-sanitized user input
if ($someFilter) $conditions[] = "someInt = {$someFilter}";
if ($otherFilter) $conditions[] = "MATCH(textColumn) AGAINST('{$otherFilter}')";
// repeat as much as you like, the only drawback is you can't write complex logic here.
// now merge the constraints to form the where-clause
$conditions = implode(' AND ', $conditions);

// Query in heredoc is much cleaner and structured.
$query = <<<HEREDOC

SELECT * FROM yourTable
WHERE {$conditions}
ORDER BY year DESC, pubDate DESC

HEREDOC;
while ($result = mysql_fetch_assoc($query)) {
  // do your stuff
}


text:
Q: How do I discard all changes made with TinyMCE? This seems like it would be pretty easy and common but I can't seem to get it to work.
I have a button (Edit) which turns TinyMCE on for edit mode. When this happens the edit button becomes (Cancel) and if pressed TinyMCE shuts down and all changes should be lost. The text should revert back to it's original state as if nothing happened. When I press Cancel I've still got all of my edits. I'm sure I can requery the original data, but there's got to be something built in for something so common.
Here's my relevant HTML:

                @Model.CreatedMonth
                @Model.CreatedDay
                @Model.CreatedYear

@Model.Title

@Model.Body

            @foreach (var tag in Model.Tags)
            {
                @Html.Action("_TagSummary", "Tag", new { tagId = tag })
            }

Edit

Delete

Here's my relevant jQuery:
function edit() {
//Make the title and header to look editable
$('#title').css({
    border: "1px dotted #333"
});
$('#body').css({
    border: "1px dotted #333"
});

//Detatch the 'edit' handler
$('.edit').unbind();
//Change it to a 'save' event
$('.edit').html('Save').click(save);

//Detatch the 'delete' handler
$('.delete').unbind();
//Change it to a 'cancel' event
$('.delete').html('Cancel').click(cancel);

//Go into edit mode
//Prevent adding the editor over and over
if (!tinymce.activeEditor) {
    tinymce.init({
        selector: "#title",
        theme: "modern",
        language: "en",
        inline: true,
        toolbar: "undo redo",
        menubar: false,
        browser_spellcheck: true
    });

    tinymce.init({
        selector: "#body",
        theme: "modern",
        language: "en",
        inline: true,
        menubar: false,
        browser_spellcheck: true,
        plugins: [
                                "link"
        ],
        toolbar: "undo redo | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link"
    });
}
}

function cancel() {
//Make the title and header to look non-editable
$('#title').css({
    border: "none"
});
$('#body').css({
    border: "none"
});

//Detatch the 'edit' handler
$('.edit').unbind();
//Change it to a 'edit' event
$('.edit').html('Edit').click(edit);

//Detatch the 'delete' handler
$('.delete').unbind();
//Change it to a 'delete' event
$('.delete').html('Delete').click(del);

//Disable edit mode
//Only remove the current editor if it's active
if (tinymce.activeEditor) {
    //tinymce.triggerSave();
    tinymce.execCommand('mceRemoveEditor', true, tinymce.activeEditor.id);
}
}

I create 2 inline MCE editors, one for title and one for body. The edit button has binding to start up the MCE editing and once selected has new binding to shut it off. I can't get the edits to "undo" and I can't find any documentation that helps. I'm using TinyMCE 4.0.12 by the way. Thanks.

A: I am using this, TinyMCE already have information before save
{
`tinymce.bodyElement.innerHTML = tinymce.startContent`
}

A: Here is clear and working solution for v.4:
tinyMCE.activeEditor.bodyElement.innerHTML = tinyMCE.activeEditor.startContent;

Where tinyMCE is global variable.

A: I'd still be interested in seeing a more automatic way of doing this, but after reading through the TinyMCE documentation for days I don't see an easy way of doing this. Here's how I solved my own issue using jQuery. These are additions to the methods above:
function edit() {
    //Save the current state of the content
    initialBody = $('#body').html();
    initialTitle = $('#title').html();

    // Rest of the method above goes here
}

This saves the state of the data at the time the user pressed Edit. Now if the user presses Cancel I do the following:
function cancel() {

    // Rest of the method above goes here

    //Disable edit mode
    //Only remove the current editor if it's active
    if (tinymce.activeEditor) {
        tinymce.execCommand('mceRemoveEditor', true, 'title');
        tinymce.execCommand('mceRemoveEditor', true, 'body');
    }

    //Reset the content
    $('#title').html(initialTitle);
    $('#body').html(initialBody);
}

I hope this helps someone out. Let me know if there's a better way.


text:
Q: Reverse an array of integers without using Swift's object properties/methods At a last iOS Developer job interview I got a task that I didn't quite know how to do properly.
Task:
Reverse an array of integers in place.
Inputs: arr (the array), and n - which is the number of elements in arr
Allocate as little memory as possible, and don't use Swift's object properties (so basically anything you access with a dot notation e.g .reverse(), .insert(at: etc. is not allowed)

A: With tuples
func reverse(array: inout [Int], count: Int) {
    if count < 2 { return }
    var first = 0
    var last = count - 1
    while first < last {
        (array[first], array[last]) = (array[last], array[first])
        first += 1
        last -= 1
    }
}

Without tuples
func reverse(array: inout [Int], count: Int) {
    func swapAt(_ firstIndex: Int, _ secondIndex: Int) {
        let firstValue = array[firstIndex]
        array[firstIndex] = array[secondIndex]
        array[secondIndex] = firstValue
    }

    if count < 2 { return }
    var first = 0
    var last = count - 1
    while first < last {
        swapAt(first, last)
        first += 1
        last -= 1
    }
}