Programs & Examples On #Uiaccelerometer

The UIAccelerometer class lets you register to receive acceleration-related data from the onboard hardware. As a device moves, its hardware reports linear acceleration changes along the primary axes in three-dimensional space. You can use this data to detect both the current orientation of the device (relative to the ground) and any instantaneous changes to that orientation. Deprecated in iOS 5.0. Available in iOS 2.0 and later.

How to support UTF-8 encoding in Eclipse

I tried all settings mentioned in this post to build my project successfully however that didn't work for me. At last I was able to build my project successfully with mvn -DargLine=-Dfile.encoding=UTF-8 clean insall command.

What's the difference between integer class and numeric class in R

There are multiple classes that are grouped together as "numeric" classes, the 2 most common of which are double (for double precision floating point numbers) and integer. R will automatically convert between the numeric classes when needed, so for the most part it does not matter to the casual user whether the number 3 is currently stored as an integer or as a double. Most math is done using double precision, so that is often the default storage.

Sometimes you may want to specifically store a vector as integers if you know that they will never be converted to doubles (used as ID values or indexing) since integers require less storage space. But if they are going to be used in any math that will convert them to double, then it will probably be quickest to just store them as doubles to begin with.

How to see the CREATE VIEW code for a view in PostgreSQL?

Kept having to return here to look up pg_get_viewdef (how to remember that!!), so searched for a more memorable command... and got it:

\d+ viewname

You can see similar sorts of commands by typing \? at the pgsql command line.

Bonus tip: The emacs command sql-postgres makes pgsql a lot more pleasant (edit, copy, paste, command history).

SQL LEFT JOIN Subquery Alias

I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.

SELECT wpoi.order_id As No_Commande
FROM  wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id 
                            AND wpp.meta_key = '_shipping_first_name'
WHERE  wpoi.order_id =2198 

Does return stop a loop?

Yes, return stops execution and exits the function. return always** exits its function immediately, with no further execution if it's inside a for loop.

It is easily verified for yourself:

_x000D_
_x000D_
function returnMe() {
  for (var i = 0; i < 2; i++) {
    if (i === 1) return i;
  }
}

console.log(returnMe());
_x000D_
_x000D_
_x000D_

** Notes: See this other answer about the special case of try/catch/finally and this answer about how forEach loops has its own function scope will not break out of the containing function.

Using an IF Statement in a MySQL SELECT query

How to use an IF statement in the MySQL "select list":

select if (1>2, 2, 3);                         //returns 3
select if(1<2,'yes','no');                     //returns yes
SELECT IF(STRCMP('test','test1'),'no','yes');  //returns no

How to use an IF statement in the MySQL where clause search condition list:

create table penguins (id int primary key auto_increment, name varchar(100))
insert into penguins (name) values ('rico')
insert into penguins (name) values ('kowalski')
insert into penguins (name) values ('skipper')

select * from penguins where 3 = id
-->3    skipper

select * from penguins where (if (true, 2, 3)) = id
-->2    kowalski

How to use an IF statement in the MySQL "having clause search conditions":

select * from penguins 
where 1=1
having (if (true, 2, 3)) = id
-->1    rico

Use an IF statement with a column used in the select list to make a decision:

select (if (id = 2, -1, 1)) item
from penguins
where 1=1
--> 1
--> -1
--> 1

If statements embedded in SQL queries is a bad "code smell". Bad code has high "WTF's per minute" during code review. This is one of those things. If I see this in production with your name on it, I'm going to automatically not like you.

JAVA_HOME directory in Linux

Did you set your JAVA_HOME

  • Korn and bash shells:export JAVA_HOME=jdk-install-dir
  • Bourne shell:JAVA_HOME=jdk-install-dir;export JAVA_HOME
  • C shell:setenv JAVA_HOME jdk-install-dir

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

I've spent on this problem much time and as for me (for Intellij IDEA) the solution is to specify right path to res directory:

  • right click on project
  • click Modules in the left panel
  • select Android below your project name
  • in Structure tab set right path.

And don't forget to check all the paths in this tab!

I hope it will be helpful for somebody!

CSS3 selector to find the 2nd div of the same class

First you must select the parent element and set :nth-of-type(n) for the parent and then select the element you want. something like this :

#topmenu li:nth-of-type(2) ul.childUl {

This will select the second submenu from topmenu. #topmenu li is the parent element.

HTML:

<ul id="topmenu">
    <li>
        <ul class="childUl">
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>
    <li>
        <ul class="childUl">
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>
    <li>
        <ul class="childUl">
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </li>

Alternative to file_get_contents?

Use cURL. This function is an alternative to file_get_contents.

function url_get_contents ($Url) {
    if (!function_exists('curl_init')){ 
        die('CURL is not installed!');
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $Url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

List of special characters for SQL LIKE clause

For SQL Server, from http://msdn.microsoft.com/en-us/library/ms179859.aspx :

  • % Any string of zero or more characters.

    WHERE title LIKE '%computer%' finds all book titles with the word 'computer' anywhere in the book title.

  • _ Any single character.

    WHERE au_fname LIKE '_ean' finds all four-letter first names that end with ean (Dean, Sean, and so on).

  • [ ] Any single character within the specified range ([a-f]) or set ([abcdef]).

    WHERE au_lname LIKE '[C-P]arsen' finds author last names ending with arsen and starting with any single character between C and P, for example Carsen, Larsen, Karsen, and so on. In range searches, the characters included in the range may vary depending on the sorting rules of the collation.

  • [^] Any single character not within the specified range ([^a-f]) or set ([^abcdef]).

    WHERE au_lname LIKE 'de[^l]%' all author last names starting with de and where the following letter is not l.

How to show code but hide output in RMarkdown?

As @ J_F answered in the comments, using {r echo = T, results = 'hide'}.

I wanted to expand on their answer - there are great resources you can access to determine all possible options for your chunk and output display - I keep a printed copy at my desk!

You can find them either on the RStudio Website under Cheatsheets (look for the R Markdown cheatsheet and R Markdown Reference Guide) or, in RStudio, navigate to the "Help" tab, choose "Cheatsheets", and look for the same documents there.

Finally to set default chunk options, you can run (in your first chunk) something like the following code if you want most chunks to have the same behavior:

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = T,
                      results = "hide")
```

Later, you can modify the behavior of individual chunks like this, which will replace the default value for just the results option.

```{r analysis, results="markup"}
# code here
```

css absolute position won't work with margin-left:auto margin-right: auto

If the element is position absolutely, then it isn't relative, or in reference to any object - including the page itself. So margin: auto; can't decide where the middle is.

Its waiting to be told explicitly, using left and top where to position itself.

You can still center it programatically, using javascript or somesuch.

Spring MVC - HttpMediaTypeNotAcceptableException

As Alex hinted in one of the answers, you could use the ContentNegotiationManagerFactoryBean to set the default content-type to "application/json", but I felt that that approach was not for me.

What I was trying to do was to post a form to a method like this

@RequestMapping(value = "/post/to/me", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public @ResponseBody MyJsonPOJO handlePostForm(@Valid @ModelAttribute("form") ValidateMeForm form, BindingResult bindingResult) throws ApiException {

What I instead chose to do was to change the "Accept" header of the request from the browser to "application/json", thereby making SpringMVC find my method.

Using the (not yet finalized) Javascript Fetch API:

var form = new FormData();
form.append("myData", "data");

let fetchConfig = {
    method: "POST",
    body: form,
    headers: {"Accept": "application/json"}
};

fetch("/post/to/me", fetchConfig)
    .then(... // Javascript Promise API here

Et voilà! Now SpringMVC finds the method, validates the form, and lets you return a JSON POJO.

angular.element vs document.getElementById or jQuery selector with spin (busy) control

It can work like that:

var myElement = angular.element( document.querySelector( '#some-id' ) );

You wrap the Document.querySelector() native Javascript call into the angular.element() call. So you always get the element in a jqLite or jQuery object, depending whether or not jQuery is available/loaded.

Official documentation for angular.element:

If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angulars built-in subset of jQuery, that called "jQuery lite" or jqLite.

All element references in Angular are always wrapped with jQuery or jqLite (such as the element argument in a directives compile or link function). They are never raw DOM references.

In case you do wonder why to use document.querySelector(), please read this answer.

Ajax Success and Error function failure

One also may use the following to catch the errors:

$.ajax({
    url: url, 
    success: function (data) {
        // Handle success here
        $('#editor-content-container').html(data);
        $('#editor-container').modal('show');
    },
    cache: false
}).fail(function (jqXHR, textStatus, error) {
    // Handle error here
    $('#editor-content-container').html(jqXHR.responseText);
    $('#editor-container').modal('show');
});

Google maps Marker Label with multiple characters

A much simpler solution to this problem that allows letters, numbers and words as the label is the following code. More specifically, the line of code starting with "icon:". Any string or variable could be substituted for 'k'.

for (i = 0; i < locations.length; i++) 
      { 
      k = i + 1;
      marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[i][1], locations[i][2]),     
      map: map,
      icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=' + k + '|FF0000|000000'
});

--- the locations array holds the lat and long and k is the row number for the address I was mapping. In other words if I had a 100 addresses to map my marker labels would be 1 to 100.

How to URL encode in Python 3?

For Python 3 you could try using quote instead of quote_plus:

import urllib.parse

print(urllib.parse.quote("http://www.sample.com/"))

Result:

http%3A%2F%2Fwww.sample.com%2F

Or:

from requests.utils import requote_uri
requote_uri("http://www.sample.com/?id=123 abc")

Result:

'https://www.sample.com/?id=123%20abc'

Scroll Automatically to the Bottom of the Page

A simple way if you want to scroll down specific element

Call this function whenever you want to scroll down.

_x000D_
_x000D_
function scrollDown() {_x000D_
 document.getElementById('scroll').scrollTop =  document.getElementById('scroll').scrollHeight_x000D_
}
_x000D_
ul{_x000D_
 height: 100px;_x000D_
 width: 200px;_x000D_
 overflow-y: scroll;_x000D_
 border: 1px solid #000;_x000D_
}
_x000D_
<ul id='scroll'>_x000D_
<li>Top Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Something Here</li>_x000D_
<li>Bottom Here</li>_x000D_
<li style="color: red">Bottom Here</li>_x000D_
</ul>_x000D_
_x000D_
<br />_x000D_
_x000D_
<button onclick='scrollDown()'>Scroll Down</button>
_x000D_
_x000D_
_x000D_

How to group time by hour or by 10 minutes

finally done with

GROUP BY
DATEPART(YEAR, DT.[Date]),
DATEPART(MONTH, DT.[Date]),
DATEPART(DAY, DT.[Date]),
DATEPART(HOUR, DT.[Date]),
(DATEPART(MINUTE, DT.[Date]) / 10)

How to remove pip package after deleting it manually

I'm sure there's a better way to achieve this and I would like to read about it, but a workaround I can think of is this:

  1. Install the package on a different machine.
  2. Copy the rm'ed directory to the original machine (ssh, ftp, whatever).
  3. pip uninstall the package (should work again then).

But, yes, I'd also love to hear about a decent solution for this situation.

Connecting PostgreSQL 9.2.1 with Hibernate

Yes by using spring-boot with hibernate configuration files we can persist the data to the database. keep hibernating .cfg.xml in your src/main/resources folder for reading the configurations related to database.

enter image description here

Codeigniter $this->db->get(), how do I return values for a specific row?

You simply use this in one row.

$query = $this->db->get_where('mytable',array('id'=>'3'));

HTML img scaling

I think the best solution is resize the images via script or locally and upload them again. Remember, you're forcing your viewers to download larger files than they need

Java System.out.print formatting

Since you are using Java, printf is available from version 1.5

You may use it like this

System.out.printf("%03d ", x);

For Example:

System.out.printf("%03d ", 5);
System.out.printf("%03d ", 55);
System.out.printf("%03d ", 555);

Will Give You

005 055 555

as output

See: System.out.printf and Format String Syntax

How to Decode Json object in laravel and apply foreach loop on that in laravel

your string is NOT a valid json to start with.

a valid json will be,

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

if you do a json_decode, it will yield,

stdClass Object
(
    [area] => Array
        (
            [0] => stdClass Object
                (
                    [area] => kothrud
                )

            [1] => stdClass Object
                (
                    [area] => katraj
                )

        )

)

Update: to use

$string = '

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

';
            $area = json_decode($string, true);

            foreach($area['area'] as $i => $v)
            {
                echo $v['area'].'<br/>';
            }

Output:

kothrud
katraj

Update #2:

for that true:

When TRUE, returned objects will be converted into associative arrays. for more information, click here

Get key and value of object in JavaScript?

Change your object.

var top_brands = [ 
  { key: 'Adidas', value: 100 }, 
  { key: 'Nike', value: 50 }
];

var $brand_options = $("#top-brands");

$.each(top_brands, function(brand) {
  $brand_options.append(
    $("<option />").val(brand.key).text(brand.key + " " + brand.value)
  );
});

As a rule of thumb:

  • An object has data and structure.
  • 'Adidas', 'Nike', 100 and 50 are data.
  • Object keys are structure. Using data as the object key is semantically wrong. Avoid it.

There are no semantics in {Nike: 50}. What's "Nike"? What's 50?

{key: 'Nike', value: 50} is a little better, since now you can iterate an array of these objects and values are at predictable places. This makes it easy to write code that handles them.

Better still would be {vendor: 'Nike', itemsSold: 50}, because now values are not only at predictable places, they also have meaningful names. Technically that's the same thing as above, but now a person would also understand what the values are supposed to mean.

Align text to the bottom of a div

You now can do this with Flexbox justify-content: flex-end now:

_x000D_
_x000D_
div {_x000D_
  display: flex;_x000D_
  justify-content: flex-end;_x000D_
  align-items: flex-end;_x000D_
  width: 150px;_x000D_
  height: 150px;_x000D_
  border: solid 1px red;_x000D_
}_x000D_
  
_x000D_
<div>_x000D_
  Something to align_x000D_
</div>
_x000D_
_x000D_
_x000D_

Consult your Caniuse to see if Flexbox is right for you.

How to avoid "RuntimeError: dictionary changed size during iteration" error?

I would try to avoid inserting empty lists in the first place, but, would generally use:

d = {k: v for k,v in d.iteritems() if v} # re-bind to non-empty

If prior to 2.7:

d = dict( (k, v) for k,v in d.iteritems() if v )

or just:

empty_key_vals = list(k for k in k,v in d.iteritems() if v)
for k in empty_key_vals:
    del[k]

How do I create a Linked List Data Structure in Java?

Its much better to use java.util.LinkedList, because it's probably much more optimized, than the one that you will write.

Should I learn C before learning C++?

I love this question - it's like asking "what should I learn first, snowboarding or skiing"? I think it depends if you want to snowboard or to ski. If you want to do both, you have to learn both.

In both sports, you slide down a hill on snow using devices that are sufficiently similar to provoke this question. However, they are also sufficiently different so that learning one does not help you much with the other. Same thing with C and C++. While they appear to be languages sufficiently similar in syntax, the mind set that you need for writing OO code vs procedural code is sufficiently different so that you pretty much have to start from the beginning, whatever language you learn second.

Port 443 in use by "Unable to open process" with PID 4

The solution by "Mark Seagoe" worked for me too. I got a message that "Port 443 in use by Unable to open process with PID 14508". So i opened task manager and killed this process 14508. This was used by my previous xampp version and it was orphaned.

so no need to change any ports or anything, this is a simple two step process and it worked .

Checking if a variable exists in javascript

I found this shorter and much better:

    if(varName !== (undefined || null)) { //do something }

How to run Java program in command prompt

A very general command prompt how to for java is

javac mainjava.java
java mainjava

You'll very often see people doing

javac *.java
java mainjava

As for the subclass problem that's probably occurring because a path is missing from your class path, the -c flag I believe is used to set that.

How do I call REST API from an android app?

  1. If you want to integrate Retrofit (all steps defined here):

Goto my blog : retrofit with kotlin

  1. Please use android-async-http library.

the link below explains everything step by step.

http://loopj.com/android-async-http/

Here are sample apps:

  1. http://www.techrepublic.com/blog/software-engineer/calling-restful-services-from-your-android-app/

  2. http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes

Create a class :

public class HttpUtils {
  private static final String BASE_URL = "http://api.twitter.com/1/";
 
  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
      
  public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(url, params, responseHandler);
  }

  public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(url, params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Call Method :

    RequestParams rp = new RequestParams();
    rp.add("username", "aaa"); rp.add("password", "aaa@123");
                    
    HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            // If the response is JSONObject instead of expected JSONArray
            Log.d("asd", "---------------- this is response : " + response);
            try {
                JSONObject serverResp = new JSONObject(response.toString());                                                
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                   
        }
            
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
            // Pull out the first event on the public timeline
                    
        }
    });

Please grant internet permission in your manifest file.

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

you can add compile 'com.loopj.android:android-async-http:1.4.9' for Header[] and compile 'org.json:json:20160212' for JSONObject in build.gradle file if required.

How can you float: right in React Native?

why does the Text take up the full space of the View, instead of just the space for "Hello"?

Because the View is a flex container and by default has flexDirection: 'column' and alignItems: 'stretch', which means that its children should be stretched out to fill its width.

(Note, per the docs, that all components in React Native are display: 'flex' by default and that display: 'inline' does not exist at all. In this way, the default behaviour of a Text within a View in React Native differs from the default behaviour of span within a div on the web; in the latter case, the span would not fill the width of the div because a span is an inline element by default. There is no such concept in React Native.)

How can the Text be floated / aligned to the right?

The float property doesn't exist in React Native, but there are loads of options available to you (with slightly different behaviours) that will let you right-align your text. Here are the ones I can think of:

1. Use textAlign: 'right' on the Text element

<View>
  <Text style={{textAlign: 'right'}}>Hello, World!</Text>
</View>

(This approach doesn't change the fact that the Text fills the entire width of the View; it just right-aligns the text within the Text.)

2. Use alignSelf: 'flex-end' on the Text

<View>
  <Text style={{alignSelf: 'flex-end'}}>Hello, World!</Text>
</View>

This shrinks the Text element to the size required to hold its content and puts it at the end of the cross direction (the horizontal direction, by default) of the View.

3. Use alignItems: 'flex-end' on the View

<View style={{alignItems: 'flex-end'}}>
  <Text>Hello, World!</Text>
</View>

This is equivalent to setting alignSelf: 'flex-end' on all the View's children.

4. Use flexDirection: 'row' and justifyContent: 'flex-end' on the View

<View style={{flexDirection: 'row', justifyContent: 'flex-end'}}>
  <Text>Hello, World!</Text>
</View>

flexDirection: 'row' sets the main direction of layout to be horizontal instead of vertical; justifyContent is just like alignItems, but controls alignment in the main direction instead of the cross direction.

5. Use flexDirection: 'row' on the View and marginLeft: 'auto' on the Text

<View style={{flexDirection: 'row'}}>
  <Text style={{marginLeft: 'auto'}}>Hello, World!</Text>
</View>

This approach is demonstrated, in the context of the web and real CSS, at https://stackoverflow.com/a/34063808/1709587.

6. Use position: 'absolute' and right: 0 on the Text:

<View>
  <Text style={{position: 'absolute', right: 0}}>Hello, World!</Text>
</View>

Like in real CSS, this takes the Text "out of flow", meaning that its siblings will be able to overlap it and its vertical position will be at the top of the View by default (although you can explicitly set a distance from the top of the View using the top style property).


Naturally, which of these various approaches you want to use - and whether the choice between them even matters at all - will depend upon your precise circumstances.

Fundamental difference between Hashing and Encryption algorithms

  1. Use hashes when you only need to go one way. For example, for passwords in a system, you use hashing because you will only ever verify that the value a user entered, after hashing, matches the value in your repository. With encryption, you can go two ways.

  2. hashing algorithms and encryption algorithms are just mathematical algorithms. So in that respect they are not different -- its all just mathematical formulas. Semantics wise, though, there is the very big distinction between hashing (one-way) and encryption(two-way). Why are hashes irreversible? Because they are designed to be that way, because sometimes you want a one-way operation.

How to include external Python code to use in other files?

You will need to import the other file as a module like this:

import Math

If you don't want to prefix your Calculate function with the module name then do this:

from Math import Calculate

If you want to import all members of a module then do this:

from Math import *

Edit: Here is a good chapter from Dive Into Python that goes a bit more in depth on this topic.

How can I resolve the error: "The command [...] exited with code 1"?

Check your paths: If you are using a separate build server for TFS (most likely), make sure that all your paths in the .csproj file match the TFS server paths. I got the above error when checking in the *.csproj file when it had references to my development machine paths and not the TFS server paths.

Remove multi-line commands: Also, try and remove multi-line commands into single-line commands in xml as a precaution. I had the following xml in the *.proj that caused issues in TFS:

<Exec Condition="bl.." 
Command=" Blah...
..." </Exec>

Changing the above xml to this worked:

  <Exec Condition="bl.." Command=" Blah..." </Exec>

How to limit the maximum files chosen when using multiple file input

Another possible solution with JS

function onSelect(e) {
    if (e.files.length > 5) {
        alert("Only 5 files accepted.");
        e.preventDefault();
    }
}

line breaks in a textarea

You can use following code:

$course_description = nl2br($_POST["course_description"]);
$course_description = trim($course_description);

Auto increment in MongoDB to store sequence of Unique User ID

First Record should be add

"_id" = 1    in your db

$database = "demo";
$collections ="democollaction";
echo getnextid($database,$collections);

function getnextid($database,$collections){

     $m = new MongoClient();
    $db = $m->selectDB($database);
    $cursor = $collection->find()->sort(array("_id" => -1))->limit(1);
    $array = iterator_to_array($cursor);

    foreach($array as $value){



        return $value["_id"] + 1;

    }
 }

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

Where it is documented:

From the API documentation under the has_many association in "Module ActiveRecord::Associations::ClassMethods"

collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!

The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,

Class Dog
   has_many :tags
   belongs_to :person
end

Class Person
  has_many :dogs
end

d = Dog.new
d.build_person(:attributes => "go", :here => "like normal")

or even

t = Tag.new
t.build_dog(:name => "Rover", :breed => "Maltese")

You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)

How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)

Select All as default value for Multivalue parameter

Adding to the answer from E_8.
This does not work if you have empty strings.

You can get around this by modifying your select statement in SQL or modifying your query in the SSRS dataset.

 Select distinct phonenumber
from YourTable
where phonenumber <> ''
Order by Phonenumber

how to prevent adding duplicate keys to a javascript array

var a = [1,2,3], b = [4,1,5,2];

b.forEach(function(value){
  if (a.indexOf(value)==-1) a.push(value);
});

console.log(a);
// [1, 2, 3, 4, 5]

For more details read up on Array.indexOf.

If you want to rely on jQuery, instead use jQuery.inArray:

$.each(b,function(value){
  if ($.inArray(value,a)==-1) a.push(value);
});

If all your values are simply and uniquely representable as strings, however, you should use an Object instead of an Array, for a potentially massive speed increase (as described in the answer by @JonathanSampson).

What is the cleanest way to disable CSS transition effects temporarily?

You can disable animation, transition, trasforms for all of element in page with this css code

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '* {' +
'/*CSS transitions*/' +
' -o-transition-property: none !important;' +
' -moz-transition-property: none !important;' +
' -ms-transition-property: none !important;' +
' -webkit-transition-property: none !important;' +
'  transition-property: none !important;' +
'/*CSS transforms*/' +
'  -o-transform: none !important;' +
' -moz-transform: none !important;' +
'   -ms-transform: none !important;' +
'  -webkit-transform: none !important;' +
'   transform: none !important;' +
'  /*CSS animations*/' +
'   -webkit-animation: none !important;' +
'   -moz-animation: none !important;' +
'   -o-animation: none !important;' +
'   -ms-animation: none !important;' +
'   animation: none !important;}';
   document.getElementsByTagName('head')[0].appendChild(style);

What does `set -x` do?

-u: disabled by default. When activated, an error message is displayed when using an unconfigured variable.

-v: inactive by default. After activation, the original content of the information will be displayed (without variable resolution) before the information is output.

-x: inactive by default. If activated, the command content will be displayed before the command is run (after variable resolution, there is a ++ symbol).

Compare the following differences:

/ # set -v && echo $HOME
/root
/ # set +v && echo $HOME
set +v && echo $HOME
/root

/ # set -x && echo $HOME
+ echo /root
/root
/ # set +x && echo $HOME
+ set +x
/root

/ # set -u && echo $NOSET
/bin/sh: NOSET: parameter not set
/ # set +u && echo $NOSET

How to detect orientation change?

I need to detect rotation while using the camera with AVFoundation, and found that the didRotate (now deprecated) & willTransition methods were unreliable for my needs. Using the notification posted by David did work, but is not current for Swift 3.x & above.

The following makes use of a closure, which appears to be Apple's preference going forward.

var didRotate: (Notification) -> Void = { notification in
        switch UIDevice.current.orientation {
        case .landscapeLeft, .landscapeRight:
            print("landscape")
        case .portrait, .portraitUpsideDown:
            print("Portrait")
        default:
            print("other (such as face up & down)")
        }
    }

To set up the notification:

NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification,
                                       object: nil,
                                       queue: .main,
                                       using: didRotate)

To tear down the notification:

NotificationCenter.default.removeObserver(self,
                                          name: UIDevice.orientationDidChangeNotification,
                                          object: nil)

Regarding the deprecation statement, my initial comment was misleading, so I wanted to update that. As noted, the usage of @objc inference has been deprecated, which in turn was needed to use a #selector. By using a closure instead, this can be avoided and you now have a solution that should avoid a crash due to calling an invalid selector.

How to hide a navigation bar from first ViewController in Swift?

In Swift 3, you can use isNavigationBarHidden Property also to show or hide navigation bar

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    // Hide the navigation bar for current view controller
    self.navigationController?.isNavigationBarHidden = true;
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    // Show the navigation bar on other view controllers
   self.navigationController?.isNavigationBarHidden = false;
}

What is @RenderSection in asp.net MVC

If you have a _Layout.cshtml view like this

<html>
    <body>
        @RenderBody()
        @RenderSection("scripts", required: false)
    </body>
</html>

then you can have an index.cshtml content view like this

@section scripts {
     <script type="text/javascript">alert('hello');</script>
}

the required indicates whether or not the view using the layout page must have a scripts section

Array length in angularjs returns undefined

var leg= $scope.name.length;
$log.info(leg);

jQuery CSS Opacity

jQuery('#main').css('opacity') = '0.6';

should be

jQuery('#main').css('opacity', '0.6');

Update:

http://jsfiddle.net/GegMk/ if you type in the text box. Click away, the opacity changes.

Can I call a constructor from another constructor (do constructor chaining) in C++?

Another option that has not been shown yet is to split your class into two, wrapping a lightweight interface class around your original class in order to achieve the effect you are looking for:

class Test_Base {
    public Test_Base() {
        DoSomething();
    }
};

class Test : public Test_Base {
    public Test() : Test_Base() {
    }

    public Test(int count) : Test_Base() {
        DoSomethingWithCount(count);
    }
};

This could get messy if you have many constructors that must call their "next level up" counterpart, but for a handful of constructors, it should be workable.

How can I display a tooltip on an HTML "option" tag?

I don't believe that you can achieve this functionality with standard <select> element.

What i would suggest is to use such way.

http://filamentgroup.com/lab/jquery_ipod_style_and_flyout_menus/

The basic version of it won't take too much space and you can easily bind mouseover events to sub items to show a nice tooltip.

Hope this helps, Sinan.

How to write specific CSS for mozilla, chrome and IE

For that

  • You can scan user Agent and find out which browser, its version. Including the OS for OS specific styles
  • You can use various CSS Hacks for specific browser
  • Or Scripts or Plugins to indentify the browser and apply various classes to the elements

Using PHP

See

Then then create the dynamic CSS file as per the detected browser

Here is a CSS Hacks list

/***** Selector Hacks ******/

/* IE6 and below */
* html #uno  { color: red }

/* IE7 */
*:first-child+html #dos { color: red } 

/* IE7, FF, Saf, Opera  */
html>body #tres { color: red }

/* IE8, FF, Saf, Opera (Everything but IE 6,7) */
html>/**/body #cuatro { color: red }

/* Opera 9.27 and below, safari 2 */
html:first-child #cinco { color: red }

/* Safari 2-3 */
html[xmlns*=""] body:last-child #seis { color: red }

/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:nth-of-type(1) #siete { color: red }

/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:first-of-type #ocho {  color: red }

/* saf3+, chrome1+ */
@media screen and (-webkit-min-device-pixel-ratio:0) {
 #diez  { color: red  }
}

/* iPhone / mobile webkit */
@media screen and (max-device-width: 480px) {
 #veintiseis { color: red  }
}


/* Safari 2 - 3.1 */
html[xmlns*=""]:root #trece  { color: red  }

/* Safari 2 - 3.1, Opera 9.25 */
*|html[xmlns*=""] #catorce { color: red  }

/* Everything but IE6-8 */
:root *> #quince { color: red  }

/* IE7 */
*+html #dieciocho {  color: red }

/* Firefox only. 1+ */
#veinticuatro,  x:-moz-any-link  { color: red }

/* Firefox 3.0+ */
#veinticinco,  x:-moz-any-link, x:default  { color: red  }



/***** Attribute Hacks ******/

/* IE6 */
#once { _color: blue }

/* IE6, IE7 */
#doce { *color: blue; /* or #color: blue */ }

/* Everything but IE6 */
#diecisiete { color/**/: blue }

/* IE6, IE7, IE8 */
#diecinueve { color: blue\9; }

/* IE7, IE8 */
#veinte { color/*\**/: blue\9; }

/* IE6, IE7 -- acts as an !important */
#veintesiete { color: blue !ie; } /* string after ! can be anything */

Source: http://paulirish.com/2009/browser-specific-css-hacks/

If you want to use Plugin then here is one

http://rafael.adm.br/css_browser_selector/

How to check if text fields are empty on form submit using jQuery?

I really hate forms which don't tell me what input(s) is/are missing. So I improve the Dominic's answer - thanks for this.

In the css file set the "borderR" class to border has red color.

$('#<form_id>').submit(function () {
    var allIsOk = true;

    // Check if empty of not
    $(this).find( 'input[type!="hidden"]' ).each(function () {
        if ( ! $(this).val() ) { 
            $(this).addClass('borderR').focus();
            allIsOk = false;
        }
    });

    return allIsOk
});

Clearing NSUserDefaults

I love extensions when they make the code cleaner:

extension NSUserDefaults {
    func clear() {
        guard let domainName = NSBundle.mainBundle().bundleIdentifier else {
            return
        }

        self.removePersistentDomainForName(domainName)
    }
}

Swift 5

extension UserDefaults {
    func clear() {
        guard let domainName = Bundle.main.bundleIdentifier else {
            return
        }
        removePersistentDomain(forName: domainName)
        synchronize()
    }
}

How to center a label text in WPF?

The Control class has HorizontalContentAlignment and VerticalContentAlignment properties. These properties determine how a control’s content fills the space within the control.
Set HorizontalContentAlignment and VerticalContentAlignment to Center.

<button> vs. <input type="button" />. Which to use?

Inside a <button> element you can put content, like text or images.

<button type="button">Click Me!</button> 

This is the difference between this element and buttons created with the <input> element.

Set timeout for ajax (jQuery)

Here's some examples that demonstrate setting and detecting timeouts in jQuery's old and new paradigmes.

Live Demo

Promise with jQuery 1.8+

Promise.resolve(
  $.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
  })
).then(function(){
  //do something
}).catch(function(e) {
  if(e.statusText == 'timeout')
  {     
    alert('Native Promise: Failed from timeout'); 
    //do something. Try again perhaps?
  }
});

jQuery 1.8+

$.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
}).done(function(){
    //do something
}).fail(function(jqXHR, textStatus){
    if(textStatus === 'timeout')
    {     
        alert('Failed from timeout'); 
        //do something. Try again perhaps?
    }
});?

jQuery <= 1.7.2

$.ajax({
    url: '/getData',
    error: function(jqXHR, textStatus){
        if(textStatus === 'timeout')
        {     
             alert('Failed from timeout');         
            //do something. Try again perhaps?
        }
    },
    success: function(){
        //do something
    },
    timeout:3000 //3 second timeout
});

Notice that the textStatus param (or jqXHR.statusText) will let you know what the error was. This may be useful if you want to know that the failure was caused by a timeout.

error(jqXHR, textStatus, errorThrown)

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests.

src: http://api.jquery.com/jQuery.ajax/

How do I get current URL in Selenium Webdriver 2 Python?

Use current_url element for Python 2:

print browser.current_url

For Python 3 and later versions of selenium:

print(driver.current_url)

How do I get the directory that a program is running from?

As Minok mentioned, there is no such functionality specified ini C standard or C++ standard. This is considered to be purely OS-specific feature and it is specified in POSIX standard, for example.

Thorsten79 has given good suggestion, it is Boost.Filesystem library. However, it may be inconvenient in case you don't want to have any link-time dependencies in binary form for your program.

A good alternative I would recommend is collection of 100% headers-only STLSoft C++ Libraries Matthew Wilson (author of must-read books about C++). There is portable facade PlatformSTL gives access to system-specific API: WinSTL for Windows and UnixSTL on Unix, so it is portable solution. All the system-specific elements are specified with use of traits and policies, so it is extensible framework. There is filesystem library provided, of course.

How to validate an Email in PHP?

I always use this:

function validEmail($email){
    // First, we check that there's one @ symbol, and that the lengths are right
    if (!preg_match("/^[^@]{1,64}@[^@]{1,255}$/", $email)) {
        // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
        return false;
    }
    // Split it into sections to make life easier
    $email_array = explode("@", $email);
    $local_array = explode(".", $email_array[0]);
    for ($i = 0; $i < sizeof($local_array); $i++) {
        if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
            return false;
        }
    }
    if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
        $domain_array = explode(".", $email_array[1]);
        if (sizeof($domain_array) < 2) {
            return false; // Not enough parts to domain
        }
        for ($i = 0; $i < sizeof($domain_array); $i++) {
            if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
                return false;
            }
        }
    }

    return true;
}

How to make CSS width to fill parent?

box-sizing: border-box;
width: 100%;
padding: 5px;

box-sizing: border box; makes it so that padding, margin and border are included in the width calculations.

MDN

Uncaught ReferenceError: $ is not defined

put latest jquery cdn on top of your main html page

Like If your main html page is index.html

place jquery cdn on top of this page like this

_x000D_
_x000D_
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("h2").hide();
  });
});
</script>
</head>
<body>

<h2>This will hide me</h2>


<button>Click me</button>

</body>
</html>
_x000D_
_x000D_
_x000D_

Getting HTTP headers with Node.js

I'm not sure how you might do this with Node, but the general idea would be to send an HTTP HEAD request to the URL you're interested in.

HEAD

Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.


Something like this, based it on this question:

var cli = require('cli');
var http = require('http');
var url = require('url');

cli.parse();

cli.main(function(args, opts) {
        this.debug(args[0]);

        var siteUrl = url.parse(args[0]);
        var site = http.createClient(80, siteUrl.host);
        console.log(siteUrl);

        var request = site.request('HEAD', siteUrl.pathname, {'host' : siteUrl.host})
        request.end();

        request.on('response', function(response) {
                response.setEncoding('utf8');
                console.log('STATUS: ' + response.statusCode);
                response.on('data', function(chunk) {
                        console.log("DATA: " + chunk);
                });
        });
});

Removing a model in rails (reverse of "rails g model Title...")

For future questioners: If you can't drop the tables from the console, try to create a migration that drops the tables for you. You should create a migration and then in the file note tables you want dropped like this:

class DropTables < ActiveRecord::Migration
  def up
    drop_table :table_you_dont_want
  end

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

You don't need to prevent this error message!
Error messages are your friends!
Without error message you'd never know what is happened.
It's all right! Any working code supposed to throw out error messages.

Though error messages needs proper handling. Usually you don't have to to take any special actions to avoid such an error messages. Just leave your code intact. But if you don't want this error message to be shown to the user, just turn it off. Not error message itself but daislaying it to the user.

ini_set('display_errors',0);
ini_set('log_errors',1);

or even better at .htaccess/php.ini level
And user will never see any error messages. While you will be able still see it in the error log.
Please note that error_reporting should be at max in both cases.

To prevent this message you can check mysql_query result and run fetch_assoc only on success.
But usually nobody uses it as it may require too many nested if's.
But there can be solution too - exceptions!

But it is still not necessary. You can leave your code as is, because it is supposed to work without errors when done.

Using return is another method to avoid nested error messages. Here is a snippet from my database handling function:

  $res = mysql_query($query);
  if (!$res) {
    trigger_error("dbget: ".mysql_error()." in ".$query);
    return false;
  }
  if (!mysql_num_rows($res)) return NULL;

  //fetching goes here
  //if there was no errors only

How to wrap async function calls into a sync function in Node.js or Javascript?

Javascript is a single threaded language, you don't want to block your whole server! Async code eliminates, race conditions by making dependencies explicit.

Learn to love asynchronous code!

Have a look at promises for asynchronous code without creating a pyramid of callback hell. I recommend the promiseQ library for node.js

httpGet(url.parse("http://example.org/")).then(function (res) {
    console.log(res.statusCode);  // maybe 302
    return httpGet(url.parse(res.headers["location"]));
}).then(function (res) {
    console.log(res.statusCode);  // maybe 200
});

http://howtonode.org/promises

EDIT: this is by far my most controversial answer, node now has yield keyword, which allows you to treat async code as if it were sychronous. http://blog.alexmaccaw.com/how-yield-will-transform-node

Recommended date format for REST GET API

Check this article for the 5 laws of API dates and times HERE:

  • Law #1: Use ISO-8601 for your dates
  • Law #2: Accept any timezone
  • Law #3: Store it in UTC
  • Law #4: Return it in UTC
  • Law #5: Don’t use time if you don’t need it

More info in the docs.

How to encrypt String in Java

I'd recommend to use some standard symmetric cypher that is widely available like DES, 3DES or AES. While that is not the most secure algorithm, there are loads of implementations and you'd just need to give the key to anyone that is supposed to decrypt the information in the barcode. javax.crypto.Cipher is what you want to work with here.

Let's assume the bytes to encrypt are in

byte[] input;

Next, you'll need the key and initialization vector bytes

byte[] keyBytes;
byte[] ivBytes;

Now you can initialize the Cipher for the algorithm that you select:

// wrap key data in Key/IV specs to pass to cipher
SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
// create the cipher with the algorithm you choose
// see javadoc for Cipher class for more info, e.g.
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

Encryption would go like this:

cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] encrypted= new byte[cipher.getOutputSize(input.length)];
int enc_len = cipher.update(input, 0, input.length, encrypted, 0);
enc_len += cipher.doFinal(encrypted, enc_len);

And decryption like this:

cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] decrypted = new byte[cipher.getOutputSize(enc_len)];
int dec_len = cipher.update(encrypted, 0, enc_len, decrypted, 0);
dec_len += cipher.doFinal(decrypted, dec_len);

MIPS: Integer Multiplication and Division

To multiply, use mult for signed multiplication and multu for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0 that means that you assume the result will fit in 32 bits.

The 32 most significant bits will be held in the HI special register (accessible by mfhi instruction) and the 32 least significant bits will be held in the LO special register (accessible by the mflo instruction):

E.g.:

li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0

To divide, use div for signed division and divu for unsigned division. In this case, the HI special register will hold the remainder and the LO special register will hold the quotient of the division.

E.g.:

div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0

Day Name from Date in JS

You could use the Date.getDay() method, which returns 0 for sunday, up to 6 for saturday. So, you could simply create an array with the name for the day names:

var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var d = new Date(dateString);
var dayName = days[d.getDay()];

Here dateString is the string you received from the third party API.

Alternatively, if you want the first 3 letters of the day name, you could use the Date object's built-in toString method:

var d = new Date(dateString);
var dayName = d.toString().split(' ')[0];

That will take the first word in the d.toString() output, which will be the 3-letter day name.

How can I make an svg scale with its parent container?

Adjusting the currentScale attribute works in IE ( I tested with IE 11), but not in Chrome.

Binary search (bisection) in Python

If you just want to see if it's present, try turning the list into a dict:

# Generate a list
l = [n*n for n in range(1000)]

# Convert to dict - doesn't matter what you map values to
d = dict((x, 1) for x in l)

count = 0
for n in range(1000000):
    # Compare with "if n in l"
    if n in d:
        count += 1

On my machine, "if n in l" took 37 seconds, while "if n in d" took 0.4 seconds.

How to get an array of specific "key" in multidimensional array without looping

Since PHP 5.5, you can use array_column:

$ids = array_column($users, 'id');

This is the preferred option on any modern project. However, if you must support PHP<5.5, the following alternatives exist:

Since PHP 5.3, you can use array_map with an anonymous function, like this:

$ids = array_map(function ($ar) {return $ar['id'];}, $users);

Before (Technically PHP 4.0.6+), you must create an anonymous function with create_function instead:

$ids = array_map(create_function('$ar', 'return $ar["id"];'), $users);

Uploading files to file server using webclient class

Just use

File.Copy(filepath, "\\\\192.168.1.28\\Files");

A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.

The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.

You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!

If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"

If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.

New to MongoDB Can not run command mongo

Check that path to database data files exists ;) :

Sun Nov 06 18:48:37 [initandlisten] exception in initAndListen: 10296 dbpath (/data/db) does not exist, terminating

How to include (source) R script in other scripts

I solved my problem using entire address where my code is: Before:

if(!exists("foo", mode="function")) source("utils.r")

After:

if(!exists("foo", mode="function")) source("C:/tests/utils.r")

Using jQuery to test if an input has focus

Here’s a more robust answer than the currently accepted one:

jQuery.expr[':'].focus = function(elem) {
  return elem === document.activeElement && (elem.type || elem.href);
};

Note that the (elem.type || elem.href) test was added to filter out false positives like body. This way, we make sure to filter out all elements except form controls and hyperlinks.

(Taken from this gist by Ben Alman.)

Setting an image button in CSS - image:active

Check this link . You were missing . before myButton. It was a small error. :)

.myButton{
    background:url(./images/but.png) no-repeat;
    cursor:pointer;
    border:none;
    width:100px;
    height:100px;
}

.myButton:active  /* use Dot here */
{   
    background:url(./images/but2.png) no-repeat;
}

IOException: The process cannot access the file 'file path' because it is being used by another process

I had the following scenario that was causing the same error:

  • Upload files to the server
  • Then get rid of the old files after they have been uploaded

Most files were small in size, however, a few were large, and so attempting to delete those resulted in the cannot access file error.

It was not easy to find, however, the solution was as simple as Waiting "for the task to complete execution":

using (var wc = new WebClient())
{
   var tskResult = wc.UploadFileTaskAsync(_address, _fileName);
   tskResult.Wait(); 
}

SyntaxError of Non-ASCII character

You should define source code encoding, add this to the top of your script:

# -*- coding: utf-8 -*-

The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:

import sys
print sys.getdefaultencoding()

Also see:

Can I nest a <button> element inside an <a> using HTML5?

It would be really weird if that was valid, and I would expect it to be invalid. What should it mean to have one clickable element inside of another clickable element? Which is it -- a button, or a link?

jQuery/JavaScript: accessing contents of an iframe

Have you tried the classic, waiting for the load to complete using jQuery's builtin ready function?

$(document).ready(function() {
    $('some selector', frames['nameOfMyIframe'].document).doStuff()
} );

K

How to throw a C++ exception

Wanted to ADD to the other answers described here an additional note, in the case of custom exceptions.

In the case where you create your own custom exception, that derives from std::exception, when you catch "all possible" exceptions types, you should always start the catch clauses with the "most derived" exception type that may be caught. See the example (of what NOT to do):

#include <iostream>
#include <string>

using namespace std;

class MyException : public exception
{
public:
    MyException(const string& msg) : m_msg(msg)
    {
        cout << "MyException::MyException - set m_msg to:" << m_msg << endl;
    }

   ~MyException()
   {
        cout << "MyException::~MyException" << endl;
   }

   virtual const char* what() const throw () 
   {
        cout << "MyException - what" << endl;
        return m_msg.c_str();
   }

   const string m_msg;
};

void throwDerivedException()
{
    cout << "throwDerivedException - thrown a derived exception" << endl;
    string execptionMessage("MyException thrown");
    throw (MyException(execptionMessage));
}

void illustrateDerivedExceptionCatch()
{
    cout << "illustrateDerivedExceptionsCatch - start" << endl;
    try 
    {
        throwDerivedException();
    }
    catch (const exception& e)
    {
        cout << "illustrateDerivedExceptionsCatch - caught an std::exception, e.what:" << e.what() << endl;
        // some additional code due to the fact that std::exception was thrown...
    }
    catch(const MyException& e)
    {
        cout << "illustrateDerivedExceptionsCatch - caught an MyException, e.what::" << e.what() << endl;
        // some additional code due to the fact that MyException was thrown...
    }

    cout << "illustrateDerivedExceptionsCatch - end" << endl;
}

int main(int argc, char** argv)
{
    cout << "main - start" << endl;
    illustrateDerivedExceptionCatch();
    cout << "main - end" << endl;
    return 0;
}

NOTE:

0) The proper order should be vice-versa, i.e.- first you catch (const MyException& e) which is followed by catch (const std::exception& e).

1) As you can see, when you run the program as is, the first catch clause will be executed (which is probably what you did NOT wanted in the first place).

2) Even though the type caught in the first catch clause is of type std::exception, the "proper" version of what() will be called - cause it is caught by reference (change at least the caught argument std::exception type to be by value - and you will experience the "object slicing" phenomena in action).

3) In case that the "some code due to the fact that XXX exception was thrown..." does important stuff WITH RESPECT to the exception type, there is misbehavior of your code here.

4) This is also relevant if the caught objects were "normal" object like: class Base{}; and class Derived : public Base {}...

5) g++ 7.3.0 on Ubuntu 18.04.1 produces a warning that indicates the mentioned issue:

In function ‘void illustrateDerivedExceptionCatch()’: item12Linux.cpp:48:2: warning: exception of type ‘MyException’ will be caught catch(const MyException& e) ^~~~~

item12Linux.cpp:43:2: warning: by earlier handler for ‘std::exception’ catch (const exception& e) ^~~~~

Again, I will say, that this answer is only to ADD to the other answers described here (I thought this point is worth mention, yet could not depict it within a comment).

Why can a function modify some arguments as perceived by the caller, but not others?

I will rename variables to reduce confusion. n -> nf or nmain. x -> xf or xmain:

def f(nf, xf):
    nf = 2
    xf.append(4)
    print 'In f():', nf, xf

def main():
    nmain = 1
    xmain = [0,1,2,3]
    print 'Before:', nmain, xmain
    f(nmain, xmain)
    print 'After: ', nmain, xmain

main()

When you call the function f, the Python runtime makes a copy of xmain and assigns it to xf, and similarly assigns a copy of nmain to nf.

In the case of n, the value that is copied is 1.

In the case of x the value that is copied is not the literal list [0, 1, 2, 3]. It is a reference to that list. xf and xmain are pointing at the same list, so when you modify xf you are also modifying xmain.

If, however, you were to write something like:

    xf = ["foo", "bar"]
    xf.append(4)

you would find that xmain has not changed. This is because, in the line xf = ["foo", "bar"] you have change xf to point to a new list. Any changes you make to this new list will have no effects on the list that xmain still points to.

Hope that helps. :-)

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

Upgrading pip in windows with -

python -m pip install --upgrade pip

and then running pip install with --user option -

pip install --user package_name

solved my problem.

MySQL skip first 10 results

Use LIMIT with two parameters. For example, to return results 11-60 (where result 1 is the first row), use:

SELECT * FROM foo LIMIT 10, 50

For a solution to return all results, see Thomas' answer.

Windows 10 SSH keys

If you have Windows 10 with the OpenSSH client you may be able to generate the key, but you will have trouble copying it to the target Linux box as the ssh-copy-id command is not part of the client toolset.

Having has this problem I wrote a small PowerShell function to address this, that you add to your profile.

function ssh-copy-id([string]$userAtMachine, [string]$port = 22) {   
    # Get the generated public key
    $key = "$ENV:USERPROFILE" + "/.ssh/id_rsa.pub"
    # Verify that it exists
    if (!(Test-Path "$key")) {
        # Alert user
        Write-Error "ERROR: '$key' does not exist!"            
    }
    else {  
        # Copy the public key across
        & cat "$key" | ssh $userAtMachine -p $port "umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys || exit 1"      
    }
}

You can get the gist here

I have a brief write up about it here

How to resolve symbolic links in a shell script

readlink -e [filepath]

seems to be exactly what you're asking for - it accepts an arbirary path, resolves all symlinks, and returns the "real" path - and it's "standard *nix" that likely all systems already have

Java stack overflow error - how to increase the stack size in Eclipse?

It may be curable by increasing the stack size - but a better solution would be to work out how to avoid recursing so much. A recursive solution can always be converted to an iterative solution - which will make your code scale to larger inputs much more cleanly. Otherwise you'll really be guessing at how much stack to provide, which may not even be obvious from the input.

Are you absolutely sure it's failing due to the size of the input rather than a bug in the code, by the way? Just how deep is this recursion?

EDIT: Okay, having seen the update, I would personally try to rewrite it to avoid using recursion. Generally having a Stack<T> of "things still do to" is a good starting point to remove recursion.

Sorting Python list based on the length of the string

When you pass a lambda to sort, you need to return an integer, not a boolean. So your code should instead read as follows:

xs.sort(lambda x,y: cmp(len(x), len(y)))

Note that cmp is a builtin function such that cmp(x, y) returns -1 if x is less than y, 0 if x is equal to y, and 1 if x is greater than y.

Of course, you can instead use the key parameter:

xs.sort(key=lambda s: len(s))

This tells the sort method to order based on whatever the key function returns.

EDIT: Thanks to balpha and Ruslan below for pointing out that you can just pass len directly as the key parameter to the function, thus eliminating the need for a lambda:

xs.sort(key=len)

And as Ruslan points out below, you can also use the built-in sorted function rather than the list.sort method, which creates a new list rather than sorting the existing one in-place:

print(sorted(xs, key=len))

RandomForestClassfier.fit(): ValueError: could not convert string to float

As your input is in string you are getting value error message use countvectorizer it will convert data set in to sparse matrix and train your ml algorithm you will get the result

Convert data.frame column to a vector?

a1 = c(1, 2, 3, 4, 5)
a2 = c(6, 7, 8, 9, 10)
a3 = c(11, 12, 13, 14, 15)
aframe = data.frame(a1, a2, a3)
avector <- as.vector(aframe['a2'])

avector<-unlist(avector)
#this will return a vector of type "integer"

Python JSON serialize a Decimal object

I would like to let everyone know that I tried Michal Marczyk's answer on my web server that was running Python 2.6.5 and it worked fine. However, I upgraded to Python 2.7 and it stopped working. I tried to think of some sort of way to encode Decimal objects and this is what I came up with:

import decimal

class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            return str(o)
        return super(DecimalEncoder, self).default(o)

Note that this will convert the decimal to its string representation (e.g.; "1.2300") to a. not lose significant digits and b. prevent rounding errors.

This should hopefully help anyone who is having problems with Python 2.7. I tested it and it seems to work fine. If anyone notices any bugs in my solution or comes up with a better way, please let me know.

Excel formula to get cell color

As commented, just in case the link I posted there broke, try this:

Add a Name(any valid name) in Excel's Name Manager under Formula tab in the Ribbon.
Then assign a formula using GET.CELL function.

=GET.CELL(63,INDIRECT("rc",FALSE))

63 stands for backcolor.
Let's say we name it Background so in any cell with color type:

=Background

Result:
enter image description here

Notice that Cells A2, A3 and A4 returns 3, 4, and 5 respectively which equates to the cells background color index. HTH.
BTW, here's a link on Excel's Color Index

How can I write variables inside the tasks file in ansible

Variable definitions are meant to be used in tasks. But if you want to include them in tasks probably use the register directive. Like this:

- name: Define variable in task.
  shell: echo "http://www.my.url.com"
  register: url

- name: Download apache
  shell: wget {{ item }}
  with_items: url.stdout

You can also look at roles as a way of separating tasks depending on the different roles roles. This way you can have separate variables for each of one of your roles. For example you may have a url variable for apache1 and a separate url variable for the role apache2.

How do I add a new column to a Spark DataFrame (using PySpark)?

The simplest way to add a column is to use "withColumn". Since the dataframe is created using sqlContext, you have to specify the schema or by default can be available in the dataset. If the schema is specified, the workload becomes tedious when changing every time.

Below is an example that you can consider:

from pyspark.sql import SQLContext
from pyspark.sql.types import *
sqlContext = SQLContext(sc) # SparkContext will be sc by default 

# Read the dataset of your choice (Already loaded with schema)
Data = sqlContext.read.csv("/path", header = True/False, schema = "infer", sep = "delimiter")

# For instance the data has 30 columns from col1, col2, ... col30. If you want to add a 31st column, you can do so by the following:
Data = Data.withColumn("col31", "Code goes here")

# Check the change 
Data.printSchema()

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

What is the cleanest way to ssh and run multiple commands in Bash?

Not sure if the cleanest for long commands but certainly the easiest:

ssh user@host "cmd1; cmd2; cmd3"

How can I include a YAML file inside another?

I think the solution used by @maxy-B looks great. However, it didn't succeed for me with nested inclusions. For example if config_1.yaml includes config_2.yaml, which includes config_3.yaml there was a problem with the loader. However, if you simply point the new loader class to itself on load, it works! Specifically, if we replace the old _include function with the very slightly modified version:

def _include(self, loader, node):                                    
     oldRoot = self.root                                              
     filename = os.path.join(self.root, loader.construct_scalar(node))
     self.root = os.path.dirname(filename)                           
     data = yaml.load(open(filename, 'r'), loader = IncludeLoader)                            
     self.root = oldRoot                                              
     return data

Upon reflection I agree with the other comments, that nested loading is not appropriate for yaml in general as the input stream may not be a file, but it is very useful!

How to print variable addresses in C?

You want to use %p to print a pointer. From the spec:

p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner.

And don't forget the cast, e.g.

printf("%p\n",(void*)&a);

Sort array by value alphabetically php

asort() - Maintains key association: yes.

sort() - Maintains key association: no.

Source: http://php.net/manual/en/array.sorting.php

Provide an image for WhatsApp link sharing

Had same issue, added og:image and it didn't work while the url end with slash sign (/). After removing the slash from the URL - the image get loaded.. Interesting bug...

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

Also, if you can't change class B, you can fix the error by using multiple inheritance.

class B:
    def meth(self, arg):
        print arg

class C(B, object):
    def meth(self, arg):
        super(C, self).meth(arg)

print C().meth(1)

How to show one layout on top of the other programmatically in my case?

FrameLayout is not the better way to do this:

Use RelativeLayout instead. You can position the elements anywhere you like. The element that comes after, has the higher z-index than the previous one (i.e. it comes over the previous one).

Example:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimary"
        app:srcCompat="@drawable/ic_information"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is a text."
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:layout_margin="8dp"
        android:padding="5dp"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:background="#A000"
        android:textColor="@android:color/white"/>
</RelativeLayout>

enter image description here

npm check and update package if needed

To really update just one package install NCU and then run it just for that package. This will bump to the real latest.

npm install -g npm-check-updates

ncu -f your-intended-package-name -u

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

On MAC Remove gradle-2.1-all folder from the following path /Users/amitsapra/.gradle/wrapper/dists/gradle-2.1-all and then try gradle build again. I faced same issues with 5.4.1-all.

It takes a little time but fixes everything

Inserting code in this LaTeX document with indentation

Here is how to add inline code:

You can add inline code with {\tt code } or \texttt{ code }. If you want to format the inline code, then it would be best to make your own command

\newcommand{\code}[1]{\texttt{#1}}

Also, note that code blocks can be loaded from other files with

\lstinputlisting[breaklines]{source.c}

breaklines isn't required, but I find it useful. Be aware that you'll have to specify \usepackage{ listings } for this one.

Update: The listings package also includes the \lstinline command, which has the same syntax highlighting features as the \lstlisting and \lstinputlisting commands (see Cloudanger's answer for configuration details). As mentioned in a few other answers, there's also the minted package, which provides the \mintinline command. Like \lstinline, \mintinline provides the same syntax highlighting as a regular minted code block:

\documentclass{article}

\usepackage{minted}

\begin{document}
  This is a sentence with \mintinline{python}{def inlineCode(a="ipsum)}
\end{document}

How to make modal dialog in WPF?

Did you try showing your window using the ShowDialog method?

Don't forget to set the Owner property on the dialog window to the main window. This will avoid weird behavior when Alt+Tabbing, etc.

The executable was signed with invalid entitlements

This is because your device, on which you are running your application is not selected with your provisioning profile.

So just go through Certificates, Identifiers & Profiles select your iOS Provisioning Profiles click on edit then select your Device

enter image description here

org.json.simple cannot be resolved

I was facing same issue in my Spring Integration project. I added below JSON dependencies in pom.xml file. It works for me.

<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20090211</version>
</dependency>

A list of versions can be found here: https://mvnrepository.com/artifact/org.json/json

Preserve Line Breaks From TextArea When Writing To MySQL

i am using this two method steps for preserve same text which is in textarea to store in mysql and at a getting time i can also simply displaying plain text.....

step 1:

$status=$_POST['status'];<br/>
$textToStore = nl2br(htmlentities($status, ENT_QUOTES, 'UTF-8'));

In query enter $textToStore....

step 2:

write code for select query...and direct echo values....

It works

How to convert an NSTimeInterval (seconds) into minutes

Since it's essentially a double...

Divide by 60.0 and extract the integral part and the fractional part.

The integral part will be the whole number of minutes.

Multiply the fractional part by 60.0 again.

The result will be the remaining seconds.

jQuery function to get all unique elements from an array?

    // for numbers
    a = [1,3,2,4,5,6,7,8, 1,1,4,5,6]
    $.unique(a)
    [7, 6, 1, 8, 3, 2, 5, 4]

    // for string
    a = ["a", "a", "b"]
    $.unique(a)
    ["b", "a"]

And for dom elements there is no example is needed here I guess because you already know that!

Here is the jsfiddle link of live example: http://jsfiddle.net/3BtMc/4/

How to search images from private 1.0 registry in docker?

Currently AFAIK there is no easy way to do this as this information should be stored by index which private registry doesn't have. But depending on how you started registry you have 2 options:

  1. if you started registry without -v to store data in separate host folder you can try with docker diff <id_of_registry_container> with this you should get info about changes in container fs. All pushed images should be somewhere in /tmp/registry/repositories/
  2. if you started registry with -v just check content of mounted directory on host

If you used "centos" as name it should be in /tmp/registry/repositories/library/centos. This folder will contain text files which describes image structure. Actual data is in /tmp/registry/images/.

OS X Bash, 'watch' command

I had a similar problem.

When I googled, I came across the blog post Install Watch Command on Mac OS X recently. This is not exactly 'installing software', but simply getting the binary for the 'watch' command.

How do I access ViewBag from JS

try: var cc = @Html.Raw(Json.Encode(ViewBag.CC)

Regular expression [Any number]

if("123".search(/^\d+$/) >= 0){
   // its a number
}

Clearing _POST array fully

To unset the $_POST variable, redeclare it as an empty array:

$_POST = array();

HikariCP - connection is not available

From stack trace:

HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.

The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.

Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.

otherwise, your maximum connections 'at a time' requirement is higher than 20 !

How to read an external properties file in Maven

This answer to a similar question describes how to extend the properties plugin so it can use a remote descriptor for the properties file. The descriptor is basically a jar artifact containing a properties file (the properties file is included under src/main/resources).

The descriptor is added as a dependency to the extended properties plugin so it is on the plugin's classpath. The plugin will search the classpath for the properties file, read the file''s contents into a Properties instance, and apply those properties to the project's configuration so they can be used elsewhere.

HTTPS setup in Amazon EC2

You can also use Amazon API Gateway. Put your application behind API Gateway. Please check this FAQ

Verilog generate/genvar in an always block

for verilog just do

parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
  temp <= {ROWBITS{1'b0}}; // fill with 0
end

Check if two lists are equal

Use SequenceEqual to check for sequence equality because Equals method checks for reference equality.

var a = ints1.SequenceEqual(ints2);

Or if you don't care about elements order use Enumerable.All method:

var a = ints1.All(ints2.Contains);

The second version also requires another check for Count because it would return true even if ints2 contains more elements than ints1. So the more correct version would be something like this:

var a = ints1.All(ints2.Contains) && ints1.Count == ints2.Count;

In order to check inequality just reverse the result of All method:

var a = !ints1.All(ints2.Contains)

Start an activity from a fragment

I use this in my fragment.

Button btn1 = (Button) thisLayout
            .findViewById(R.id.btnDb1);

    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent(getActivity(), otherActivity.class);
            ((MainActivity) getActivity()).startActivity(intent);

        }
    });

    return thisLayout;
}

how to know status of currently running jobs

I found a better answer by Kenneth Fisher. The following query returns only currently running jobs:

SELECT
    ja.job_id,
    j.name AS job_name,
    ja.start_execution_date,      
    ISNULL(last_executed_step_id,0)+1 AS current_executed_step_id,
    Js.step_name
FROM msdb.dbo.sysjobactivity ja 
LEFT JOIN msdb.dbo.sysjobhistory jh ON ja.job_history_id = jh.instance_id
JOIN msdb.dbo.sysjobs j ON ja.job_id = j.job_id
JOIN msdb.dbo.sysjobsteps js
    ON ja.job_id = js.job_id
    AND ISNULL(ja.last_executed_step_id,0)+1 = js.step_id
WHERE
  ja.session_id = (
    SELECT TOP 1 session_id FROM msdb.dbo.syssessions ORDER BY agent_start_date DESC
  )
AND start_execution_date is not null
AND stop_execution_date is null;

You can get more information about a job by adding more columns from msdb.dbo.sysjobactivity table in select clause.

How to debug .htaccess RewriteRule not working

To test your htaccess rewrite rules, simply fill in the url that you're applying the rules to, place the contents of your htaccess on the larger input area and press "Test" button.

http://htaccess.mwl.be/

How do I add python3 kernel to jupyter (IPython)

Here's a Windows/non command line method I found, which worked for me: Find the folder where the kernel files are stored (on my machine - C:\ProgramData\jupyter\kernels - note that ProgramData is a hidden folder), create a copy of the existing kernel's folder, change the name and edit the json file within to point to the new kernel's directory. In this json you can also edit the kernel name that is displayed in ipython (e.g. instead of just python 2 you can specify 2.7.9 if you need to further distinguish for some reason).

Why are iframes considered dangerous and a security risk?

As soon as you're displaying content from another domain, you're basically trusting that domain not to serve-up malware.

There's nothing wrong with iframes per se. If you control the content of the iframe, they're perfectly safe.

How do I reverse an int array in Java?

    public static void main(String args[])    {
        int [] arr = {10, 20, 30, 40, 50}; 
        reverse(arr, arr.length);
    }

    private static void reverse(int[] arr,    int length)    {

        for(int i=length;i>0;i--)    { 
            System.out.println(arr[i-1]); 
        }
    }

Using Exit button to close a winform program

Remove the method, I suspect you might also need to remove it from your Form.Designer.

Otherwise: Application.Exit();

Should work.

That's why the designer is bad for you. :)

CSS - Expand float child DIV height to parent's height

For the parent:

display: flex;

For children:

align-items: stretch;

You should add some prefixes, check caniuse.

How does JPA orphanRemoval=true differ from the ON DELETE CASCADE DML clause

The difference is:
- orphanRemoval = true: "Child" entity is removed when it's no longer referenced (its parent may not be removed).
- CascadeType.REMOVE: "Child" entity is removed only when its "Parent" is removed.

Remove x-axis label/text in chart.js

Faced this issue of removing the labels in Chartjs now. Looks like the documentation is improved. http://www.chartjs.org/docs/#getting-started-global-chart-configuration

Chart.defaults.global.legend.display = false;

this global settings prevents legends from being shown in all Charts. Since this was enough for me, I used it. I am not sure to how to avoid legends for individual charts.

Proper way to empty a C-String

Two other ways are strcpy(str, ""); and string[0] = 0

To really delete the Variable contents (in case you have dirty code which is not working properly with the snippets above :P ) use a loop like in the example below.

#include <string.h>

...

int i=0;
for(i=0;i<strlen(string);i++)
{
    string[i] = 0;
}

In case you want to clear a dynamic allocated array of chars from the beginning, you may either use a combination of malloc() and memset() or - and this is way faster - calloc() which does the same thing as malloc but initializing the whole array with Null.

At last i want you to have your runtime in mind. All the way more, if you're handling huge arrays (6 digits and above) you should try to set the first value to Null instead of running memset() through the whole String.

It may look dirtier at first, but is way faster. You just need to pay more attention on your code ;)

I hope this was useful for anybody ;)

How to add and remove classes in Javascript without jQuery

Another approach to add the class to element using pure JavaScript

For adding class:

document.getElementById("div1").classList.add("classToBeAdded");

For removing class:

document.getElementById("div1").classList.remove("classToBeRemoved");

Note: but not supported in IE <= 9 or Safari <=5.0

How do I install cURL on Windows?

You may find XAMPP at http://www.apachefriends.org/en/xampp.html

http://www.apachefriends.org/en/xampp-windows.html explains XMAPP for Windows.

Yes, there are 3 php.ini files after installation, one is for php4, one is for php5, and one is for apache. Please modify them accordingly.

ImportError: No module named xlsxwriter

I installed it by using a wheel file that can be found at this location: https://pypi.org/project/XlsxWriter/#files

I then ran pip install "XlsxWriter-1.2.8-py2.py3-none-any.whl"

Processing ./XlsxWriter-1.2.8-py2.py3-none-any.whl
Installing collected packages: XlsxWriter
Successfully installed XlsxWriter-1.2.8

Iterating through populated rows

I'm going to make a couple of assumptions in my answer. I'm assuming your data starts in A1 and there are no empty cells in the first column of each row that has data.

This code will:

  1. Find the last row in column A that has data
  2. Loop through each row
  3. Find the last column in current row with data
  4. Loop through each cell in current row up to last column found.

This is not a fast method but will iterate through each one individually as you suggested is your intention.


Sub iterateThroughAll()
    ScreenUpdating = False
    Dim wks As Worksheet
    Set wks = ActiveSheet

    Dim rowRange As Range
    Dim colRange As Range

    Dim LastCol As Long
    Dim LastRow As Long
    LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row

    Set rowRange = wks.Range("A1:A" & LastRow)

    'Loop through each row
    For Each rrow In rowRange
        'Find Last column in current row
        LastCol = wks.Cells(rrow, wks.Columns.Count).End(xlToLeft).Column
        Set colRange = wks.Range(wks.Cells(rrow, 1), wks.Cells(rrow, LastCol))

        'Loop through all cells in row up to last col
        For Each cell In colRange
            'Do something to each cell
            Debug.Print (cell.Value)
        Next cell
    Next rrow
    ScreenUpdating = True
End Sub

AngularJS ng-style with a conditional expression

simple example:

<div ng-style="isTrue && {'background-color':'green'} || {'background-color': 'blue'}" style="width:200px;height:100px;border:1px solid gray;"></div>

{'background-color':'green'} RETURN true

OR the same result:

<div ng-style="isTrue && {'background-color':'green'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>

other conditional possibility:

<div ng-style="count === 0 && {'background-color':'green'}  || count === 1 && {'background-color':'yellow'}" style="width:200px;height:100px;border:1px solid gray;background-color: blue"></div>

How eliminate the tab space in the column in SQL Server 2008

See it might be worked -------

UPDATE table_name SET column_name=replace(column_name, ' ', '') //Remove white space

UPDATE table_name SET column_name=replace(column_name, '\n', '') //Remove newline

UPDATE table_name SET column_name=replace(column_name, '\t', '') //Remove all tab

Thanks Subroto

Position an element relative to its container

You are right that CSS positioning is the way to go. Here's a quick run down:

position: relative will layout an element relative to itself. In other words, the elements is laid out in normal flow, then it is removed from normal flow and offset by whatever values you have specified (top, right, bottom, left). It's important to note that because it's removed from flow, other elements around it will not shift with it (use negative margins instead if you want this behaviour).

However, you're most likely interested in position: absolute which will position an element relative to a container. By default, the container is the browser window, but if a parent element either has position: relative or position: absolute set on it, then it will act as the parent for positioning coordinates for its children.

To demonstrate:

_x000D_
_x000D_
#container {_x000D_
  position: relative;_x000D_
  border: 1px solid red;_x000D_
  height: 100px;_x000D_
}_x000D_
_x000D_
#box {_x000D_
  position: absolute;_x000D_
  top: 50px;_x000D_
  left: 20px;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="box">absolute</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In that example, the top left corner of #box would be 100px down and 50px left of the top left corner of #container. If #container did not have position: relative set, the coordinates of #box would be relative to the top left corner of the browser view port.

Eclipse hangs on loading workbench

After some investigation about file dates I solved the same issue (which is a randomly recurrent trouble on my Kepler) by simply deleting the following file in my local workspace: .metadata.plugins\org.eclipse.jdt.core\variablesAndContainers.dat

with negligible impact on the workspace restoring.

I hope it can help someone else...

Proper MIME type for OTF fonts

One way to silence this warning from Chrome would be to update Chrome and then make sure your mime type is one of these:

 "font/ttf"
 "font/opentype"
 "application/font-woff"
 "application/x-font-type1"
 "application/x-font-ttf"
 "application/x-truetype-font"

This list is per the patch found at Bug 111418 at webkit.org.

The same patch demotes the message from a "Warning" to a "Log", so just upgrading Chrome to any post March-2013 version would get rid of the yellow triangle.

Since the question is about silencing a Chrome warning, and folks might be holding on to old Chrome versions for whatever reasons, I figured this was worth adding.

Flutter: RenderBox was not laid out

i

I used this code to fix the issue of displaying items in the horizontal list.

new Container(
      height: 20,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          ListView.builder(
            scrollDirection: Axis.horizontal,
            shrinkWrap: true,
            itemCount: array.length,
            itemBuilder: (context, index){
              return array[index];
            },
          ),
        ],
      ),
    );

Convert comma separated string of ints to int array

I have found a simple solution which worked for me.

String.Join(",",str.Split(','));

Add text to Existing PDF using Python

You may have better luck breaking the problem down into converting PDF into an editable format, writing your changes, then converting it back into PDF. I don't know of a library that lets you directly edit PDF but there are plenty of converters between DOC and PDF for example.

Python: json.loads returns items prefixing with 'u'

I kept running into this problem when trying to capture JSON data in the log with the Python logging library, for debugging and troubleshooting purposes. Getting the u character is a real nuisance when you want to copy the text and paste it into your code somewhere.

As everyone will tell you, this is because it is a Unicode representation, and it could come from the fact that you’ve used json.loads() to load in the data from a string in the first place.

If you want the JSON representation in the log, without the u prefix, the trick is to use json.dumps() before logging it out. For example:

import json
import logging

# Prepare the data
json_data = json.loads('{"key": "value"}')

# Log normally and get the Unicode indicator
logging.warning('data: {}'.format(json_data))
>>> WARNING:root:data: {u'key': u'value'}

# Dump to a string before logging and get clean output!
logging.warning('data: {}'.format(json.dumps(json_data)))
>>> WARNING:root:data: {'key': 'value'}

How to add to the PYTHONPATH in Windows, so it finds my modules/packages?

For anyone trying to achieve this with Python 3.3+, the Windows installer now includes an option to add python.exe to the system search path. Read more in the docs.

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

I didn't want to unstack or over-complicate this issue, since I just wanted to drop some highly correlated features as part of a feature selection phase.

So I ended up with the following simplified solution:

# map features to their absolute correlation values
corr = features.corr().abs()

# set equality (self correlation) as zero
corr[corr == 1] = 0

# of each feature, find the max correlation
# and sort the resulting array in ascending order
corr_cols = corr.max().sort_values(ascending=False)

# display the highly correlated features
display(corr_cols[corr_cols > 0.8])

In this case, if you want to drop correlated features, you may map through the filtered corr_cols array and remove the odd-indexed (or even-indexed) ones.

Waiting till the async task finish its work

I think the easiest way is to create an interface to get the data from onpostexecute and run the Ui from interface :

Create an Interface :

public interface AsyncResponse {
    void processFinish(String output);
}

Then in asynctask

@Override
protected void onPostExecute(String data) {
    delegate.processFinish(data);
}

Then in yout main activity

@Override
public void processFinish(String data) {
     // do things

}

Move the mouse pointer to a specific position?

You could detect position of the mouse pointer and then move the web page (with body position relative) so they hover over what you want them to click.

For an example you can paste this code on the current page in your browser console (and refresh afterwards)

var upvote_position = $('#answer-12878316').position();
$('body').mousemove(function (event) {
    $(this).css({
        position: 'relative',
        left: (event.pageX - upvote_position.left - 22) + 'px',
        top: (event.pageY - upvote_position.top - 35) + 'px'
    });        
});

How to find files recursively by file type and copy them to a directory while in ssh?

Something like this should work.

ssh [email protected] 'find -type f -name "*.pdf" -exec cp {} ./pdfsfolder \;'

How to use System.Net.HttpClient to post a complex type?

If you want the types of convenience methods mentioned in other answers but need portability (or even if you don't), you might want to check out Flurl [disclosure: I'm the author]. It (thinly) wraps HttpClient and Json.NET and adds some fluent sugar and other goodies, including some baked-in testing helpers.

Post as JSON:

var resp = await "http://localhost:44268/api/test".PostJsonAsync(widget);

or URL-encoded:

var resp = await "http://localhost:44268/api/test".PostUrlEncodedAsync(widget);

Both examples above return an HttpResponseMessage, but Flurl includes extension methods for returning other things if you just want to cut to the chase:

T poco = await url.PostJsonAsync(data).ReceiveJson<T>();
dynamic d = await url.PostUrlEncodedAsync(data).ReceiveJson();
string s = await url.PostUrlEncodedAsync(data).ReceiveString();

Flurl is available on NuGet:

PM> Install-Package Flurl.Http

What is char ** in C?

It is a pointer to a pointer, so yes, in a way it's a 2D character array. In the same way that a char* could indicate an array of chars, a char** could indicate that it points to and array of char*s.

How to declare and initialize a static const array as a class member?

// in foo.h
class Foo {
    static const unsigned char* Msg;
};

// in foo.cpp
static const unsigned char Foo_Msg_data[] = {0x00,0x01};
const unsigned char* Foo::Msg = Foo_Msg_data;

Iterating through a list in reverse order in java

Very simple Example:

List<String> list = new ArrayList<String>();

list.add("ravi");

list.add("kant");

list.add("soni");

// Iterate to disply : result will be as ---     ravi kant soni

for (String name : list) {
  ...
}

//Now call this method

Collections.reverse(list);

// iterate and print index wise : result will be as ---     soni kant ravi

for (String name : list) {
  ...
}

How can I change cols of textarea in twitter-bootstrap?

This works for me with twitter bootstrap 2 and simple_form 2.0.4
Result is a span6 text area in a span9 row

 <div class="row" >
   <div class="span9">
     <%= f.input :some_text, :input_html => {:rows => 5, :placeholder => "Enter some text.", :class => "span6"}%>
   </div>
 </div>

Trying to get property of non-object MySQLi result

I think thats not the reason everybody told above. There is something wrong in your code, maybe miss spelling or mismatching with the database column names. If mysqli query gets no result then it will return false, so that it is not a object - is a wrong idea. Everything works fine. it returns 1 or 0 if query have result or not.

So, my suggestion is check your variable names and table column names or any other misspelling.

How can I recognize touch events using jQuery in Safari for iPad? Is it possible?

Using touchstart or touchend alone is not a good solution, because if you scroll the page, the device detects it as touch or tap too. So, the best way to detect a tap and click event at the same time is to just detect the touch events which are not moving the screen (scrolling). So to do this, just add this code to your application:

$(document).on('touchstart', function() {
    detectTap = true; // Detects all touch events
});
$(document).on('touchmove', function() {
    detectTap = false; // Excludes the scroll events from touch events
});
$(document).on('click touchend', function(event) {
    if (event.type == "click") detectTap = true; // Detects click events
       if (detectTap){
          // Here you can write the function or codes you want to execute on tap

       }
 });

I tested it and it works fine for me on iPad and iPhone. It detects tap and can distinguish tap and touch scroll easily.

How to remove "index.php" in codeigniter's path

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* /codeigniter/index.php/$0 [PT,L]

after changing RewriteRule .* index.php/$0 [PT,L] with the project folder name "codeigniter".its working for me. Thanks guys for your support.

Replacing blank values (white space) with NaN in pandas

you can also use a filter to do it.

df = PD.DataFrame([
    [-0.532681, 'foo', 0],
    [1.490752, 'bar', 1],
    [-1.387326, 'foo', 2],
    [0.814772, 'baz', ' '],     
    [-0.222552, '   ', 4],
    [-1.176781,  'qux', '  '])
    df[df=='']='nan'
    df=df.astype(float)

What are the differences between B trees and B+ trees?

B+Trees are much easier and higher performing to do a full scan, as in look at every piece of data that the tree indexes, since the terminal nodes form a linked list. To do a full scan with a B-Tree you need to do a full tree traversal to find all the data.

B-Trees on the other hand can be faster when you do a seek (looking for a specific piece of data by key) especially when the tree resides in RAM or other non-block storage. Since you can elevate commonly used nodes in the tree there are less comparisons required to get to the data.

Fastest way to find second (third...) highest/lowest value in vector or column

Here you go... kit is the obvious winner!

N = 1e6
x = rnorm(N)

maxN <- function(x, N=2){
  len <- length(x)
  if(N>len){
    warning('N greater than length(x).  Setting N=length(x)')
    N <- length(x)
  }
  sort(x,partial=len-N+1)[len-N+1]
}

microbenchmark::microbenchmark(
  Rfast = Rfast::nth(x,5,descending = T),
  maxN = maxN(x,5),
  order = x[order(x, decreasing = T)[5]],
  kit = x[kit::topn(x, 5L,decreasing = T)[5L]]
) 
# Unit: milliseconds
# expr       min        lq     mean    median        uq        max neval
# Rfast 12.311168 12.473771 16.36982 12.702134 16.110779 102.749873   100
# maxN  12.922118 13.124358 17.49628 18.977537 20.053139  28.928694   100
# order 50.443100 50.926975 52.54067 51.270163 52.323116  66.561606   100
# kit    1.177202  1.216371  1.29542  1.240228  1.297286   2.771715   100

Edit: I forgot that kit::topn has hasna option...let's do another run.

microbenchmark::microbenchmark(
  Rfast = Rfast::nth(x,5,descending = T),
  maxN = maxN(x,5),
  order = x[order(x, decreasing = T)[5]],
  kit = x[kit::topn(x, 5L,decreasing = T)[5L]],
  kit2 = x[kit::topn(x, 5L,decreasing = T,hasna = F)[5L]],
  unit = "ms"
) 
# Unit: milliseconds
# expr       min        lq       mean     median        uq       max neval
# Rfast 13.194314 13.358787 14.7227116 13.4560340 14.551194 24.524105   100
# maxN   7.378960  7.527661 10.0747803  7.7119715 12.217756 67.409526   100
# order 50.088927 50.488832 52.4714347 50.7415680 52.267003 70.062662   100
# kit    1.180698  1.217237  1.2975441  1.2429790  1.278243  3.263202   100
# kit2   0.842354  0.876329  0.9398055  0.9109095  0.944407  2.135903   100

How to open an Excel file in C#?

Is this a commercial application or some hobbyist / open source software?

I'm asking this because in my experience, all free .NET Excel handling alternatives have serious problems, for different reasons. For hobbyist things, I usually end up porting jExcelApi from Java to C# and using it.

But if this is a commercial application, you would be better off by purchasing a third party library, like Aspose.Cells. Believe me, it totally worths it as it saves a lot of time and time ain't free.

Android Camera Preview Stretched

OK, so I think there is no sufficient answer for general camera preview stretching problem. Or at least I didn't find one. My app also suffered this stretching syndrome and it took me a while to puzzle together a solution from all the user answers on this portal and internet.

I tried @Hesam's solution but it didn't work and left my camera preview majorly distorted.

First I show the code of my solution (the important parts of the code) and then I explain why I took those steps. There is room for performance modifications.

Main activity xml layout:

<RelativeLayout 
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <FrameLayout
        android:id="@+id/camera_preview"
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
    />
</RelativeLayout>

Camera Preview:

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

private SurfaceHolder prHolder;
private Camera prCamera;
public List<Camera.Size> prSupportedPreviewSizes;
private Camera.Size prPreviewSize;

@SuppressWarnings("deprecation")
public YoCameraPreview(Context context, Camera camera) {
    super(context);
    prCamera = camera;

    prSupportedPreviewSizes = prCamera.getParameters().getSupportedPreviewSizes();

    prHolder = getHolder();
    prHolder.addCallback(this);
    prHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

public void surfaceCreated(SurfaceHolder holder) {
    try {
        prCamera.setPreviewDisplay(holder);
        prCamera.startPreview();
    } catch (IOException e) {
        Log.d("Yologram", "Error setting camera preview: " + e.getMessage());
    }
}

public void surfaceDestroyed(SurfaceHolder holder) {
}

public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    if (prHolder.getSurface() == null){
      return;
    }

    try {
        prCamera.stopPreview();
    } catch (Exception e){
    }

    try {
        Camera.Parameters parameters = prCamera.getParameters();
        List<String> focusModes = parameters.getSupportedFocusModes();
        if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
        }
        parameters.setPreviewSize(prPreviewSize.width, prPreviewSize.height);

        prCamera.setParameters(parameters);
        prCamera.setPreviewDisplay(prHolder);
        prCamera.startPreview();

    } catch (Exception e){
        Log.d("Yologram", "Error starting camera preview: " + e.getMessage());
    }
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
    final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);

    setMeasuredDimension(width, height);

    if (prSupportedPreviewSizes != null) {
        prPreviewSize = 
            getOptimalPreviewSize(prSupportedPreviewSizes, width, height);
    }    
}

public Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {

    final double ASPECT_TOLERANCE = 0.1;
    double targetRatio = (double) h / w;

    if (sizes == null)
        return null;

    Camera.Size optimalSize = null;
    double minDiff = Double.MAX_VALUE;

    int targetHeight = h;

    for (Camera.Size size : sizes) {
        double ratio = (double) size.width / size.height;
        if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
            continue;

        if (Math.abs(size.height - targetHeight) < minDiff) {
            optimalSize = size;
            minDiff = Math.abs(size.height - targetHeight);
        }
    }

    if (optimalSize == null) {
        minDiff = Double.MAX_VALUE;
        for (Camera.Size size : sizes) {
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }
    }

    return optimalSize;
}
}

Main activity:

public class MainActivity extends Activity {

...

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);     
    setContentView(R.layout.activity_main);

        maCamera = getCameraInstance();

        maLayoutPreview = (FrameLayout) findViewById(R.id.camera_preview);

        maPreview = new CameraPreview(this, maCamera);

        Point displayDim = getDisplayWH();
        Point layoutPreviewDim = calcCamPrevDimensions(displayDim, 
                maPreview.getOptimalPreviewSize(maPreview.prSupportedPreviewSizes, 
                    displayDim.x, displayDim.y));
        if (layoutPreviewDim != null) {
            RelativeLayout.LayoutParams layoutPreviewParams = 
                (RelativeLayout.LayoutParams) maLayoutPreview.getLayoutParams();
            layoutPreviewParams.width = layoutPreviewDim.x;
            layoutPreviewParams.height = layoutPreviewDim.y;
            layoutPreviewParams.addRule(RelativeLayout.CENTER_IN_PARENT);
            maLayoutPreview.setLayoutParams(layoutPreviewParams);
        }
        maLayoutPreview.addView(maPreview);
}

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private Point getDisplayWH() {

    Display display = this.getWindowManager().getDefaultDisplay();
    Point displayWH = new Point();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        display.getSize(displayWH);
        return displayWH;
    }
    displayWH.set(display.getWidth(), display.getHeight());
    return displayWH;
}

private Point calcCamPrevDimensions(Point disDim, Camera.Size camDim) {

    Point displayDim = disDim;
    Camera.Size cameraDim = camDim;

    double widthRatio = (double) displayDim.x / cameraDim.width;
    double heightRatio = (double) displayDim.y / cameraDim.height;

    // use ">" to zoom preview full screen
    if (widthRatio < heightRatio) {
        Point calcDimensions = new Point();
        calcDimensions.x = displayDim.x;
        calcDimensions.y = (displayDim.x * cameraDim.height) / cameraDim.width;
        return calcDimensions;
    }
    // use "<" to zoom preview full screen
    if (widthRatio > heightRatio) { 
        Point calcDimensions = new Point();
        calcDimensions.x = (displayDim.y * cameraDim.width) / cameraDim.height;
        calcDimensions.y = displayDim.y;
        return calcDimensions;
    }
    return null;
}   
}

My commentary:

The point of all this is, that although you calculate the optimal camera size in getOptimalPreviewSize() you only pick the closest ratio to fit your screen. So unless the ratio is exactly the same the preview will stretch.

Why will it stretch? Because your FrameLayout camera preview is set in layout.xml to match_parent in width and height. So that is why the preview will stretch to full screen.

What needs to be done is to set camera preview layout width and height to match the chosen camera size ratio, so the preview keeps its aspect ratio and won't distort.

I tried to use the CameraPreview class to do all the calculations and layout changes, but I couldn't figure it out. I tried to apply this solution, but SurfaceView doesn't recognize getChildCount () or getChildAt (int index). I think, I got it working eventually with a reference to maLayoutPreview, but it was misbehaving and applied the set ratio to my whole app and it did so after first picture was taken. So I let it go and moved the layout modifications to the MainActivity.

In CameraPreview I changed prSupportedPreviewSizes and getOptimalPreviewSize() to public so I can use it in MainActivity. Then I needed the display dimensions (minus the navigation/status bar if there is one) and chosen optimal camera size. I tried to get the RelativeLayout (or FrameLayout) size instead of display size, but it was returning zero value. This solution didn't work for me. The layout got it's value after onWindowFocusChanged (checked in the log).

So I have my methods for calculating the layout dimensions to match the aspect ratio of chosen camera size. Now you just need to set LayoutParams of your camera preview layout. Change the width, height and center it in parent.

There are two choices how to calculate the preview dimensions. Either you want it to fit the screen with black bars (if windowBackground is set to null) on the sides or top/bottom. Or you want the preview zoomed to full screen. I left comment with more information in calcCamPrevDimensions().

How do I include a JavaScript file in another JavaScript file?

There is also Head.js. It is very easy to deal with:

head.load("js/jquery.min.js",
          "js/jquery.someplugin.js",
          "js/jquery.someplugin.css", function() {
  alert("Everything is ok!");
});

As you see, it's easier than Require.js and as convenient as jQuery's $.getScript method. It also has some advanced features, like conditional loading, feature detection and much more.

Check if value is zero or not null in python

The simpler way:

h = ''
i = None
j = 0
k = 1
print h or i or j or k

Will print 1

print k or j or i or h

Will print 1

Check if input is number or letter javascript

Just find the remainder by dividing by 1, that is x%1. If the remainder is 0, it means that x is a whole number. Otherwise, you have to display the message "Must input numbers". This will work even in the case of strings, decimal numbers etc.

function checkInp()
{
    var x = document.forms["myForm"]["age"].value;
    if ((x%1) != 0) 
    {
        alert("Must input numbers");
        return false;
    }
}

How do I specify local .gem files in my Gemfile?

You can force bundler to use the gems you deploy using "bundle package" and "bundle install --local"

On your development machine:

bundle install

(Installs required gems and makes Gemfile.lock)

bundle package

(Caches the gems in vendor/cache)

On the server:

bundle install --local

(--local means "use the gems from vendor/cache")

How can I display an RTSP video stream in a web page?

Wowza

  1. Re-streaming RTSP to RTMP(Flash Player) Will not work with Android Chrome or FF (Flash is not supported)
  2. Re-streaming RTSP to HLS

Web Call Server (Flashphoner)

  1. Re-Streaming RTSP to WebRTC (Native browser feature for Chrome and FF either on Android or desktop)

  2. Re-Streaming RTSP to Websockets (iOS Safari and Chrome/FF Desktop)

Take a look at this article.

Execute function after Ajax call is complete

Try this code:

var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
 $.ajax({                                            
     url: 'api.php',                        
     data: 'id1='+q+'',                                                         
     dataType: 'json',
     async:false,                    
     success: function(data)          
     {   
        id = data[0];              
        vname = data[1];
     },
    complete: function (data) {
      printWithAjax(); 
     }
    });

  }//end of the for statement
  }//end of ajax call function

The "complete" function executes only after the "success" of ajax. So try to call the printWithAjax() on "complete". This should work for you.

Stopping an Android app from console

adb shell killall -9 com.your.package.name

according to MAC "mandatory access control" you probably have the permission to kill process which is not started by root

have fun!

Private pages for a private Github repo

As outlined above, Github pages do not support that functionality. I had the same issue when our team decided to host project documentation (static HTML) internally and privately.

I ended up creating a service https://www.privatehub.cloud It is basically a simple proxy server with Github OAuth authentication, so it merely returns your GitHub repository content with a proper MIME type. By design, only who have access to foo will be able to see foo content at https://bar-foo.privatehub.cloud. From functional point of view, you can think about it as a simplified GitHub pages with built-in authentication.

Unfortunately, Github OAuth does not allow to request read-only access to private repos, so the server needs the full access (obviously, it does not write anything to your repo). As GitHub API allows to retrieve files under 1 Mb only, the service cannot return larger files. Yet, I found the service is quite suitable for small projects for internal documentation or staging version of a website.

URL to compose a message in Gmail (with full Gmail interface and specified to, bcc, subject, etc.)

The example URLs for standard gmail, above, return a google error.

The February 2014 post to thread 2583928 recommends replacing view=cm&fs=1&tf=1 with &v=b&cs=wh.

Note: It also no longer seems possible to autopopulate the mail body.

Hibernate Error executing DDL via JDBC Statement

spring.jpa.hibernate.ddl-auto = update

change update to create, and run it

after run safely again change create to update so again all tables will not create and you can use your previous data

Cordova app not displaying correctly on iPhone X (Simulator)

For a manual fix to an existing cordova project

The black bars

Add this to your info.plist file. Fixing the launch image is a separate issue i.e. How to Add iPhoneX Launch Image

<key>UILaunchStoryboardName</key>
<string>CDVLaunchScreen</string>

The white bars

Set viewport-fit=cover in the meta tag

<meta name="viewport" content="initial-scale=1, width=device-width, height=device-height, viewport-fit=cover">

Transparent background on winforms?

Here was my solution:

In the constructors add these two lines:

this.BackColor = Color.LimeGreen;
this.TransparencyKey = Color.LimeGreen;

In your form, add this method:

protected override void OnPaintBackground(PaintEventArgs e)
{
    e.Graphics.FillRectangle(Brushes.LimeGreen, e.ClipRectangle);
}

Be warned, not only is this form fully transparent inside the frame, but you can also click through it. However, it might be cool to draw an image onto it and make the form able to be dragged everywhere to create a custom shaped form.

Vuejs: v-model array in multiple input

If you were asking how to do it in vue2 and make options to insert and delete it, please, have a look an js fiddle

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    finds: [] _x000D_
  },_x000D_
  methods: {_x000D_
    addFind: function () {_x000D_
      this.finds.push({ value: 'def' });_x000D_
    },_x000D_
    deleteFind: function (index) {_x000D_
      console.log(index);_x000D_
      console.log(this.finds);_x000D_
      this.finds.splice(index, 1);_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <h1>Finds</h1>_x000D_
  <div v-for="(find, index) in finds">_x000D_
    <input v-model="find.value">_x000D_
    <button @click="deleteFind(index)">_x000D_
      delete_x000D_
    </button>_x000D_
  </div>_x000D_
  _x000D_
  <button @click="addFind">_x000D_
    New Find_x000D_
  </button>_x000D_
  _x000D_
  <pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to create an email form that can send email using html

You can't, the only things you can do with html is open your default email application. You must use a server code to send an email, php, asp .net....

Display HTML form values in same page after submit using Ajax

display html form values in same page after clicking on submit button using JS & html codes. After opening it up again it should give that comments in that page.

LaTeX source code listing like in professional books

I am happy with the listings package:

Listing example

Here is how I configure it:

\lstset{
language=C,
basicstyle=\small\sffamily,
numbers=left,
numberstyle=\tiny,
frame=tb,
columns=fullflexible,
showstringspaces=false
}

I use it like this:

\begin{lstlisting}[caption=Caption example.,
  label=a_label,
  float=t]
// Insert the code here
\end{lstlisting}

Create an ISO date object in javascript

try below:

var temp_datetime_obj = new Date();

collection.find({
    start_date:{
        $gte: new Date(temp_datetime_obj.toISOString())
    }
}).toArray(function(err, items) { 
    /* you can console.log here */ 
});

Site does not exist error for a2ensite

There's another good way, just edit the file apache2.conf theres a line at the end

IncludeOptional sites-enabled/*.conf

just remove the .conf at the end, like this

IncludeOptional sites-enabled/*

and restart the server.

(I tried this only in the Ubuntu 13.10, when I updated it.)

Get Filename Without Extension in Python

If I had to do this with a regex, I'd do it like this:

s = re.sub(r'\.jpg$', '', s)

How do I store an array in localStorage?

Just created this:

https://gist.github.com/3854049

//Setter
Storage.setObj('users.albums.sexPistols',"blah");
Storage.setObj('users.albums.sexPistols',{ sid : "My Way", nancy : "Bitch" });
Storage.setObj('users.albums.sexPistols.sid',"Other songs");

//Getters
Storage.getObj('users');
Storage.getObj('users.albums');
Storage.getObj('users.albums.sexPistols');
Storage.getObj('users.albums.sexPistols.sid');
Storage.getObj('users.albums.sexPistols.nancy');

What are Keycloak's OAuth2 / OpenID Connect endpoints?

Actually link to .well-know is on the first tab of your realm settings - but link doesn't look like link, but as value of text box... bad ui design. Screenshot of Realm's General Tab

Convert Json string to Json object in Swift 4

The problem is that you thought your jsonString is a dictionary. It's not.

It's an array of dictionaries. In raw json strings, arrays begin with [ and dictionaries begin with {.


I used your json string with below code :

let string = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]"
let data = string.data(using: .utf8)!
do {
    if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
    {
       print(jsonArray) // use the json here     
    } else {
        print("bad json")
    }
} catch let error as NSError {
    print(error)
}

and I am getting the output :

[["form_desc": <null>, "form_name": Activity 4 with Images, "canonical_name": df_SAWERQ, "form_id": 3465]]

Control cannot fall through from one case label

You need to add a break statement:

switch (searchType)
{
case "SearchBooks":
    Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
    Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
    break;
case "SearchAuthors":
    Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
    Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
    break;
}

This assumes that you want to either handle the SearchBooks case or the SearchAuthors - as you had written in, in a traditional C-style switch statement the control flow would have "fallen through" from one case statement to the next meaning that all 4 lines of code get executed in the case where searchType == "SearchBooks".

The compiler error you are seeing was introduced (at least in part) to warn the programmer of this potential error.

As an alternative you could have thrown an error or returned from a method.

How can I insert binary file data into a binary SQL field using a simple insert statement?

If you mean using a literal, you simply have to create a binary string:

insert into Files (FileId, FileData) values (1, 0x010203040506)

And you will have a record with a six byte value for the FileData field.


You indicate in the comments that you want to just specify the file name, which you can't do with SQL Server 2000 (or any other version that I am aware of).

You would need a CLR stored procedure to do this in SQL Server 2005/2008 or an extended stored procedure (but I'd avoid that at all costs unless you have to) which takes the filename and then inserts the data (or returns the byte string, but that can possibly be quite long).


In regards to the question of only being able to get data from a SP/query, I would say the answer is yes, because if you give SQL Server the ability to read files from the file system, what do you do when you aren't connected through Windows Authentication, what user is used to determine the rights? If you are running the service as an admin (God forbid) then you can have an elevation of rights which shouldn't be allowed.

How do I measure separate CPU core usage for a process?

You can still do this in top. While top is running, press '1' on your keyboard, it will then show CPU usage per core.

Limit the processes shown by having that specific process run under a specific user account and use Type 'u' to limit to that user

How can you run a Java program without main method?

public class X { static {
  System.out.println("Main not required to print this");
  System.exit(0);
}}

Run from the cmdline with java X.

JavaScript, getting value of a td with id name

if i click table name its shown all fields about table. i did table field to show. but i need to know click function.

My Code:

$sql = "SHOW tables from database_name where tables_in_databasename not like '%tablename' and tables_in_databasename not like '%tablename%'";


$result=mysqli_query($cons,$sql);

$count = 0;

$array = array();

while ($row = mysqli_fetch_assoc($result)) {

    $count++;

    $tbody_txt .= '<tr>';

    foreach ($row as $key => $value) {
        if($count  == '1') {
            $thead_txt .='<td>'.$key.'</td>';
        }
        $tbody_txt .='<td>'.$value.'</td>';


        $array[$key][] = $value;
    }
}?>

MS Access DB Engine (32-bit) with Office 64-bit

If both versions of Microsoft Access Database Engine 2010 can't coexists, then your only solution is to complain to Microsoft, regarding loading 64 bits versions of this in your 32 bits app is impossible directly, what you can do is a service that runs in 64 bits that comunicates with another 32 bits service or your application via pipes or networks sockets, but it may require a significant effort.