Programs & Examples On #Sublist

How to Get a Sublist in C#

Your collection class could have a method that returns a collection (a sublist) based on criteria passed in to define the filter. Build a new collection with the foreach loop and pass it out.

Or, have the method and loop modify the existing collection by setting a "filtered" or "active" flag (property). This one could work but could also cause poblems in multithreaded code. If other objects deped on the contents of the collection this is either good or bad depending of how you use the data.

Python list / sublist selection -1 weirdness

-1 isn't special in the sense that the sequence is read backwards, it rather wraps around the ends. Such that minus one means zero minus one, exclusive (and, for a positive step value, the sequence is read "from left to right".

so for i = [1, 2, 3, 4], i[2:-1] means from item two to the beginning minus one (or, 'around to the end'), which results in [3]. The -1th element, or element 0 backwards 1 is the last 4, but since it's exclusive, we get 3.

I hope this is somewhat understandable.

Bootstrap 3 collapsed menu doesn't close on click

If you only want your navigation to toggle when used on a mobile screen, just adding data-toggle="collapse" and data-target="#navbar" to your a elements will work on the mobile screen, but will give you a weird flicker when clicked on a desktop screen. The jQuery solutions do not work well if you are in an Aurelia or Angular environment.

The best solution for me was to create a custom attribute that listens to the corresponding media query and adds in the data-toggle="collapse"attribute if desired:

<a href="#" ... collapse-toggle-if-less768 data-target="#navbar"> ...

The custom attribute with Aurelia looks like this:

_x000D_
_x000D_
import {autoinject} from 'aurelia-framework';_x000D_
_x000D_
@autoinject_x000D_
export class CollapseToggleIfLess768CustomAttribute {_x000D_
  element: Element;_x000D_
_x000D_
  constructor(element: Element) {_x000D_
    this.element = element;_x000D_
    var mql = window.matchMedia("(min-width: 768px)");_x000D_
    mql.addListener((mediaQueryList: MediaQueryList) => this.handleMediaChange(mediaQueryList));_x000D_
    this.handleMediaChange(mql);_x000D_
  }_x000D_
_x000D_
  handleMediaChange(mediaQueryList: MediaQueryList) {_x000D_
    if (mediaQueryList.matches) {_x000D_
      var dataToggle = this.element.attributes.getNamedItem("data-toggle");_x000D_
      if (dataToggle) {_x000D_
        this.element.attributes.removeNamedItem("data-toggle");_x000D_
      }_x000D_
    } else {_x000D_
      var dataToggle = this.element.attributes.getNamedItem("data-toggle");_x000D_
      if (!dataToggle) {_x000D_
        var dataToggle = document.createAttribute("data-toggle");_x000D_
        dataToggle.value = "collapse";_x000D_
        this.element.attributes.setNamedItem(dataToggle);_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is Static. You can not invoke a non-static method from a static method.

GetRandomBits()

is not a static method. Either you have to create an instance of Program

Program p = new Program();
p.GetRandomBits();

or make

GetRandomBits() static.

ReactJS and images in public folder

To reference images in public there are two ways I know how to do it straight forward. One is like above from Homam Bahrani.

using

    <img src={process.env.PUBLIC_URL + '/yourPathHere.jpg'} /> 

And since this works you really don't need anything else but, this also works...

    <img src={window.location.origin + '/yourPathHere.jpg'} />

firestore: PERMISSION_DENIED: Missing or insufficient permissions

Check if the service account is added in IAM & Admin https://console.cloud.google.com/iam-admin/iam with an appropriate role such as Editor

Changing user agent on urllib2.urlopen

For urllib you can use:

from urllib import FancyURLopener

class MyOpener(FancyURLopener, object):
    version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'

myopener = MyOpener()
myopener.retrieve('https://www.google.com/search?q=test', 'useragent.html')

Access an arbitrary element in a dictionary in Python

How about, this. Not mentioned here yet.

py 2 & 3

a = {"a":2,"b":3}
a[list(a)[0]] # the first element is here
>>> 2

How to get package name from anywhere?

You can use undocumented method android.app.ActivityThread.currentPackageName() :

Class<?> clazz = Class.forName("android.app.ActivityThread");
Method method  = clazz.getDeclaredMethod("currentPackageName", null);
String appPackageName = (String) method.invoke(clazz, null);

Caveat: This must be done on the main thread of the application.

Thanks to this blog post for the idea: http://blog.javia.org/static-the-android-application-package/ .

UIView background color in Swift

self.view.backgroundColor = UIColor.redColor()

In Swift 3:

self.view.backgroundColor = UIColor.red

There is no tracking information for the current branch

I run into this exact message often because I create a local branches via git checkout -b <feature-branch-name> without first creating the remote branch.

After all the work was finished and committed locally the fix was git push -u which created the remote branch, pushed all my work, and then the merge-request URL.

Creating instance list of different objects

List anyObject = new ArrayList();

or

List<Object> anyObject = new ArrayList<Object>();

now anyObject can hold objects of any type.

use instanceof to know what kind of object it is.

Create a string and append text to it

Concatenate with & operator

Dim str as String  'no need to create a string instance
str = "Hello " & "World"

You can concate with the + operator as well but you can get yourself into trouble when trying to concatenate numbers.


Concatenate with String.Concat()

str = String.Concat("Hello ", "World")

Useful when concatenating array of strings


StringBuilder.Append()

When concatenating large amounts of strings use StringBuilder, it will result in much better performance.

    Dim sb as new System.Text.StringBuilder()
    str = sb.Append("Hello").Append(" ").Append("World").ToString()

Strings in .NET are immutable, resulting in a new String object being instantiated for every concatenation as well a garbage collection thereof.

How to store Emoji Character in MySQL Database

If you are inserting using PHP, and you have followed the various ALTER database and ALTER table options above, make sure your php connection's charset is utf8mb4.

Example of connection string:

$this->pdo = new PDO("mysql:host=$ip;port=$port;dbname=$db;charset=utf8mb4", etc etc

Notice the "charset" is utf8mb4, not just utf8!

Git merge without auto commit

Note the output while doing the merge - it is saying Fast Forward

In such situations, you want to do:

git merge v1.0 --no-commit --no-ff

Batch file to delete folders older than 10 days in Windows 7

Adapted from this answer to a very similar question:

FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"

You should run this command from within your d:\study folder. It will delete all subfolders which are older than 10 days.

The /S /Q after the rd makes it delete folders even if they are not empty, without prompting.

I suggest you put the above command into a .bat file, and save it as d:\study\cleanup.bat.

Efficient way to apply multiple filters to pandas DataFrame or Series

Chaining conditions creates long lines, which are discouraged by pep8. Using the .query method forces to use strings, which is powerful but unpythonic and not very dynamic.

Once each of the filters is in place, one approach is

import numpy as np
import functools
def conjunction(*conditions):
    return functools.reduce(np.logical_and, conditions)

c_1 = data.col1 == True
c_2 = data.col2 < 64
c_3 = data.col3 != 4

data_filtered = data[conjunction(c1,c2,c3)]

np.logical operates on and is fast, but does not take more than two arguments, which is handled by functools.reduce.

Note that this still has some redundancies: a) shortcutting does not happen on a global level b) Each of the individual conditions runs on the whole initial data. Still, I expect this to be efficient enough for many applications and it is very readable.

You can also make a disjunction (wherein only one of the conditions needs to be true) by using np.logical_or instead:

import numpy as np
import functools
def disjunction(*conditions):
    return functools.reduce(np.logical_or, conditions)

c_1 = data.col1 == True
c_2 = data.col2 < 64
c_3 = data.col3 != 4

data_filtered = data[disjunction(c1,c2,c3)]

How to check if array element exists or not in javascript?

_x000D_
_x000D_
var fruits = ["Banana", "Orange", "Apple", "Mango"];_x000D_
if(fruits.indexOf("Banana") == -1){_x000D_
    console.log('item not exist')_x000D_
} else {_x000D_
 console.log('item exist')_x000D_
}
_x000D_
_x000D_
_x000D_

In PANDAS, how to get the index of a known value?

I think this may help you , both index and columns of the values.

value you are looking for is not duplicated:

poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
value=poz.iloc[0,0]
index=poz.index.item()
column=poz.columns.item()

you can get its index and column

duplicated:

matrix=pd.DataFrame([[1,1],[1,np.NAN]],index=['q','g'],columns=['f','h'])
matrix
Out[83]: 
   f    h
q  1  1.0
g  1  NaN
poz=matrix[matrix==minv].dropna(axis=1,how='all').dropna(how='all')
index=poz.stack().index.tolist()
index
Out[87]: [('q', 'f'), ('q', 'h'), ('g', 'f')]

you will get a list

How to set background image of a view?

Besides all of the other responses here, I really don't think that using backgroundColor in this way is the proper way to do things. Personally, I would create a UIImageView and insert it into your view hierarchy. You can either insert it into your top view and push it all the way to the back with sendSubviewToBack: or you can make the UIImageView the parent view.

I wouldn't worry about things like how efficient each implementation is at this point because unless you actually see an issue, it really doesn't matter. Your first priority for now should be writing code that you can understand and can easily be changed. Creating a UIColor to use as your background image isn't the clearest method of doing this.

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

You can try this:

Select To_date ('15/2/2007 00:00:00', 'DD/MM/YYYY HH24:MI:SS'),
       To_date ('28/2/2007 10:12', 'DD/MM/YYYY HH24:MI:SS')
  From DUAL;

Source: http://notsyncing.org/2008/02/manipulando-fechas-con-horas-en-plsql-y-sql/

HTML Button : Navigate to Other Page - Different Approaches

I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.

I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.

Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.

Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.

How to create custom exceptions in Java?

public class MyException extends Exception {
        // special exception code goes here
}

Throw it as:

 throw new MyException ("Something happened")

Catch as:

catch (MyException e)
{
   // something
}

Is there any way to wait for AJAX response and halt execution?

New, using jquery's promise implementation:

function functABC(){

  // returns a promise that can be used later. 

  return $.ajax({
    url: 'myPage.php',
    data: {id: id}
  });
}


functABC().then( response => 
  console.log(response);
);

Nice read e.g. here.

This is not "synchronous" really, but I think it achieves what the OP intends.

Old, (jquery's async option has since been deprecated):

All Ajax calls can be done either asynchronously (with a callback function, this would be the function specified after the 'success' key) or synchronously - effectively blocking and waiting for the servers answer. To get a synchronous execution you have to specify

async: false 

like described here

Note, however, that in most cases asynchronous execution (via callback on success) is just fine.

Sublime Text 3 how to change the font size of the file sidebar?

The answers are omitting the square brackets, in the case one is creating the file from scratch.

To recap, for the ST3 users who don't have the Default.sublime-theme file (which is actually the default configuration), the simplest procedure is:

  1. Navigate to Sublime Text -> Preferences -> Browse Packages
  2. Open the User directory
  3. Create a file named Default.sublime-theme (if you're using the default theme, otherwise use the theme name, e.g. Material-Theme-Darker.sublime-theme) with the following content (modify font.size as required):

[
    {
        "class": "sidebar_label",
        "color": [0, 0, 0],
        "font.bold": false,
        "font.size": 12
    },
]

For reference, here there is the full file (as found in ST2).

Ubuntu 18.04

Location of theme setting on Ubuntu 18.04, installed via sudo apt install sublime-text:

~/.config/sublime-text-3/Packages/User/Default.sublime-theme

MacOS

Location of theme setting on MacOS, installed via DMG:

~/Library/Application\ Support/Sublime\ Text\ 3/Packages/User/Default.sublime-theme

How to save picture to iPhone photo library?

Below function would work. You can copy from here and paste there...

-(void)savePhotoToAlbum:(UIImage*)imageToSave {

    CGImageRef imageRef = imageToSave.CGImage;
    NSDictionary *metadata = [NSDictionary new]; // you can add
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

    [library writeImageToSavedPhotosAlbum:imageRef metadata:metadata completionBlock:^(NSURL *assetURL,NSError *error){
        if(error) {
            NSLog(@"Image save eror");
        }
    }];
}

Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

This problem is usually due to the map div not being rendered before the javascript runs that needs to access it.

You should put your initialization code inside an onload function or at the bottom of your HTML file, just before the tag, so the DOM is completely rendered before it executes (note that the second option is more sensitive to invalid HTML).

Note, as pointed out by matthewsheets this also could be cause by the div with that id not existing at all in your HTML (the pathological case of the div not being rendered)

Adding code sample from wf9a5m75's post to put everything in one place:

<script type="text/javascript">

function initialize() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"),
            myOptions);
}
google.maps.event.addDomListener(window, "load", initialize);

</script>

Set focus on TextBox in WPF from view model

The problem is that once the IsUserNameFocused is set to true, it will never be false. This solves it by handling the GotFocus and LostFocus for the FrameworkElement.

I was having trouble with the source code formatting so here is a link

Set CSS property in Javascript?

It is important to understand that the code bellow does not change the stylesheet, but instead changes the DOM:

document.getElementById("p2").style.color = "blue";

The DOM stores a computed value of the stylesheet element properties, and when you dynamically change an elements style using Javascript you are changing the DOM. This is important to note, and understand because the way you write your code can affect your dynamics. If you try to obtain values that were not written directly into the element itself, like so...

let elem = document.getElementById('some-element');
let propertyValue = elem.style['some-property'];

...you will return an undefined value that will be stored in the code example's 'propertyValue' variable. If you are working with getting and setting properties that were written inside a CSS style-sheet and you want a SINGLE FUNCTION that gets, as well as sets style-property-values in this situation, which is a very common situation to be in, then you have got to use JQuery.

$(selector).css(property,value)

The only downside is you got to know JQuery, but this is honestly one of the very many good reasons that every Javascript Developer should learn JQuery. If you want to get a CSS property that was computed from a style-sheet in pure JavaScript then you need to use.

function getCssProp(){
  let ele = document.getElementById("test");
  let cssProp = window.getComputedStyle(ele,null).getPropertyValue("width");
}

The downside to this method is that the getComputedValue method only gets, it does not set. Mozilla's Take on Computed Values This link goes more into depth about what I have addressed here. Hope This Helps Someone!!!

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

Base on this I was able to solve this by changing the constructor of XmlSerializer I was using instead of changing the classes.

Instead of using something like this (suggested in the other answers):

[XmlInclude(typeof(Derived))]
public class Base {}

public class Derived : Base {}

public void Serialize()
{
    TextWriter writer = new StreamWriter(SchedulePath);
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Derived>));
    xmlSerializer.Serialize(writer, data);
    writer.Close();
}

I did this:

public class Base {}

public class Derived : Base {}

public void Serialize()
{
    TextWriter writer = new StreamWriter(SchedulePath);
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Derived>), new[] { typeof(Derived) });
    xmlSerializer.Serialize(writer, data);
    writer.Close();
}

How to redirect DNS to different ports

Possible solutions:

  1. Use nginx on the server as a proxy that will listen to port A and multiplex to port B or C.

  2. If you use AWS you can use the load balancer to redirect the request to specific port based on the host.

Spring Boot Configure and Use Two DataSources

@Primary annotation when used against a method like below works good if the two data sources are on the same db location/server.

@Bean(name = "datasource1")
@ConfigurationProperties("database1.datasource")
@Primary
public DataSource dataSource(){
  return DataSourceBuilder.create().build();
}

@Bean(name = "datasource2")
@ConfigurationProperties("database2.datasource")
public DataSource dataSource2(){
  return DataSourceBuilder.create().build();
}

If the data sources are on different servers its better to use @Component along with @Primary annotation. The following code snippet works well on two different data sources at different locations

database1.datasource.url = jdbc:mysql://127.0.0.1:3306/db1
database1.datasource.username = root
database1.datasource.password = mysql
database1.datasource.driver-class-name=com.mysql.jdbc.Driver

database2.datasource1.url = jdbc:mysql://192.168.113.51:3306/db2
database2.datasource1.username = root
database2.datasource1.password = mysql
database2.datasource1.driver-class-name=com.mysql.jdbc.Driver

@Configuration
@Primary
@Component
@ComponentScan("com.db1.bean")
class DBConfiguration1{
    @Bean("db1Ds")
    @ConfigurationProperties(prefix="database1.datasource")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

}

@Configuration
@Component
@ComponentScan("com.db2.bean")
class DBConfiguration2{
    @Bean("db2Ds")
    @ConfigurationProperties(prefix="database2.datasource1")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

}

Understanding the set() function

As an unordered collection type, set([8, 1, 6]) is equivalent to set([1, 6, 8]).

While it might be nicer to display the set contents in sorted order, that would make the repr() call more expensive.

Internally, the set type is implemented using a hash table: a hash function is used to separate items into a number of buckets to reduce the number of equality operations needed to check if an item is part of the set.

To produce the repr() output it just outputs the items from each bucket in turn, which is unlikely to be the sorted order.

JRE installation directory in Windows

In the command line you can type java -version

angular 2 how to return data from subscribe

Two ways I know of:

export class SomeComponent implements OnInit
{
    public localVar:any;

    ngOnInit(){
        this.http.get(Path).map(res => res.json()).subscribe(res => this.localVar = res);
    }
}

This will assign your result into local variable once information is returned just like in a promise. Then you just do {{ localVar }}

Another Way is to get a observable as a localVariable.

export class SomeComponent
{
    public localVar:any;

    constructor()
    {
        this.localVar = this.http.get(path).map(res => res.json());
    }
}

This way you're exposing a observable at which point you can do in your html is to use AsyncPipe {{ localVar | async }}

Please try it out and let me know if it works. Also, since angular 2 is pretty new, feel free to comment if something is wrong.

Hope it helps

ASP.NET MVC: Html.EditorFor and multi-line text boxes

Another way

@Html.TextAreaFor(model => model.Comments[0].Comment)

And in your css do this

textarea
{
    font-family: inherit;
    width: 650px;
    height: 65px;
}

That DataType dealie allows carriage returns in the data, not everybody likes those.

Why is an OPTIONS request sent and can I disable it?

After spending a whole day and a half trying to work through a similar problem I found it had to do with IIS.

My Web API project was set up as follows:

// WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
    var cors = new EnableCorsAttribute("*", "*", "*");
    config.EnableCors(cors);
    //...
}

I did not have CORS specific config options in the web.config > system.webServer node like I have seen in so many posts

No CORS specific code in the global.asax or in the controller as a decorator

The problem was the app pool settings.

The managed pipeline mode was set to classic (changed it to integrated) and the Identity was set to Network Service (changed it to ApplicationPoolIdentity)

Changing those settings (and refreshing the app pool) fixed it for me.

Returning JSON from a PHP Script

In case you're doing this in WordPress, then there is a simple solution:

add_action( 'parse_request', function ($wp) {
    $data = /* Your data to serialise. */
    wp_send_json_success($data); /* Returns the data with a success flag. */
    exit(); /* Prevents more response from the server. */
})

Note that this is not in the wp_head hook, which will always return most of the head even if you exit immediately. The parse_request comes a lot earlier in the sequence.

How to get the difference between two dictionaries in Python?

def flatten_it(d):
    if isinstance(d, list) or isinstance(d, tuple):
        return tuple([flatten_it(item) for item in d])
    elif isinstance(d, dict):
        return tuple([(flatten_it(k), flatten_it(v)) for k, v in sorted(d.items())])
    else:
        return d

dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'b': 1}

print set(flatten_it(dict1)) - set(flatten_it(dict2)) # set([('b', 2), ('c', 3)])
# or 
print set(flatten_it(dict2)) - set(flatten_it(dict1)) # set([('b', 1)])

How to call a Web Service Method?

write return(secondmethod) inside of the first method

enter image description here

What are the benefits of learning Vim?

Personally,

I find many of these terminal text editors incapable at times. Would I invest time picking one up? Absolutely! I would continue to learning one along side a IDE. Of course in the end, it really comes down to preference.

How to convert file to base64 in JavaScript?

TypeScript version

const file2Base64 = (file:File):Promise<string> => {
    return new Promise<string> ((resolve,reject)=> {
         const reader = new FileReader();
         reader.readAsDataURL(file);
         reader.onload = () => resolve(reader.result.toString());
         reader.onerror = error => reject(error);
     })
    }

How to Turn Off Showing Whitespace Characters in Visual Studio IDE

In Visual Studio 2010 the key sequence CTRL+E, S will also toggle display of whitespace characters.

How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?

I verify XPath and CSS selectors using WebSync Chrome extension.

It provides possibility to verify selectors and also to generate/modify selectors by clicking on element attributes.

https://chrome.google.com/webstore/detail/natu-websync/aohpgnblncapofbobbilnlfliihianac

enter image description here

SQL Server: Invalid Column Name

with refresh table or close and open sql server this work

Resizing an iframe based on content

This is an old thread, but in 2020 it's still a relevant question. I've actually posted this answer in another old thread as well^^ (https://stackoverflow.com/a/64110252/4383587)


Just wanted to share my solution and excitement. It took me four entire days of intensive research and failure, but I think I've found a neat way of making iframes entirely responsive! Yey!

I tried a ton of different approaches... I didn't want to use a two-way communication tunnel as with postMessage because it's awkward for same-origin and complicated for cross-origin (as no admin wants to open doors and implement this on your behalf).

I've tried using MutationObservers and still needed several EventListeners (resize, click,..) to ensure that every change of the layout was handled correctly. - What if a script toggles the visibility of an element? Or what if it dynamically preloads more content on demand? - Another issue was getting an accurate height of the iframe contents from somewhere. Most people suggest using scrollHeight or offsetHeight, or combination of it by using Math.max. The problem is, that these values don't get updated until the iframe element changes its dimensions. To achieve that you could simply reset the iframe.height = 0 before grabbing the scrollHeight, but there are even more caveats to this. So, screw this.

Then, I had another idea to experiment with requestAnimationFrame to get rid of my events and observers hell. Now, I could react to every layout change immediately, but I still had no reliable source to infer the content height of the iframe from. And theeen I discovered getComputedStyle, by accident! This was an enlightenment! Everything just clicked.

Well, see the code I could eventually distill from my countless attempts.

function fit() {
    var iframes = document.querySelectorAll("iframe.gh-fit")

    for(var id = 0; id < iframes.length; id++) {
        var win = iframes[id].contentWindow
        var doc = win.document
        var html = doc.documentElement
        var body = doc.body
        var ifrm = iframes[id] // or win.frameElement

        if(body) {
            body.style.overflowX = "scroll" // scrollbar-jitter fix
            body.style.overflowY = "hidden"
        }
        if(html) {
            html.style.overflowX = "scroll" // scrollbar-jitter fix
            html.style.overflowY = "hidden"
            var style = win.getComputedStyle(html)
            ifrm.width = parseInt(style.getPropertyValue("width")) // round value
            ifrm.height = parseInt(style.getPropertyValue("height"))
        }
    }

    requestAnimationFrame(fit)
}

addEventListener("load", requestAnimationFrame.bind(this, fit))

That is it, yes! - In your HTML code write <iframe src="page.html" class="gh-fit gh-fullwidth"></iframe>. The gh-fit is a just fake CSS class, used to identify which iframe elements in your DOM should be affect by the script. The gh-fullwidth is a simple CSS class with one rule width: 100%;.

The above script automatically fetches all iframes from the DOM, that have a .gh-fit class assigned. It then grabs and uses the pre-calculated style values for width and height from document.getComputedStyle(iframe), which always contain a pixel-perfect size of that element!!! Just perfect!

Note, this solution doesn't work cross-origin (nor does any other solution, without a two-way communication strategy like IFrameResizer). JS simply can't access the DOM of an iframe, if it doesn't belong to you.

The only other cross-origin solution I can think of, is to use a proxy like https://github.com/gnuns/allorigins. But this would involve deep-copying every request you make - in other words - you 'steal' the entire page source code (to make it yours and let JS access the DOM) and you patch every link/path in this source, so that it goes through the proxy as well. The re-linking routine is a tough one, but doable.

I'll probably try myself at this cross-origin problem, but that's for another day. Enjoy the code! :)

Combine multiple JavaScript files into one JS file

I usually have it on a Makefile:

# All .js compiled into a single one.
compiled=./path/of/js/main.js

compile:
    @find ./path/of/js -type f -name "*.js" | xargs cat > $(compiled)

Then you run:

make compile

I hope it helps.

Change placeholder text

var input = document.getElementById ("IdofInput");
input.placeholder = "No need to fill this field";

You can find out more about placeholder here: http://help.dottoro.com/ljgugboo.php

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

PHP Constants Containing Arrays?

Since PHP 5.6, you can declare an array constant with const:

<?php
const DEFAULT_ROLES = array('guy', 'development team');

The short syntax works too, as you'd expect:

<?php
const DEFAULT_ROLES = ['guy', 'development team'];

If you have PHP 7, you can finally use define(), just as you had first tried:

<?php
define('DEFAULT_ROLES', array('guy', 'development team'));

What is the order of precedence for CSS?

Also important to note is that when you have two styles on an HTML element with equal precedence, the browser will give precedence to the styles that were written to the DOM last ... so if in the DOM:

<html>
<head>
<style>.container-ext { width: 100%; }</style>
<style>.container { width: 50px; }</style>
</head>
<body>
<div class="container container-ext">Hello World</div>
</body>

...the width of the div will be 50px

Uninstall mongoDB from ubuntu

use command with sudo,

sudo apt-get autoremove --purge mongodb

OR

sudo apt-get remove mongodb* --purge

It will remove complete mongodb

How can I ssh directly to a particular directory?

Based on additions to @rogeriopvl's answer, I suggest the following:

ssh -t xxx.xxx.xxx.xxx "cd /directory_wanted && bash"

Chaining commands by && will make the next command run only when the previous one was successful (as opposed to using ;, which executes commands sequentially). This is particularly useful when needing to cd to a directory performing the command.

Imagine doing the following:

/home/me$ cd /usr/share/teminal; rm -R *

The directory teminal doesn't exist, which causes you to stay in the home directory and remove all the files in there with the following command.

If you use &&:

/home/me$ cd /usr/share/teminal && rm -R *

The command will fail after not finding the directory.

What is the difference between baud rate and bit rate?

I don't understand why everyone is making this complicated (answers).

I'll just leave this here.

bit rate vs. baud rate

So above would be:

  • Signal Unit: 4 bits
  • Baud Rate [Signal Units per second]: 1000 Bd (baud)
  • Bit Rate [Baud Rate * Signal Unit]: 4000 bps (bits per second)

Bit rate and Baud rate, these two terms are often used in data communication. Bit rate is simply the number of bits (i.e., 0’s and 1’s) transmitted per unit time. While Baud rate is the number of signal units transmitted per unit time that is needed to represent those bits.

Python - 'ascii' codec can't decode byte

You use u"??".encode('utf8') to encode an unicode string. But if you want to represent "??", you should decode it. Just like:

"??".decode("utf8")

You will get what you want. Maybe you should learn more about encode & decode.

Get a list of dates between two dates

You can use MySQL's user variables like this:

SET @num = -1;
SELECT DATE_ADD( '2009-01-01', interval @num := @num+1 day) AS date_sequence, 
your_table.* FROM your_table
WHERE your_table.other_column IS NOT NULL
HAVING DATE_ADD('2009-01-01', interval @num day) <= '2009-01-13'

@num is -1 because you add to it the first time you use it. Also, you can't use "HAVING date_sequence" because that makes the user variable increment twice for each row.

scp or sftp copy multiple files with single command

In my case, I am restricted to only using the sftp command.
So, I had to use a batchfile with sftp. I created a script such as the following. This assumes you are working in the /tmp directory, and you want to put the files in the destdir_on_remote_system on the remote system. This also only works with a noninteractive login. You need to set up public/private keys so you can login without entering a password. Change as needed.

#!/bin/bash

cd /tmp
# start script with list of files to transfer
ls -1 fileset1* > batchfile1
ls -1 fileset2* >> batchfile1

sed -i -e 's/^/put /' batchfile1
echo "cd destdir_on_remote_system" > batchfile
cat batchfile1 >> batchfile
rm batchfile1

sftp -b batchfile user@host

DTO and DAO concepts and MVC

DTO is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.

  • DTO should only contain private fields for your data, getters, setters, and constructors.
  • DTO is not recommended to add business logic methods to such classes, but it is OK to add some util methods.

DAO is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).

Here is an example of how the DAO and DTO interfaces would look like:

interface PersonDTO {
    String getName();
    void setName(String name);
    //.....
}

interface PersonDAO {
    PersonDTO findById(long id);
    void save(PersonDTO person);
    //.....
}

The MVC is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.

As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.

Find all files in a folder

A lot of these answers won't actually work, having tried them myself. Give this a go:

string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo d = new DirectoryInfo(filepath);

foreach (var file in d.GetFiles("*.txt"))
{
      Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name);
}

It will move all .txt files on the desktop to the folder TextFiles.

How to find numbers from a string?

This a variant of brettdj's & pstraton post.

This will return a true Value and not give you the #NUM! error. And \D is shorthand for anything but digits. The rest is much like the others only with this minor fix.

Function StripChar(Txt As String) As Variant
With CreateObject("VBScript.RegExp")
    .Global = True
    .Pattern = "\D"
    StripChar = Val(.Replace(Txt, " "))
End With
End Function

How to calculate moving average without keeping the count and data-total?

You can simply do:

double approxRollingAverage (double avg, double new_sample) {

    avg -= avg / N;
    avg += new_sample / N;

    return avg;
}

Where N is the number of samples where you want to average over. Note that this approximation is equivalent to an exponential moving average. See: Calculate rolling / moving average in C++

Reset the database (purge all), then seed a database

If you don't feel like dropping and recreating the whole shebang just to reload your data, you could use MyModel.destroy_all (or delete_all) in the seed.db file to clean out a table before your MyModel.create!(...) statements load the data. Then, you can redo the db:seed operation over and over. (Obviously, this only affects the tables you've loaded data into, not the rest of them.)

There's a "dirty hack" at https://stackoverflow.com/a/14957893/4553442 to add a "de-seeding" operation similar to migrating up and down...

Tkinter example code for multiple windows, why won't buttons load correctly?

#!/usr/bin/env python
import Tkinter as tk

from Tkinter import *

class windowclass():

        def __init__(self,master):
                self.master = master
                self.frame = tk.Frame(master)
                self.lbl = Label(master , text = "Label")
                self.lbl.pack()
                self.btn = Button(master , text = "Button" , command = self.command )
                self.btn.pack()
                self.frame.pack()

        def command(self):
                print 'Button is pressed!'

                self.newWindow = tk.Toplevel(self.master)
                self.app = windowclass1(self.newWindow)

class windowclass1():

        def __init__(self , master):
                self.master = master
                self.frame = tk.Frame(master)
                master.title("a")
                self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25 , command = self.close_window)
                self.quitButton.pack()
                self.frame.pack()


        def close_window(self):
                self.master.destroy()


root = Tk()

root.title("window")

root.geometry("350x50")

cls = windowclass(root)

root.mainloop()

Check if element exists in jQuery

$('elemId').length doesn't work for me.

You need to put # before element id:

$('#elemId').length
---^

With vanilla JavaScript, you don't need the hash (#) e.g. document.getElementById('id_here') , however when using jQuery, you do need to put hash to target elements based on id just like CSS.

Proxy with express.js

I don't have have an express sample, but one with plain http-proxy package. A very strip down version of the proxy I used for my blog.

In short, all nodejs http proxy packages work at the http protocol level, not tcp(socket) level. This is also true for express and all express middleware. None of them can do transparent proxy, nor NAT, which means keeping incoming traffic source IP in the packet sent to backend web server.

However, web server can pickup original IP from http x-forwarded headers and add it into the log.

The xfwd: true in proxyOption enable x-forward header feature for http-proxy.

const url = require('url');
const proxy = require('http-proxy');

proxyConfig = {
    httpPort: 8888,
    proxyOptions: {
        target: {
            host: 'example.com',
            port: 80
        },
        xfwd: true // <--- This is what you are looking for.
    }
};

function startProxy() {

    proxy
        .createServer(proxyConfig.proxyOptions)
        .listen(proxyConfig.httpPort, '0.0.0.0');

}

startProxy();

Reference for X-Forwarded Header: https://en.wikipedia.org/wiki/X-Forwarded-For

Full version of my proxy: https://github.com/J-Siu/ghost-https-nodejs-proxy

node.js remove file

2019 and Node 10+ is here. Below the version using sweet async/await way.

Now no need to wrap fs.unlink into Promises nor to use additional packages (like fs-extra) anymore.

Just use native fs Promises API.

const fs = require('fs').promises;

(async () => {
  try {
    await fs.unlink('~/any/file');
  } catch (e) {
    // file doesn't exist, no permissions, etc..
    // full list of possible errors is here 
    // http://man7.org/linux/man-pages/man2/unlink.2.html#ERRORS
    console.log(e);
  }
})();

Here is fsPromises.unlink spec from Node docs.

Also please note that fs.promises API marked as experimental in Node 10.x.x (but works totally fine, though), and no longer experimental since 11.14.0.

How to "pull" from a local branch into another one?

What you are looking for is merging.

git merge master

With pull you fetch changes from a remote repository and merge them into the current branch.

How to sleep for five seconds in a batch file/cmd

An improvement of the code proposed by the user Aacini, It has resolution of hundredths of a second and does not fail when the time reaches 23:59:59,99:

for /f "tokens=1,2,3,4 delims=:," %%A in ("%TIME%") do set /a HH=%%A, MM=1%%B-100, SS=1%%C-100, CC=1%%D-100, TBASE=((HH*60+MM)*60+SS)*100+CC

:: Example delay 1 seg.
set /a TFIN=%TBASE%+100

:ESPERAR
for /f "tokens=1,2,3,4 delims=:," %%A in ("%TIME%") do set /a HH=%%A, MM=1%%B-100, SS=1%%C-100, CC=1%%D-100, TACTUAL=((HH*60+MM)*60+SS)*100+CC

if %TACTUAL% lss %TBASE% set /a TACTUAL=%TBASE%+%TACTUAL%
if %TACTUAL% lss %TFIN% goto ESPERAR

python inserting variable string as file name

Very similar to peixe.
You don't have to mention the number if the variables you add as parameters are in order of appearance

f = open('{}.csv'.format(name), 'wb')

Another option - the f-string formatting (ref):

f = open(f"{name}.csv", 'wb') 

What's a good hex editor/viewer for the Mac?

The one that I like is HexEdit Quick and easy to use

How to check if keras tensorflow backend is GPU or CPU version?

According to the documentation.

If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.

You can check what all devices are used by tensorflow by -

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

Also as suggested in this answer

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

This will print whether your tensorflow is using a CPU or a GPU backend. If you are running this command in jupyter notebook, check out the console from where you have launched the notebook.

If you are sceptic whether you have installed the tensorflow gpu version or not. You can install the gpu version via pip.

pip install tensorflow-gpu

Bootstrap 4 navbar color

I got it. This is very simple. Using the class bg you can achieve this easily.

Let me show you:

<nav class="navbar navbar-expand-lg navbar-dark navbar-full bg-primary"></nav>

This gives you the default blue navbar

If you want to change your favorite color, then simply use the style tag within the nav:

<nav class="navbar navbar-expand-lg navbar-dark navbar-full" style="background-color: #FF0000">

SSIS Connection Manager Not Storing SQL Password

Here is a simpler option that works when I encounter this.

After you create the connection, select the connection and open the Properties. In the Expressions category find Password. Re-enter the password and hit Enter. It will now be saved to the connection.

JavaScript: Object Rename Key

In case someone needs to rename a list of properties:

function renameKeys(obj, newKeys) {
  const keyValues = Object.keys(obj).map(key => {
    const newKey = newKeys[key] || key;
    return { [newKey]: obj[key] };
  });
  return Object.assign({}, ...keyValues);
}

Usage:

const obj = { a: "1", b: "2" };
const newKeys = { a: "A", c: "C" };
const renamedObj = renameKeys(obj, newKeys);
console.log(renamedObj);
// {A:"1", b:"2"}

How to specify table's height such that a vertical scroll bar appears?

to set the height of table, you need to first set css property "display: block" then you can add "width/height" properties. I find this Mozilla Article a very good resource to learn how to style tables : Link

Delete commits from a branch in Git

git reset --hard

git push origin HEAD --force

If one or more of the commits is tagged, delete the tag(s) first. Otherwise the tagged commit is not removed.

JQuery string contains check

You can use javascript's indexOf function.

_x000D_
_x000D_
var str1 = "ABCDEFGHIJKLMNOP";_x000D_
var str2 = "DEFG";_x000D_
if(str1.indexOf(str2) != -1){_x000D_
    console.log(str2 + " found");_x000D_
}
_x000D_
_x000D_
_x000D_

T-SQL stored procedure that accepts multiple Id values

You could use XML.

E.g.

declare @xmlstring as  varchar(100) 
set @xmlstring = '<args><arg value="42" /><arg2>-1</arg2></args>' 

declare @docid int 

exec sp_xml_preparedocument @docid output, @xmlstring

select  [id],parentid,nodetype,localname,[text]
from    openxml(@docid, '/args', 1) 

The command sp_xml_preparedocument is built in.

This would produce the output:

id  parentid    nodetype    localname   text
0   NULL        1           args        NULL
2   0           1           arg         NULL
3   2           2           value       NULL
5   3           3           #text       42
4   0           1           arg2        NULL
6   4           3           #text       -1

which has all (more?) of what you you need.

How do I determine whether my calculation of pi is accurate?

Since I'm the current world record holder for the most digits of pi, I'll add my two cents:

Unless you're actually setting a new world record, the common practice is just to verify the computed digits against the known values. So that's simple enough.

In fact, I have a webpage that lists snippets of digits for the purpose of verifying computations against them: http://www.numberworld.org/digits/Pi/


But when you get into world-record territory, there's nothing to compare against.

Historically, the standard approach for verifying that computed digits are correct is to recompute the digits using a second algorithm. So if either computation goes bad, the digits at the end won't match.

This does typically more than double the amount of time needed (since the second algorithm is usually slower). But it's the only way to verify the computed digits once you've wandered into the uncharted territory of never-before-computed digits and a new world record.


Back in the days where supercomputers were setting the records, two different AGM algorithms were commonly used:

These are both O(N log(N)^2) algorithms that were fairly easy to implement.

However, nowadays, things are a bit different. In the last three world records, instead of performing two computations, we performed only one computation using the fastest known formula (Chudnovsky Formula):

Enter image description here

This algorithm is much harder to implement, but it is a lot faster than the AGM algorithms.

Then we verify the binary digits using the BBP formulas for digit extraction.

Enter image description here

This formula allows you to compute arbitrary binary digits without computing all the digits before it. So it is used to verify the last few computed binary digits. Therefore it is much faster than a full computation.

The advantage of this is:

  1. Only one expensive computation is needed.

The disadvantage is:

  1. An implementation of the Bailey–Borwein–Plouffe (BBP) formula is needed.
  2. An additional step is needed to verify the radix conversion from binary to decimal.

I've glossed over some details of why verifying the last few digits implies that all the digits are correct. But it is easy to see this since any computation error will propagate to the last digits.


Now this last step (verifying the conversion) is actually fairly important. One of the previous world record holders actually called us out on this because, initially, I didn't give a sufficient description of how it worked.

So I've pulled this snippet from my blog:

N = # of decimal digits desired
p = 64-bit prime number

Enter image description here

Compute A using base 10 arithmetic and B using binary arithmetic.

Enter image description here

If A = B, then with "extremely high probability", the conversion is correct.


For further reading, see my blog post Pi - 5 Trillion Digits.

"401 Unauthorized" on a directory

  • Open IIS
  • select site where you are facing the problem

  • Select Below

enter image description here

- Right click on Anonymous Authentication and click on edit and follow below

enter image description here

What is the use of System.in.read()?

It allows you to read from the standard input (mainly, the console). This SO question may helps you.

How do I add a library path in cmake?

You had better use find_library command instead of link_directories. Concretely speaking there are two ways:

  1. designate the path within the command

    find_library(NAMES gtest PATHS path1 path2 ... pathN)

  2. set the variable CMAKE_LIBRARY_PATH

    set(CMAKE_LIBRARY_PATH path1 path2)
    find_library(NAMES gtest)

the reason is as flowings:

Note This command is rarely necessary and should be avoided where there are other choices. Prefer to pass full absolute paths to libraries where possible, since this ensures the correct library will always be linked. The find_library() command provides the full path, which can generally be used directly in calls to target_link_libraries(). Situations where a library search path may be needed include: Project generators like Xcode where the user can switch target architecture at build time, but a full path to a library cannot be used because it only provides one architecture (i.e. it is not a universal binary).

Libraries may themselves have other private library dependencies that expect to be found via RPATH mechanisms, but some linkers are not able to fully decode those paths (e.g. due to the presence of things like $ORIGIN).

If a library search path must be provided, prefer to localize the effect where possible by using the target_link_directories() command rather than link_directories(). The target-specific command can also control how the search directories propagate to other dependent targets.

auto refresh for every 5 mins

Refresh document every 300 seconds using HTML Meta tag add this inside the head tag of the page

 <meta http-equiv="refresh" content="300">

Using Script:

            setInterval(function() {
                  window.location.reload();
                }, 300000); 

Jquery checking success of ajax post

using jQuery 1.8 and above, should use the following:

var request = $.ajax({
    type: 'POST',
    url: 'mmm.php',
    data: { abc: "abcdefghijklmnopqrstuvwxyz" } })
    .done(function(data) { alert("success"+data.slice(0, 100)); })
    .fail(function() { alert("error"); })
    .always(function() { alert("complete"); });

check out the docs as @hitautodestruct stated.

Trim a string based on the string length

// this is how you shorten the length of the string with .. // add following method to your class

private String abbreviate(String s){
  if(s.length() <= 10) return s;
  return s.substring(0, 8) + ".." ;
}

Search input with an icon Bootstrap 4

in ASPX bootstrap v4.0.0, no beta (dl 21-01-2018)

<div class="input-group">
<asp:TextBox ID="txt_Product" runat="server" CssClass="form-control" placeholder="Product"></asp:TextBox>
<div class="input-group-append">
    <asp:LinkButton ID="LinkButton3" runat="server" CssClass="btn btn-outline-primary">
        <i class="ICON-copyright"></i>
    </asp:LinkButton>
</div>

How to check if an object is defined?

If a class type is not defined, you'll get a compiler error if you try to use the class, so in that sense you should have to check.

If you have an instance, and you want to ensure it's not null, simply check for null:

if (value != null)
{
    // it's not null. 
}

Memcached vs. Redis?

Here is the really great article/differences provided by Amazon

Redis is a clear winner comparing with memcached.

Only one plus point for Memcached It is multithreaded and fast. Redis has lots of great features and is very fast, but limited to one core.

Great points about Redis, which are not supported in Memcached

  • Snapshots - User can take a snapshot of Redis cache and persist on secondary storage any point of time.
  • Inbuilt support for many data structures like Set, Map, SortedSet, List, BitMaps etc.
  • Support for Lua scripting in redis

MSVCP140.dll missing

That usually means that your friend does not have the Microsoft redistributable for Visual C++. I am of course assuming you are using VC++ and not MingW or another compiler. Since your friend does not have VS installed as well there is no guarantee he has the redist installed.

VC++ Distro

DataGridView - how to set column width?

The following also can be tried:

DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells

or use the other setting options in the DataGridViewAutoSizeColumnsMode Enum

take(1) vs first()

It seems that in RxJS 5.2.0 the .first() operator has a bug,

Because of that bug .take(1) and .first() can behave quite different if you are using them with switchMap:

With take(1) you will get behavior as expected:

var x = Rx.Observable.interval(1000)
   .do( x=> console.log("One"))
   .take(1)
   .switchMap(x => Rx.Observable.interval(1000))
   .do( x=> console.log("Two"))
   .subscribe((x) => {})

// In the console you will see:
// One
// Two
// Two
// Two
// Two
// etc...

But with .first() you will get wrong behavior:

var x = Rx.Observable.interval(1000)
  .do( x=> console.log("One"))
  .first()
  .switchMap(x => Rx.Observable.interval(1000))
  .do( x=> console.log("Two"))
  .subscribe((x) => {})

// In console you will see:
// One
// One
// Two
// One
// Two
// One
// etc... 

Here's a link to codepen

Media Player called in state 0, error (-38,0)

Some times file are encoded in a way that Android can't decode. Even some mp4 files can not be played. Please try a different file format (.3gp are played most of the time) and see..

ASP.Net MVC: How to display a byte array image from model

I recommend something along these lines, even if the image lives inside of your model.

I realize you are asking for a direct way to access it right from the view and many others have answered that and told you what is wrong with that approach so this is just another way that will load the image in an async fashion for you and I think is a better approach.

Sample Model:

[Bind(Exclude = "ID")]
public class Item
{
    [Key]
    [ScaffoldColumn(false)]
    public int ID { get; set; }

    public String Name { get; set; }

    public byte[] InternalImage { get; set; } //Stored as byte array in the database.
}

Sample Method in the Controller:

public async Task<ActionResult> RenderImage(int id)
{
    Item item = await db.Items.FindAsync(id);

    byte[] photoBack = item.InternalImage;

    return File(photoBack, "image/png");
}

View

@model YourNameSpace.Models.Item

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<div>
<h4>Item</h4>
<hr />
<dl class="dl-horizontal">
    <img src="@Url.Action("RenderImage", new { id = Model.ID})" />
</dl>
<dl class="dl-horizontal">
    <dt>
        @Html.DisplayNameFor(model => model.Name)
    </dt>

    <dd>
        @Html.DisplayFor(model => model.Name)
    </dd>
</dl>
</div>

How to read an http input stream

try this code

String data = "";
InputStream iStream = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream, "utf8"));
StringBuffer sb = new StringBuffer();
String line = "";

while ((line = br.readLine()) != null) {
    sb.append(line);
}

data = sb.toString();
System.out.println(data);

Return the most recent record from ElasticSearch index

Get the Last ID using by date (with out time stamp)

Sample URL : http://localhost:9200/deal/dealsdetails/
Method : POST

Query :

{
  "fields": ["_id"],
  "sort": [{
      "created_date": {
        "order": "desc"
      }
    },
    {
      "_score": {
        "order": "desc"
      }
    }
  ],
  "size": 1
}

result:

{
  "took": 4,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 9,
    "max_score": null,
    "hits": [{
      "_index": "deal",
      "_type": "dealsdetails",
      "_id": "10",
      "_score": 1,
      "sort": [
        1478266145174,
        1
      ]
    }]
  }
}

jQuery Ajax File Upload

I have implemented a multiple file select with instant preview and upload after removing unwanted files from preview via ajax.

Detailed documentation can be found here: http://anasthecoder.blogspot.ae/2014/12/multi-file-select-preview-without.html

Demo: http://jsfiddle.net/anas/6v8Kz/7/embedded/result/

jsFiddle: http://jsfiddle.net/anas/6v8Kz/7/

Javascript:

    $(document).ready(function(){
    $('form').submit(function(ev){
        $('.overlay').show();
        $(window).scrollTop(0);
        return upload_images_selected(ev, ev.target);
    })
})
function add_new_file_uploader(addBtn) {
    var currentRow = $(addBtn).parent().parent();
    var newRow = $(currentRow).clone();
    $(newRow).find('.previewImage, .imagePreviewTable').hide();
    $(newRow).find('.removeButton').show();
    $(newRow).find('table.imagePreviewTable').find('tr').remove();
    $(newRow).find('input.multipleImageFileInput').val('');
    $(addBtn).parent().parent().parent().append(newRow);
}

function remove_file_uploader(removeBtn) {
    $(removeBtn).parent().parent().remove();
}

function show_image_preview(file_selector) {
    //files selected using current file selector
    var files = file_selector.files;
    //Container of image previews
    var imageContainer = $(file_selector).next('table.imagePreviewTable');
    //Number of images selected
    var number_of_images = files.length;
    //Build image preview row
    var imagePreviewRow = $('<tr class="imagePreviewRow_0"><td valign=top style="width: 510px;"></td>' +
        '<td valign=top><input type="button" value="X" title="Remove Image" class="removeImageButton" imageIndex="0" onclick="remove_selected_image(this)" /></td>' +
        '</tr> ');
    //Add image preview row
    $(imageContainer).html(imagePreviewRow);
    if (number_of_images > 1) {
        for (var i =1; i<number_of_images; i++) {
            /**
             *Generate class name of the respective image container appending index of selected images, 
             *sothat we can match images selected and the one which is previewed
             */
            var newImagePreviewRow = $(imagePreviewRow).clone().removeClass('imagePreviewRow_0').addClass('imagePreviewRow_'+i);
            $(newImagePreviewRow).find('input[type="button"]').attr('imageIndex', i);
            $(imageContainer).append(newImagePreviewRow);
        }
    }
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        /**
         * Allow only images
         */
        var imageType = /image.*/;
        if (!file.type.match(imageType)) {
          continue;
        }

        /**
         * Create an image dom object dynamically
         */
        var img = document.createElement("img");

        /**
         * Get preview area of the image
         */
        var preview = $(imageContainer).find('tr.imagePreviewRow_'+i).find('td:first');

        /**
         * Append preview of selected image to the corresponding container
         */
        preview.append(img); 

        /**
         * Set style of appended preview(Can be done via css also)
         */
        preview.find('img').addClass('previewImage').css({'max-width': '500px', 'max-height': '500px'});

        /**
         * Initialize file reader
         */
        var reader = new FileReader();
        /**
         * Onload event of file reader assign target image to the preview
         */
        reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
        /**
         * Initiate read
         */
        reader.readAsDataURL(file);
    }
    /**
     * Show preview
     */
    $(imageContainer).show();
}

function remove_selected_image(close_button)
{
    /**
     * Remove this image from preview
     */
    var imageIndex = $(close_button).attr('imageindex');
    $(close_button).parents('.imagePreviewRow_' + imageIndex).remove();
}

function upload_images_selected(event, formObj)
{
    event.preventDefault();
    //Get number of images
    var imageCount = $('.previewImage').length;
    //Get all multi select inputs
    var fileInputs = document.querySelectorAll('.multipleImageFileInput');
    //Url where the image is to be uploaded
    var url= "/upload-directory/";
    //Get number of inputs
    var number_of_inputs = $(fileInputs).length; 
    var inputCount = 0;

    //Iterate through each file selector input
    $(fileInputs).each(function(index, input){

        fileList = input.files;
        // Create a new FormData object.
        var formData = new FormData();
        //Extra parameters can be added to the form data object
        formData.append('bulk_upload', '1');
        formData.append('username', $('input[name="username"]').val());
        //Iterate throug each images selected by each file selector and find if the image is present in the preview
        for (var i = 0; i < fileList.length; i++) {
            if ($(input).next('.imagePreviewTable').find('.imagePreviewRow_'+i).length != 0) {
                var file = fileList[i];
                // Check the file type.
                if (!file.type.match('image.*')) {
                    continue;
                }
                // Add the file to the request.
                formData.append('image_uploader_multiple[' +(inputCount++)+ ']', file, file.name);
            }
        }
        // Set up the request.
        var xhr = new XMLHttpRequest();
        xhr.open('POST', url, true);
        xhr.onload = function () {
            if (xhr.status === 200) {
                var jsonResponse = JSON.parse(xhr.responseText);
                if (jsonResponse.status == 1) {
                    $(jsonResponse.file_info).each(function(){
                        //Iterate through response and find data corresponding to each file uploaded
                        var uploaded_file_name = this.original;
                        var saved_file_name = this.target;
                        var file_name_input = '<input type="hidden" class="image_name" name="image_names[]" value="' +saved_file_name+ '" />';
                        file_info_container.append(file_name_input);

                        imageCount--;
                    })
                    //Decrement count of inputs to find all images selected by all multi select are uploaded
                    number_of_inputs--;
                    if(number_of_inputs == 0) {
                        //All images selected by each file selector is uploaded
                        //Do necessary acteion post upload
                        $('.overlay').hide();
                    }
                } else {
                    if (typeof jsonResponse.error_field_name != 'undefined') {
                        //Do appropriate error action
                    } else {
                        alert(jsonResponse.message);
                    }
                    $('.overlay').hide();
                    event.preventDefault();
                    return false;
                }
            } else {
                /*alert('Something went wrong!');*/
                $('.overlay').hide();
                event.preventDefault();
            }
        };
        xhr.send(formData);
    })

    return false;
}

DataTable, How to conditionally delete rows

Extension method based on Linq

public static void DeleteRows(this DataTable dt, Func<DataRow, bool> predicate)
{
    foreach (var row in dt.Rows.Cast<DataRow>().Where(predicate).ToList())
        row.Delete();
}

Then use:

DataTable dt = GetSomeData();
dt.DeleteRows(r => r.Field<double>("Amount") > 123.12 && r.Field<string>("ABC") == "XYZ");

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

androidX users

Change your minSdkVersion to api level 21.

like this minSdkVersion 21 or build your app with compileSdkVersion 28 and also change targetSdkVersion to targetSdkVersion 28

and you will see v7 error will gone. After that if you face a problem with creating Toolbar or other widget. press Alt+Enter and create a method for it.

Conditionally ignoring tests in JUnit 4

A quick note: Assume.assumeTrue(condition) ignores rest of the steps but passes the test. To fail the test, use org.junit.Assert.fail() inside the conditional statement. Works same like Assume.assumeTrue() but fails the test.

How to jQuery clone() and change id?

$('#cloneDiv').click(function(){


  // get the last DIV which ID starts with ^= "klon"
  var $div = $('div[id^="klon"]:last');

  // Read the Number from that DIV's ID (i.e: 3 from "klon3")
  // And increment that number by 1
  var num = parseInt( $div.prop("id").match(/\d+/g), 10 ) +1;

  // Clone it and assign the new ID (i.e: from num 4 to ID "klon4")
  var $klon = $div.clone().prop('id', 'klon'+num );

  // Finally insert $klon wherever you want
  $div.after( $klon.text('klon'+num) );

});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

Using awk to print all columns from the nth to the last

If you want formatted text, chain your commands with echo and use $0 to print the last field.

Example:

for i in {8..11}; do
   s1="$i"
   s2="str$i"
   s3="str with spaces $i"
   echo -n "$s1 $s2" | awk '{printf "|%3d|%6s",$1,$2}'
   echo -en "$s3" | awk '{printf "|%-19s|\n", $0}'
done

Prints:

|  8|  str8|str with spaces 8  |
|  9|  str9|str with spaces 9  |
| 10| str10|str with spaces 10 |
| 11| str11|str with spaces 11 |

MySQL string replace

Yes, MySQL has a REPLACE() function:

mysql> SELECT REPLACE('www.mysql.com', 'w', 'Ww');
    -> 'WwWwWw.mysql.com'

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace

Note that it's easier if you make that an alias when using SELECT

SELECT REPLACE(string_column, 'search', 'replace') as url....

How to pass extra variables in URL with WordPress

This was the only way I could get this to work

add_action('init','add_query_args');
function add_query_args()
{ 
    add_query_arg( 'var1', 'val1' );
}

http://codex.wordpress.org/Function_Reference/add_query_arg

SQLException: No suitable driver found for jdbc:derby://localhost:1527

I solved this by adding library to the library console below my project:

  • Right click and then add library
  • add JAVA DB DRIVER.

My project is working !

Understanding REST: Verbs, error codes, and authentication

  1. Use post when you don't know how the new resource URI would look like (you create new user, application would assign the new user it's id), PUT for updating or creating resources that you know how are they going to be represented (example: PUT /myfiles/thisismynewfile.txt)
  2. return the error description in message body
  3. You can use HTTP authentication (if it's enough) Web services should be stateles

Inheritance and init method in Python

In the first situation, Num2 is extending the class Num and since you are not redefining the special method named __init__() in Num2, it gets inherited from Num.

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance.

In the second situation, since you are redefining __init__() in Num2 you need to explicitly call the one in the super class (Num) if you want to extend its behavior.

class Num2(Num):
    def __init__(self,num):
        Num.__init__(self,num)
        self.n2 = num*2

How to set timeout on python's socket recv method?

You could set timeout before receiving the response and after having received the response set it back to None:

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.settimeout(5.0)
data = sock.recv(1024)
sock.settimeout(None)

How to pass boolean values to a PowerShell script from a command prompt

You can also use 0 for False or 1 for True. It actually suggests that in the error message:

Cannot process argument transformation on parameter 'Unify'. Cannot convert value "System.String" to type "System.Boolean", parameters of this type only accept booleans or numbers, use $true, $false, 1 or 0 instead.

For more info, check out this MSDN article on Boolean Values and Operators.

Error: Cannot find module 'ejs'

The error hit me when i was working on goormIDE. This happens basically when node packages arent inside the running file. The place where app.js or home.js is executed.

add Shadow on UIView using swift 3

CODE SNIPPET:

extension UIView {

  // OUTPUT 1
  func dropShadow(scale: Bool = true) {
    layer.masksToBounds = false
    layer.shadowColor = UIColor.black.cgColor
    layer.shadowOpacity = 0.5
    layer.shadowOffset = CGSize(width: -1, height: 1)
    layer.shadowRadius = 1

    layer.shadowPath = UIBezierPath(rect: bounds).cgPath
    layer.shouldRasterize = true
    layer.rasterizationScale = scale ? UIScreen.main.scale : 1
  }

  // OUTPUT 2
  func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) {
    layer.masksToBounds = false
    layer.shadowColor = color.cgColor
    layer.shadowOpacity = opacity
    layer.shadowOffset = offSet
    layer.shadowRadius = radius

    layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
    layer.shouldRasterize = true
    layer.rasterizationScale = scale ? UIScreen.main.scale : 1
  }
}

NOTE: If you don't pass any parameter to that function, then the scale argument will be true by default. You can define a default value for any parameter in a function by assigning a value to the parameter after that parameter’s type. If a default value is defined, you can omit that parameter when calling the function.

OUTPUT 1:

shadowView.dropShadow()

enter image description here

OUTPUT 2:

shadowView.dropShadow(color: .red, opacity: 1, offSet: CGSize(width: -1, height: 1), radius: 3, scale: true)

enter image description here

layer.shouldRasterize = true will make the shadow static and cause a shadow for the initial state of the UIView. So I would recommend not to use layer.shouldRasterize = true in dynamic layouts like view inside a UITableViewCell.

How do I git rm a file without deleting it from disk?

I tried experimenting with the answers given. My personal finding came out to be:

git rm -r --cached .

And then

git add .

This seemed to make my working directory nice and clean. You can put your fileName in place of the dot.

Unix command-line JSON parser?

You could try jsawk as suggested in this answer.

Really you could whip up a quick python script to do this though.

How to remove line breaks (no characters!) from the string?

You can also use PHP trim

This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.
  • "\t" (ASCII 9 (0x09)), a tab.
  • "\n" (ASCII 10 (0x0A)), a new line (line feed).
  • "\r" (ASCII 13 (0x0D)), a carriage return.
  • "\0" (ASCII 0 (0x00)), the NUL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

How to close <img> tag properly?

<img src='stackoverflow.png' />

Works fine and closes the tag properly. Best to add the alt attribute for people that are visually impaired.

Converting dict to OrderedDict

Most of the time we go for OrderedDict when we required a custom order not a generic one like ASC etc.

Here is the proposed solution:

import collections
ship = {"NAME": "Albatross",
         "HP":50,
         "BLASTERS":13,
         "THRUSTERS":18,
         "PRICE":250}

ship = collections.OrderedDict(ship)

print ship


new_dict = collections.OrderedDict()
new_dict["NAME"]=ship["NAME"]
new_dict["HP"]=ship["HP"]
new_dict["BLASTERS"]=ship["BLASTERS"]
new_dict["THRUSTERS"]=ship["THRUSTERS"]
new_dict["PRICE"]=ship["PRICE"]


print new_dict

This will be output:

OrderedDict([('PRICE', 250), ('HP', 50), ('NAME', 'Albatross'), ('BLASTERS', 13), ('THRUSTERS', 18)])
OrderedDict([('NAME', 'Albatross'), ('HP', 50), ('BLASTERS', 13), ('THRUSTERS', 18), ('PRICE', 250)])

Note: The new sorted dictionaries maintain their sort order when entries are deleted. But when new keys are added, the keys are appended to the end and the sort is not maintained.(official doc)

How do I detect if Python is running as a 64-bit application?

While it may work on some platforms, be aware that platform.architecture is not always a reliable way to determine whether python is running in 32-bit or 64-bit. In particular, on some OS X multi-architecture builds, the same executable file may be capable of running in either mode, as the example below demonstrates. The quickest safe multi-platform approach is to test sys.maxsize on Python 2.6, 2.7, Python 3.x.

$ arch -i386 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 2147483647)
>>> ^D
$ arch -x86_64 /usr/local/bin/python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import platform, sys
>>> platform.architecture(), sys.maxsize
(('64bit', ''), 9223372036854775807)

Artificially create a connection timeout error

There are services available which allow you to artificially create origin timeouts by calling an API where you specify how long the server will take to respond. Server Timeout on macgyver is an example of such a service.

For example if you wanted to test a request that takes 15 seconds to respond you would simply make a post request to the macgyver API.

JSON Payload:

{
    "timeout_length": 15000
}

API Response (After 15 seconds):

{
    "response": "ok"
}

Server Timeout program on macgyver
https://askmacgyver.com/explore/program/server-timeout/3U4s6g6u

How to generate a simple popup using jQuery

Here is a very simple popup:

<!DOCTYPE html>
<html>
    <head>
        <style>
            #modal {
                position:absolute;
                background:gray;
                padding:8px;
            }

            #content {
                background:white;
                padding:20px;
            }

            #close {
                position:absolute;
                background:url(close.png);
                width:24px;
                height:27px;
                top:-7px;
                right:-7px;
            }
        </style>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script>
            var modal = (function(){
                // Generate the HTML and add it to the document
                $modal = $('<div id="modal"></div>');
                $content = $('<div id="content"></div>');
                $close = $('<a id="close" href="#"></a>');

                $modal.hide();
                $modal.append($content, $close);

                $(document).ready(function(){
                    $('body').append($modal);                       
                });

                $close.click(function(e){
                    e.preventDefault();
                    $modal.hide();
                    $content.empty();
                });
                // Open the modal
                return function (content) {
                    $content.html(content);
                    // Center the modal in the viewport
                    $modal.css({
                        top: ($(window).height() - $modal.outerHeight()) / 2, 
                        left: ($(window).width() - $modal.outerWidth()) / 2
                    });
                    $modal.show();
                };
            }());

            // Wait until the DOM has loaded before querying the document
            $(document).ready(function(){
                $('a#popup').click(function(e){
                    modal("<p>This is popup's content.</p>");
                    e.preventDefault();
                });
            });
        </script>
    </head>
    <body>
        <a id='popup' href='#'>Simple popup</a>
    </body>
</html>

More flexible solution can be found in this tutorial: http://www.jacklmoore.com/notes/jquery-modal-tutorial/ Here's close.png for the sample.

How to import an existing directory into Eclipse?

For Spring Tool Suite I do:

File -> Open projects from File System

Posting JSON Data to ASP.NET MVC

I see everyone here "took the long route!". As long as you are using MVC, I strongly recommend you to use the easiest method over all which is Newtonsoft.JSON... Also If you dont wanna use libraries check the answer links below. I took a good research time for this to solve the issue for my self and these are the solutions I found;

First implement the Newtonsoft.Json:

using Newtonsoft.Json;

Prepare your Ajax request:

$.ajax({
    dataType: "json",
    contentType: "application/json",            
    type: 'POST',
    url: '/Controller/Action',
    data: { 'items': JSON.stringify(lineItems), 'id': documentId }
});

Then go for your result class:

public ActionResult SaveData(string incoming, int documentId){
    // DeSerialize into your Model as your Model Array
    LineItem[] jsr = JsonConvert.DeserializeObject<LineItem[]>(Temp);
    foreach(LineItem item in jsr){
        // save some stuff
    }
    return Json(new { success = true, message = "Some message" });
}

See the trick up there? Instead of using JsonResult I used regular ActionResult with a string which includes json string. Then deserialized into my Model so I can use this in any action method I have.

Plus sides of this method is :

  1. Easier to pass between actions,
  2. Lesser and more clear usage of code,
  3. No need to change your model,
  4. Simple implementation with JSON.stringify(Model)
  5. Passing only string

Down sides of this method is :

  1. Passing only string
  2. Deserialization process

Also check these questions and answers which are really helpfull:

https://stackoverflow.com/a/45682516/861019

another method :

https://stackoverflow.com/a/31656160/861019

and another method :

https://stackoverflow.com/a/50787450/861019

Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used

    ActiveWorkbook.Close False

How to fix '.' is not an internal or external command error

I got exactly the same error in Windows 8 while trying to export decision tree digraph using tree.export_graphviz! Then I installed GraphViz from this link. And then I followed the below steps which resolved my issue:

  • Right click on My PC >> click on "Change Settings" under "Computer name, domain, and workgroup settings"
  • It will open the System Properties window; Goto 'Advanced' tab >> click on 'Environment Variables' >> Under "System Variables" >> select 'Path' and click on 'Edit' >> In 'Variable Value' field, put a semicolon (;) at the end of existing value and then include the path of its installation folder (e.g. ;C:\Program Files (x86)\Graphviz2.38\bin) >> Click on 'Ok' >> 'Ok' >> 'Ok'
  • Restart your PC as environment variables are changed

Location Services not working in iOS 8

To Access User Location in iOS 8 you will have to add,

NSLocationAlwaysUsageDescription in the Info.plist 

This will ask the user for the permission to get their current location.

Command not found when using sudo

Ok this is my solution: in ~/.bash_aliases just add the following:

# ADDS MY PATH WHEN SET AS ROOT
if [ $(id -u) = "0" ]; then
   export PATH=$PATH:/home/your_user/bin 
fi

Voila! Now you can execute your own scripts with sudo or set as ROOT without having to do an export PATH=$PATH:/home/your_user/bin everytime.

Notice that I need to be explicit when adding my PATH since HOME for superuser is /root

How do I install Maven with Yum?

You can add maven to the yum libraries like this:

wget http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo

Now you can install maven like this:

yum install apache-maven

Once done, maven 3 will be installed and mvn -version will show you which version you've got - I had 3.2.1.

This worked perfectly for me on CentOS 6 with one exception. It installed OpenJDK 1.6 and made it the default Java version, even though I'd already manually installed JDK 8 (possibly because I'd manually installed it). To change it back use alternatives:

alternatives --config java
alternatives --config javac

and choose the correct version.

Postgres: SQL to list table foreign keys

Here is a solution by Andreas Joseph Krogh from the PostgreSQL mailing list: http://www.postgresql.org/message-id/[email protected]

SELECT source_table::regclass, source_attr.attname AS source_column,
    target_table::regclass, target_attr.attname AS target_column
FROM pg_attribute target_attr, pg_attribute source_attr,
  (SELECT source_table, target_table, source_constraints[i] source_constraints, target_constraints[i] AS target_constraints
   FROM
     (SELECT conrelid as source_table, confrelid AS target_table, conkey AS source_constraints, confkey AS target_constraints,
       generate_series(1, array_upper(conkey, 1)) AS i
      FROM pg_constraint
      WHERE contype = 'f'
     ) query1
  ) query2
WHERE target_attr.attnum = target_constraints AND target_attr.attrelid = target_table AND
      source_attr.attnum = source_constraints AND source_attr.attrelid = source_table;

This solution handles foreign keys that reference multiple columns, and avoids duplicates (which some of the other answers fail to do). The only thing I changed were the variable names.

Here is an example that returns all employee columns that reference the permission table:

SELECT source_column
FROM foreign_keys
WHERE source_table = 'employee'::regclass AND target_table = 'permission'::regclass;

Calling a javascript function recursively

Here's one very simple example:

var counter = 0;

function getSlug(tokens) {
    var slug = '';

    if (!!tokens.length) {
        slug = tokens.shift();
        slug = slug.toLowerCase();
        slug += getSlug(tokens);

        counter += 1;
        console.log('THE SLUG ELEMENT IS: %s, counter is: %s', slug, counter);
    }

    return slug;
}

var mySlug = getSlug(['This', 'Is', 'My', 'Slug']);
console.log('THE SLUG IS: %s', mySlug);

Notice that the counter counts "backwards" in regards to what slug's value is. This is because of the position at which we are logging these values, as the function recurs before logging -- so, we essentially keep nesting deeper and deeper into the call-stack before logging takes place.

Once the recursion meets the final call-stack item, it trampolines "out" of the function calls, whereas, the first increment of counter occurs inside of the last nested call.

I know this is not a "fix" on the Questioner's code, but given the title I thought I'd generically exemplify Recursion for a better understanding of recursion, outright.

How to convert String to DOM Document object in java?

Either escape the double quotes with \

String xmlString = "<element attribname=\"value\" attribname1=\"value1\"> pcdata</element>"

or use single quotes instead

String xmlString = "<element attribname='value' attribname1='value1'> pcdata</element>"

How to export and import a .sql file from command line with options?

mysqldump will not dump database events, triggers and routines unless explicitly stated when dumping individual databases;

mysqldump -uuser -p db_name --events --triggers --routines > db_name.sql

creating a random number using MYSQL

these both are working nicely:

select round(<maxNumber>*rand())

FLOOR(RAND() * (<max> - <min> + 1)) + <min> // generates a number
between <min> and <max> inclusive.

What is sys.maxint in Python 3?

If you are looking for a number that is bigger than all others:

Method 1:

float('inf')

Method 2:

import sys
max = sys.maxsize

If you are looking for a number that is smaller than all others:

Method 1:

float('-inf')

Method 2:

import sys
min = -sys.maxsize - 1

Method 1 works in both Python2 and Python3. Method 2 works in Python3. I have not tried Method 2 in Python2.

How to make a div fill a remaining horizontal space?

I ran into this same problem trying to layout some jqueryUI controls. Although the common philosophy now is "use DIV instead of TABLE", I found in my case using TABLE worked much better. In particular, if you need to have straightforward alignment within the two elements (e.g., vertical centering, horizontal centering, etc.) the options available with TABLE give simple, intuitive controls for this.

Here's my solution:

<html>
<head>
  <title>Sample solution for fixed left, variable right layout</title>
  <style type="text/css">
    #controls {
      width: 100%;
    }
    #RightSide {
      background-color:green;
    }
  </style>
</head>

<body>
<div id="controls">
  <table border="0" cellspacing="2" cellpadding="0">
    <TR>
      <TD>
        <button>
FixedWidth
        </button>
      </TD>
      <TD width="99%" ALIGN="CENTER">
        <div id="RightSide">Right</div>
      </TD>
    </TR>
  </table>
</div>
</body>
</html>

HashSet vs. List performance

One factor your not taking into account is the robustness of the GetHashcode() function. With a perfect hash function the HashSet will clearly have better searching performance. But as the hash function diminishes so will the HashSet search time.

No module named serial

You must pip install pyserial first.

What is the most accurate way to retrieve a user's correct IP address in PHP?

Just another clean way:

  function validateIp($var_ip){
    $ip = trim($var_ip);

    return (!empty($ip) &&
            $ip != '::1' &&
            $ip != '127.0.0.1' &&
            filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false)
            ? $ip : false;
  }

  function getClientIp() {
    $ip = @$this->validateIp($_SERVER['HTTP_CLIENT_IP']) ?:
          @$this->validateIp($_SERVER['HTTP_X_FORWARDED_FOR']) ?:
          @$this->validateIp($_SERVER['HTTP_X_FORWARDED']) ?:
          @$this->validateIp($_SERVER['HTTP_FORWARDED_FOR']) ?:
          @$this->validateIp($_SERVER['HTTP_FORWARDED']) ?:
          @$this->validateIp($_SERVER['REMOTE_ADDR']) ?:
          'LOCAL OR UNKNOWN ACCESS';

    return $ip;
  }

Get exit code for command in bash/ksh

Below is the fixed code:

#!/bin/ksh
safeRunCommand() {
  typeset cmnd="$*"
  typeset ret_code

  echo cmnd=$cmnd
  eval $cmnd
  ret_code=$?
  if [ $ret_code != 0 ]; then
    printf "Error : [%d] when executing command: '$cmnd'" $ret_code
    exit $ret_code
  fi
}

command="ls -l | grep p"
safeRunCommand "$command"

Now if you look into this code few things that I changed are:

  • use of typeset is not necessary but a good practice. It make cmnd and ret_code local to safeRunCommand
  • use of ret_code is not necessary but a good practice to store return code in some variable (and store it ASAP) so that you can use it later like I did in printf "Error : [%d] when executing command: '$command'" $ret_code
  • pass the command with quotes surrounding the command like safeRunCommand "$command". If you dont then cmnd will get only the value ls and not ls -l. And it is even more important if your command contains pipes.
  • you can use typeset cmnd="$*" instead of typeset cmnd="$1" if you want to keep the spaces. You can try with both depending upon how complex is your command argument.
  • eval is used to evaluate so that command containing pipes can work fine

NOTE: Do remember some commands give 1 as return code even though there is no error like grep. If grep found something it will return 0 else 1.

I had tested with KSH/BASH. And it worked fine. Let me know if u face issues running this.

Consider defining a bean of type 'service' in your configuration [Spring boot]

I solved this issue by creating a bean for my service in SpringConfig.java file. Please check the below code,

@Configuration 
public class SpringConfig { 

@Bean
public TransactionService transactionService() {
    return new TransactionServiceImpl();
}

}

The path of this file is shown in the below image, Spring boot application folder structure

Using Mockito to stub and execute methods for testing

You are confusing a Mock with a Spy.

In a mock all methods are stubbed and return "smart return types". This means that calling any method on a mocked class will do nothing unless you specify behaviour.

In a spy the original functionality of the class is still there but you can validate method invocations in a spy and also override method behaviour.

What you want is

MyProcessingAgent mockMyAgent = Mockito.spy(MyProcessingAgent.class);

A quick example:

static class TestClass {

    public String getThing() {
        return "Thing";
    }

    public String getOtherThing() {
        return getThing();
    }
}

public static void main(String[] args) {
    final TestClass testClass = Mockito.spy(new TestClass());
    Mockito.when(testClass.getThing()).thenReturn("Some Other thing");
    System.out.println(testClass.getOtherThing());
}

Output is:

Some Other thing

NB: You should really try to mock the dependencies for the class being tested not the class itself.

How do I convert a factor into date format?

You were close. format= needs to be added to the as.Date call:

mydate <- factor("1/15/2006 0:00:00")
as.Date(mydate, format = "%m/%d/%Y")
## [1] "2006-01-15"

How does the "final" keyword in Java work? (I can still modify an object.)

"A final variable can only be assigned once"

*Reflection* - "wowo wait, hold my beer".


Freeze of final fields happen in two scenarios:

  • End of constructor.
  • When reflection sets the field's value. (as many times as it wants to)

Let's break the law

public class HoldMyBeer 
{
    final int notSoFinal;
    
    public HoldMyBeer()
    {
       notSoFinal = 1;
    }

    static void holdIt(HoldMyBeer beer, int yetAnotherFinalValue) throws Exception
    {
       Class<HoldMyBeer> cl = HoldMyBeer.class;
       Field field = cl.getDeclaredField("notSoFinal");
       field.setAccessible(true);
       field.set(beer, yetAnotherFinalValue);
    }

    public static void main(String[] args) throws Exception 
    {
       HoldMyBeer beer = new HoldMyBeer();
       System.out.println(beer.notSoFinal);
       holdIt(beer, 50);
       System.out.println(beer.notSoFinal);
       holdIt(beer, 100);
       System.out.println(beer.notSoFinal);
       holdIt(beer, 666);
       System.out.println(beer.notSoFinal);
       holdIt(beer, 8888);
       System.out.println(beer.notSoFinal);
    }    
}

Output:

1
50
100
666
8888

The "final" field has been assigned 5 different "final" values (note the quotes). And it could keep being assigned different values over and over...

Why? Because reflection is like Chuck Norris, and if it wants to change the value of an initialized final field, it does. Some say he himself is the one that pushes the new values into the stack :

Code:
   7: astore_1
  11: aload_1
  12: getfield                
  18: aload_1
  19: bipush        50        //wait what
  27: aload_1
  28: getfield                
  34: aload_1
  35: bipush        100       //come on...
  43: aload_1
  44: getfield                
  50: aload_1
  51: sipush        666      //...you were supposed to be final...
  60: aload_1
  61: getfield                
  67: aload_1
  68: sipush        8888     //ok i'm out whatever dude
  77: aload_1
  78: getfield                

When to use HashMap over LinkedList or ArrayList and vice-versa

Lists and Maps are different data structures. Maps are used for when you want to associate a key with a value and Lists are an ordered collection.

Map is an interface in the Java Collection Framework and a HashMap is one implementation of the Map interface. HashMap are efficient for locating a value based on a key and inserting and deleting values based on a key. The entries of a HashMap are not ordered.

ArrayList and LinkedList are an implementation of the List interface. LinkedList provides sequential access and is generally more efficient at inserting and deleting elements in the list, however, it is it less efficient at accessing elements in a list. ArrayList provides random access and is more efficient at accessing elements but is generally slower at inserting and deleting elements.

How do I escape double and single quotes in sed?

It's hard to escape a single quote within single quotes. Try this:

sed "s@['\"]http://www.\([^.]\+).com['\"]@URL_\U\1@g" 

Example:

$ sed "s@['\"]http://www.\([^.]\+\).com['\"]@URL_\U\1@g" <<END
this is "http://www.fubar.com" and 'http://www.example.com' here
END

produces

this is URL_FUBAR and URL_EXAMPLE here

jQuery get selected option value (not the text, but the attribute 'value')

$('select').change(function() {
    console.log($(this).val())
});?

jsFiddle example

.val() will get the value.

How can I change a button's color on hover?

Seems your selector is wrong, try using:

a.button:hover{
     background: #383;
}

Your code

a.button a:hover

Means it is going to search for an a element inside a with class button.

How to determine if Javascript array contains an object with an attribute that equals a given value?

You can use lodash. If lodash library is too heavy for your application consider chunking out unnecessary function not used.

let newArray = filter(_this.props.ArrayOne, function(item) {
                    return find(_this.props.ArrayTwo, {"speciesId": item.speciesId});
                });

This is just one way to do this. Another one can be:

var newArray=  [];
     _.filter(ArrayOne, function(item) {
                        return AllSpecies.forEach(function(cItem){
                            if (cItem.speciesId == item.speciesId){
                            newArray.push(item);
                          }
                        }) 
                    });

console.log(arr);

The above example can also be rewritten without using any libraries like:

var newArray=  [];
ArrayOne.filter(function(item) {
                return ArrayTwo.forEach(function(cItem){
                    if (cItem.speciesId == item.speciesId){
                    newArray.push(item);
                  }
                }) 
            });
console.log(arr);

Hope my answer helps.

Example of Named Pipes

Linux dotnet core doesn't support namedpipes!

Try TcpListener if you deploy to Linux

This NamedPipe Client/Server code round trips a byte to a server.

  • Client writes byte
  • Server reads byte
  • Server writes byte
  • Client reads byte

DotNet Core 2.0 Server ConsoleApp

using System;
using System.IO.Pipes;
using System.Threading.Tasks;

namespace Server
{
    class Program
    {
        static void Main(string[] args)
        {
            var server = new NamedPipeServerStream("A", PipeDirection.InOut);
            server.WaitForConnection();

            for (int i =0; i < 10000; i++)
            {
                var b = new byte[1];
                server.Read(b, 0, 1); 
                Console.WriteLine("Read Byte:" + b[0]);
                server.Write(b, 0, 1);
            }
        }
    }
}

DotNet Core 2.0 Client ConsoleApp

using System;
using System.IO.Pipes;
using System.Threading.Tasks;

namespace Client
{
    class Program
    {
        public static int threadcounter = 1;
        public static NamedPipeClientStream client;

        static void Main(string[] args)
        {
            client = new NamedPipeClientStream(".", "A", PipeDirection.InOut, PipeOptions.Asynchronous);
            client.Connect();

            var t1 = new System.Threading.Thread(StartSend);
            var t2 = new System.Threading.Thread(StartSend);

            t1.Start();
            t2.Start(); 
        }

        public static void StartSend()
        {
            int thisThread = threadcounter;
            threadcounter++;

            StartReadingAsync(client);

            for (int i = 0; i < 10000; i++)
            {
                var buf = new byte[1];
                buf[0] = (byte)i;
                client.WriteAsync(buf, 0, 1);

                Console.WriteLine($@"Thread{thisThread} Wrote: {buf[0]}");
            }
        }

        public static async Task StartReadingAsync(NamedPipeClientStream pipe)
        {
            var bufferLength = 1; 
            byte[] pBuffer = new byte[bufferLength];

            await pipe.ReadAsync(pBuffer, 0, bufferLength).ContinueWith(async c =>
            {
                Console.WriteLine($@"read data {pBuffer[0]}");
                await StartReadingAsync(pipe); // read the next data <-- 
            });
        }
    }
}

What's the difference between '$(this)' and 'this'?

Yes, you need $(this) for jQuery functions, but when you want to access basic javascript methods of the element that don't use jQuery, you can just use this.

How do I initialize a byte array in Java?

You can use this utility function:

public static byte[] fromHexString(String src) {
    byte[] biBytes = new BigInteger("10" + src.replaceAll("\\s", ""), 16).toByteArray();
    return Arrays.copyOfRange(biBytes, 1, biBytes.length);
}

Unlike variants of Denys Séguret and stefan.schwetschke, it allows inserting separator symbols (spaces, tabs, etc.) into the input string, making it more readable.

Example of usage:

private static final byte[] CDRIVES
    = fromHexString("e0 4f d0 20 ea 3a 69 10 a2 d8 08 00 2b 30 30 9d");
private static final byte[] CMYDOCS
    = fromHexString("BA8A0D4525ADD01198A80800361B1103");
private static final byte[] IEFRAME
    = fromHexString("80531c87 a0426910 a2ea0800 2b30309d");

Remove last character from C++ string

That's all you need:

#include <string>  //string::pop_back & string::empty

if (!st.empty())
    st.pop_back();

How to write inline if statement for print?

This can be done with string formatting. It works with the % notation as well as .format() and f-strings (new to 3.6)

print '%s' % (a if b else "")

or

print '{}'.format(a if b else "")

or

print(f'{a if b else ""}')

How do I convert a datetime to date?

You can convert a datetime object to a date with the date() method of the date time object, as follows:

<datetime_object>.date()

When is a language considered a scripting language?

An important difference is strong typing (versus weak typing). Scripting languages are often weakly typed, making it possible to write small programs more rapidly. For large programs this is a disadvantage, as it inhibits the compiler/interpreter to find certain bugs autonomously, making it very hard to refactor code.

What is the proper declaration of main in C++?

The two valid mains are int main() and int main(int, char*[]). Any thing else may or may not compile. If main doesn't explicitly return a value, 0 is implicitly returned.

How do I convert a byte array to Base64 in Java?

Use:

byte[] data = Base64.encode(base64str);

Encoding converts to Base64

You would need to reference commons codec from your project in order for that code to work.

For java8:

import java.util.Base64

Prevent HTML5 video from being downloaded (right-click saved)?

PHP sends the html5 video tag together with a session where the key is a random string and the value is the filename.

ini_set('session.use_cookies',1);
session_start();
$ogv=uniqid(); 
$_SESSION[$ogv]='myVideo.ogv';
$webm=uniqid(); 
$_SESSION[$webm]='myVideo.webm';
echo '<video autoplay="autoplay">'
    .'<source src="video.php?video='.$ogv.' type="video/ogg">'
    .'<source src="video.php?video='.$webm.' type="video/webm">'
    .'</video>'; 

Now PHP is asked to send the video. PHP recovers the filename; deletes the session and sends the video instantly. Additionally all the 'no cache' and mime-type headers must be present.

ini_set('session.use_cookies',1);
session_start();
$file='myhiddenvideos/'.$_SESSION[$_GET['video']];
$_SESSION=array();
$params = session_get_cookie_params();
setcookie(session_name(),'', time()-42000,$params["path"],$params["domain"],
                                         $params["secure"], $params["httponly"]);
if(!file_exists($file) or $file==='' or !is_readable($file)){
  header('HTTP/1.1 404 File not found',true);
  exit;
  }
readfile($file);
exit:

Now if the user copy the url in a new tab or use the context menu he will have no luck.

How to convert float to int with Java

If you want to convert a float value into an integer value, you have several ways to do it that depends on how do you want to round the float value.

First way is floor rounding the float value:

float myFloat = 3.14f;
int myInteger = (int)myFloat;

The output of this code will be 3, even if the myFloat value is closer to 4.

The second way is ceil rounding the float value:

float myFloat = 3.14f;
int myInteger = Math.ceil(myFloat);

The output of this code will be 4, because the rounding mode is always looking for the highest value.

How do you format a Date/Time in TypeScript?

One more to add @kamalakar's answer, need to import the same in app.module and add DateFormatPipe to providers.

    import {DateFormatPipe} from './DateFormatPipe';
    @NgModule
    ({ declarations: [],  
        imports: [],
        providers: [DateFormatPipe]
    })

Ant build failed: "Target "build..xml" does not exist"

since your ant file's name is build.xml, you should just type ant without ant build.xml. that is: > ant [enter]

Android: How to overlay a bitmap and draw over a bitmap?

public static Bitmap overlayBitmapToCenter(Bitmap bitmap1, Bitmap bitmap2) {
    int bitmap1Width = bitmap1.getWidth();
    int bitmap1Height = bitmap1.getHeight();
    int bitmap2Width = bitmap2.getWidth();
    int bitmap2Height = bitmap2.getHeight();

    float marginLeft = (float) (bitmap1Width * 0.5 - bitmap2Width * 0.5);
    float marginTop = (float) (bitmap1Height * 0.5 - bitmap2Height * 0.5);

    Bitmap overlayBitmap = Bitmap.createBitmap(bitmap1Width, bitmap1Height, bitmap1.getConfig());
    Canvas canvas = new Canvas(overlayBitmap);
    canvas.drawBitmap(bitmap1, new Matrix(), null);
    canvas.drawBitmap(bitmap2, marginLeft, marginTop, null);
    return overlayBitmap;
}

how to use "AND", "OR" for RewriteCond on Apache?

Having trouble wrapping my head around this.

Have a rewrite rule with four conditions.
The first three conditions A, B, C are to be AND which is then OR with D

RewriteCond A       true
RewriteCond B       false
RewriteCond C [OR]  true
RewriteCond D       true
RewriteRule ...

But that seems to be an expression of A and B and (C or D) = false (don't rewrite)

How can I get to the desired expression? (A and B and C) or D = true (rewrite)

Preferably without using the additional steps of setting environment variables.

HELP!!!

JOptionPane - input dialog box program

import java.util.SortedSet;
import java.util.TreeSet;

import javax.swing.JOptionPane;
import javax.swing.JFrame;

public class Average {

    public static void main(String [] args) {

        String test1= JOptionPane.showInputDialog("Please input mark for test 1: ");

        String test2= JOptionPane.showInputDialog("Please input mark for test 2: ");

        String test3= JOptionPane.showInputDialog("Please input mark for test 3: ");

        int int1 = Integer.parseInt(test1);
        int int2 = Integer.parseInt(test2);
        int int3 = Integer.parseInt(test3);

        SortedSet<Integer> set = new TreeSet<>();
        set.add(int1);
        set.add(int2);
        set.add(int3);

        Integer [] intArray = set.toArray(new Integer[3]);
        JFrame frame = new JFrame();
        JOptionPane.showInternalMessageDialog(frame.getContentPane(), String.format("Result %f", (intArray[1] + intArray[2]) / 2.0));

    }

}

Get position/offset of element relative to a parent container?

in pure js just use offsetLeft and offsetTop properties.
Example fiddle: http://jsfiddle.net/WKZ8P/

_x000D_
_x000D_
var elm = document.querySelector('span');_x000D_
console.log(elm.offsetLeft, elm.offsetTop);
_x000D_
p   { position:relative; left:10px; top:85px; border:1px solid blue; }_x000D_
span{ position:relative; left:30px; top:35px; border:1px solid red; }
_x000D_
<p>_x000D_
    <span>paragraph</span>_x000D_
</p>
_x000D_
_x000D_
_x000D_

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

"Case" can return single value only, but you can use complex type:

create type foo as (a int, b text);
select (case 1 when 1 then (1,'qq')::foo else (2,'ww')::foo end).*;

Android: Quit application when press back button

Try this:

Intent intent = new Intent(Intent.ACTION_MAIN);
          intent.addCategory(Intent.CATEGORY_HOME);
          intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//***Change Here***
          startActivity(intent);
          finish();
          System.exit(0);

Grep regex NOT containing string

grep matches, grep -v does the inverse. If you need to "match A but not B" you usually use pipes:

grep "${PATT}" file | grep -v "${NOTPATT}"

Clone an image in cv2 python

The first answer is correct but you say that you are using cv2 which inherently uses numpy arrays. So, to make a complete different copy of say "myImage":

newImage = myImage.copy()

The above is enough. No need to import numpy.

How to launch PowerShell (not a script) from the command line

Set the default console colors and fonts:

http://poshcode.org/2220
From Windows PowerShell Cookbook (O'Reilly)
by Lee Holmes (http://www.leeholmes.com/guide)

Set-StrictMode -Version Latest

Push-Location
Set-Location HKCU:\Console
New-Item '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
Set-Location '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'

New-ItemProperty . ColorTable00 -type DWORD -value 0x00562401
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f0edee
New-ItemProperty . FaceName -type STRING -value "Lucida Console"
New-ItemProperty . FontFamily -type DWORD -value 0x00000036
New-ItemProperty . FontSize -type DWORD -value 0x000c0000
New-ItemProperty . FontWeight -type DWORD -value 0x00000190
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x0bb80078
New-ItemProperty . WindowSize -type DWORD -value 0x00320078
Pop-Location

How do I do multiple CASE WHEN conditions using SQL Server 2008?

This can be an efficient way of performing different tests on a single statement

select
case colour_txt 
  when 'red' then 5 
  when 'green' then 4 
  when 'orange' then 3
else 0 
end as Pass_Flag

this only works on equality comparisons!

Using String Format to show decimal up to 2 places or simple integer

A recent project has a similar requirement. I wrote this decimal extension method, which uses the currency ("C") Format Specifier. In addition to removing zeros, it also has options for decimal digits precision, currency symbol, separator and culture.

public static DecimalExtension{

     public static string ToCurrency(this decimal val, 
                                     int precision = 2, 
                                     bool currencySymbol = false, 
                                     bool separator = false, 
                                     CultureInfo culture = null)
      {     
         if(culture == null) culture = new CultureInfo("en-US");
                                                   
         NumberFormatInfo nfi = culture.NumberFormat;
         nfi.CurrencyDecimalDigits = precision;
            
         string zeros = new String('0', precision);       
                    
         //Remove zeros
         var result = val.ToString("C",fi).Replace(nfi.CurrencyDecimalSeparator + zeros,"");
                     
         if(!separator) result = result.Replace(nfi.CurrencyGroupSeparator,"");
                    
         return currencySymbol? result: result.Replace(nfi.CurrencySymbol,"");      
        }   
}

Examples:

decimal Total = 123.00M;
Console.WriteLine(Total.ToCurrency());  
//output: 123

decimal Total = 1123.12M;
Console.WriteLine(Total.ToCurrency()); 
//Output:  1123.12

Console.WriteLine(Total.ToCurrency(4));
//Output:  1123.1200

Console.WriteLine(Total.ToCurrency(2,true,true));
//output:  $1,123.12
 
CultureInfo culture = new CultureInfo("pt-BR")  //Brazil
Console.WriteLine(Total.ToCurrency(2,true,true, culture));
//output:  R$ 1.123,12

Python not working in command prompt?

I am probably the most novice user here, I have spent six hours just to run python in the command line in Windows 8. Once I installed the 64-bit version, then I uninstalled it and replaced it with 32-bit version. Then, I tried most suggestions here, especially by defining path in the system variables, but still it didn't work.

Then I realised when I typed in the command line: echo %path%

The path still was not directed to C:\python27. So I simply restarted the computer, and now it works.

How to represent the double quotes character (") in regex?

Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex.

However, because java uses double quotes to delimit String constants, if you want to create a string in java with a double quote in it, you must escape them.

This code will test if your String matches:

if (str.matches("\".*\"")) {
    // this string starts and end with a double quote
}

Note that you don't need to add start and end of input markers (^ and $) in the regex, because matches() requires that the whole input be matched to return true - ^ and $ are implied.

PHP calculate age

If you want to only get fullyears as age, there is a supersimple way on doing that. treat dates formatted as 'YYYYMMDD' as numbers and substract them. After that cancel out the MMDD part by dividing the result with 10000 and floor it down. Simple and never fails, even takes to account leapyears and your current server time ;)

Since birthdays or mostly provided by full dates on birth location and they are relevant to CURRENT LOCAL TIME (where the age check is actually done).

$now = date['Ymd'];
$birthday = '19780917'; #september 17th, 1978
$age = floor(($now-$birthday)/10000);

so if you want to check if someone is 18 or 21 or below 100 on your timezone (nevermind the origin timezone) by birthday, this is my way to do this

How to make a JSONP request from Javascript without JQuery?

I have a pure javascript library to do that https://github.com/robertodecurnex/J50Npi/blob/master/J50Npi.js

Take a look at it and let me know if you need any help using or understanding the code.

Btw, you have simple usage example here: http://robertodecurnex.github.com/J50Npi/

What does the ??!??! operator do in C?

??! is a trigraph that translates to |. So it says:

!ErrorHasOccured() || HandleError();

which, due to short circuiting, is equivalent to:

if (ErrorHasOccured())
    HandleError();

Guru of the Week (deals with C++ but relevant here), where I picked this up.

Possible origin of trigraphs or as @DwB points out in the comments it's more likely due to EBCDIC being difficult (again). This discussion on the IBM developerworks board seems to support that theory.

From ISO/IEC 9899:1999 §5.2.1.1, footnote 12 (h/t @Random832):

The trigraph sequences enable the input of characters that are not defined in the Invariant Code Set as described in ISO/IEC 646, which is a subset of the seven-bit US ASCII code set.

How to remove last n characters from every element in the R vector

Here's a way with gsub:

cs <- c("foo_bar","bar_foo","apple","beer")
gsub('.{3}$', '', cs)
# [1] "foo_" "bar_" "ap"   "b"

How to style components using makeStyles and still have lifecycle methods in Material UI?

Hi instead of using hook API, you should use Higher-order component API as mentioned here

I'll modify the example in the documentation to suit your need for class component

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/styles';
import Button from '@material-ui/core/Button';

const styles = theme => ({
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
});

class HigherOrderComponentUsageExample extends React.Component {
  
  render(){
    const { classes } = this.props;
    return (
      <Button className={classes.root}>This component is passed to an HOC</Button>
      );
  }
}

HigherOrderComponentUsageExample.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(HigherOrderComponentUsageExample);

What is JNDI? What is its basic use? When is it used?

What is JNDI ?

JNDI stands for Java Naming and Directory Interface. It comes standard with J2EE.

What is its basic use?

With this API, you can access many types of data, like objects, devices, files of naming and directory services, eg. it is used by EJB to find remote objects. JNDI is designed to provide a common interface to access existing services like DNS, NDS, LDAP, CORBA and RMI.

When it is used?

You can use the JNDI to perform naming operations, including read operations and operations for updating the namespace. The following operations are described here.

Creating an empty bitmap and drawing though canvas in Android

This is probably simpler than you're thinking:

int w = WIDTH_PX, h = HEIGHT_PX;

Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

Here's a series of tutorials I've found on the topic: Drawing with Canvas Series

How does the stack work in assembly language?

You are correct that a stack is 'just' a data structure. Here, however, it refers to a hardware implemented stack used for a special purpose --"The Stack".

Many people have commented about hardware implemented stack versus the (software)stack data structure. I would like to add that there are three major stack structure types -

  1. A call stack -- Which is the one you are asking about! It stores function parameters and return address etc. Do read Chapter 4 ( All about 4th page i.e. page 53)functions in that book. There is a good explanation.
  2. A generic stack Which you might use in your program to do something special...
  3. A generic hardware stack
    I am not sure about this, but I remember reading somewhere that there is a general purpose hardware implemented stack available in some architectures. If anyone knows whether this is correct, please do comment.

The first thing to know is the architecture you are programming for, which the book explains (I just looked it up --link). To really understand things, I suggest that you learn about the memory, addressing, registers and architecture of x86 (I assume thats what you are learning --from the book).

File count from a folder

You can use the Directory.GetFiles method

Also see Directory.GetFiles Method (String, String, SearchOption)

You can specify the search option in this overload.

TopDirectoryOnly: Includes only the current directory in a search.

AllDirectories: Includes the current directory and all the subdirectories in a search operation. This option includes reparse points like mounted drives and symbolic links in the search.

// searches the current directory and sub directory
int fCount = Directory.GetFiles(path, "*", SearchOption.AllDirectories).Length;
// searches the current directory
int fCount = Directory.GetFiles(path, "*", SearchOption.TopDirectoryOnly).Length;

Stop MySQL service windows

This is a newer and easier answer.

  1. Run cmd as admin
  2. Type "net start mysql" then the version number, in my case "net start mysql80" for MySQL 8.0.
  3. If it says it's already running great, otherwise now mysql is running.
  4. Exit cmd, WIN+R and type services.msc, scroll down until you find my sql with the right version.
  5. Right-Click for properties, under startup type select 'Manual', then under service status select 'Stop'
  6. Now you stopped mysql service and it will not run automatically again.
  7. To turn it back on, in cmd admin 'net start mysql' and the version number, in my case 'net start mysql80'

CardView not showing Shadow in Android L

After going through the docs again, I finally found the solution.

Just add card_view:cardUseCompatPadding="true" to your CardView and shadows will appear on Lollipop devices.

What happens is, the content area in a CardView take different sizes on pre-lollipop and lollipop devices. So in lollipop devices the shadow is actually covered by the card so its not visible. By adding this attribute the content area remains the same across all devices and the shadow becomes visible.

My xml code is like :

<android.support.v7.widget.CardView
    android:id="@+id/media_card_view"
    android:layout_width="match_parent"
    android:layout_height="130dp"
    card_view:cardBackgroundColor="@android:color/white"
    card_view:cardElevation="2dp"
    card_view:cardUseCompatPadding="true"
    >
...
</android.support.v7.widget.CardView>

How to convert the background to transparent?

I would recommend this (just found via search):

  1. http://lunapic.com/editor/?action=load
  2. Browse for image to upload OR enter URL of the file (below the image)
    http://i.stack.imgur.com/2gQWg.png
  3. Edit menu/Transparent (last one)
  4. Click on the red area
  5. Behold :) below is your image, it's just white triangle with transparency...
    [dragging the image around in your browser for visibility,
    the gray background and the border is not part of the image]
    your image made transparent
  6. File menu/Save Image
    GIF/PNG/ICO image file formats support transparency, JPG doesn't!

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

Weird behavior of the != XPath operator

The problem is that the 'and' is being treated as an 'or'.

No, the problem is that you are using the XPath != operator and you aren't aware of its "weird" semantics.

Solution:

Just replace the any x != y expressions with a not(x = y) expression.

In your specific case:

Replace:

<xsl:when test="$AccountNumber != '12345' and $Balance != '0'">

with:

<xsl:when test="not($AccountNumber = '12345') and not($Balance = '0')">

Explanation:

By definition whenever one of the operands of the != operator is a nodeset, then the result of evaluating this operator is true if there is a node in the node-set, whose value isn't equal to the other operand.

So:

 $someNodeSet != $someValue

generally doesn't produce the same result as:

 not($someNodeSet = $someValue)

The latter (by definition) is true exactly when there isn't a node in $someNodeSet whose string value is equal to $someValue.

Lesson to learn:

Never use the != operator, unless you are absolutely sure you know what you are doing.

jquery append div inside div with id and manipulate

var e = $('<div style="display:block; id="myid" float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$("#box").html(e);

The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel

There are multiple ways you can handle this:

  1. If you insist on using PUT you can change the form action to POST and add a hidden method_field that has a value PUTand a hidden csrf field (if you are using blade then you just need to add @csrf_field and {{ method_field('PUT') }}). This way the form would accept the request.

  2. You can simply change the route and form method to POST. It will work just fine since you are the one defining the route and not using the resource group.

How to install an APK file on an Android phone?

If you have access to a Gmail account on the phone then an easy way (in terms of minimal set up effort) is to mail the .apk file to that Gmail account.

If you then access that account from the native Gmail app on the phone it recognises that the attachment is an app and offers an "Install" button.

As per other responses this approach also requires that you have selected USB debugging on the device.

Try this - it is remarkably easy ;-)

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

Setting Oracle 11g Session Timeout

That's generally controlled by the profile associated with the user Tomcat is connecting as.

SQL> SELECT PROFILE, LIMIT FROM DBA_PROFILES WHERE RESOURCE_NAME = 'IDLE_TIME';

PROFILE                        LIMIT
------------------------------ ----------------------------------------
DEFAULT                        UNLIMITED

SQL> SELECT PROFILE FROM DBA_USERS WHERE USERNAME = USER;

PROFILE
------------------------------
DEFAULT

So the user I'm connected to has unlimited idle time - no time out.

How to play a sound using Swift?

If code doesn't generate any error, but you don't hear sound - create the player as an instance:

   static var player: AVAudioPlayer!

For me the first solution worked when I did this change :)

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

nor does it appear in the list of environments that can be added when I click the "Add" button. All I see is the J2EE Runtime Library.

Go get "Eclipse for Java EE developers". Note the extra "EE". This includes among others the Web Tools Platform with among others a lot of server plugins with among others the one for Apache Tomcat 5.x. It's also logically; JSP/Servlet is part of the Java EE API.

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

Extract from the oficial docs:

Requires that the parent form is validated, that is, $( "form" ).validate() is called first

more about... rules

Accessing bash command line args $@ vs $*

The difference appears when the special parameters are quoted. Let me illustrate the differences:

$ set -- "arg  1" "arg  2" "arg  3"

$ for word in $*; do echo "$word"; done
arg
1
arg
2
arg
3

$ for word in $@; do echo "$word"; done
arg
1
arg
2
arg
3

$ for word in "$*"; do echo "$word"; done
arg  1 arg  2 arg  3

$ for word in "$@"; do echo "$word"; done
arg  1
arg  2
arg  3

one further example on the importance of quoting: note there are 2 spaces between "arg" and the number, but if I fail to quote $word:

$ for word in "$@"; do echo $word; done
arg 1
arg 2
arg 3

and in bash, "$@" is the "default" list to iterate over:

$ for word; do echo "$word"; done
arg  1
arg  2
arg  3

How to write LaTeX in IPython Notebook?

I came across this problem some day using colab. And I find the most painless way is just running this code before printing. Everything works like charm then.

from IPython.display import Math, HTML

def load_mathjax_in_cell_output():
  display(HTML("<script src='https://www.gstatic.com/external_hosted/"
               "mathjax/latest/MathJax.js?config=default'></script>"))
get_ipython().events.register('pre_run_cell', load_mathjax_in_cell_output)
import sympy as sp
sp.init_printing()

The result looks like this:

enter image description here

Global constants file in Swift

Consider enumerations. These can be logically broken up for separate use cases.

enum UserDefaultsKeys: String {
    case SomeNotification = "aaaaNotification"
    case DeviceToken = "deviceToken"
}

enum PhotoMetaKeys: String {
    case Orientation = "orientation_hv"
    case Size = "size"
    case DateTaken = "date_taken"
}

One unique benefit happens when you have a situation of mutually exclusive options, such as:

for (key, value) in photoConfigurationFile {
    guard let key = PhotoMetaKeys(rawvalue: key) else {
        continue // invalid key, ignore it
    }
    switch (key) {
    case.Orientation: {
        photo.orientation = value
    }
    case.Size: {
        photo.size = value
    }
    }
}

In this example, you will receive a compile error because you have not handled the case of PhotoMetaKeys.DateTaken.

Convert an int to ASCII character

"I have int i = 6; and I want char c = '6' by conversion. Any simple way to suggest?"

There are only 10 numbers. So write a function that takes an int from 0-9 and returns the ascii code. Just look it up in an ascii table and write a function with ifs or a select case.

Component is part of the declaration of 2 modules

IN Angular 4. This error is considered as ng serve run time cache issue.

case:1 this error will occur, once you import the component in one module and again import in sub modules will occur.

case:2 Import one Component in wrong place and removed and replaced in Correct module, That time it consider as ng serve cache issue. Need to Stop the project and start -do again ng serve, It will work as expected.

How to display an activity indicator with text on iOS 8 with Swift?

While Esq's answer works, I've added my own implementation which is more in line with good component architecture by separating the view into it's own class. It also uses dynamic blurring introduced in iOS 8.

Here is how mine looks with an image background:

enter image description here

The code for this is encapsulated in it's own UIView class which means you can reuse it whenever you desire.

Updated for Swift 3

Usage

func viewDidLoad() {
  super.viewDidLoad()

  // Create and add the view to the screen.
  let progressHUD = ProgressHUD(text: "Saving Photo")
  self.view.addSubview(progressHUD)
  // All done!

  self.view.backgroundColor = UIColor.black
}

UIView Code

import UIKit

class ProgressHUD: UIVisualEffectView {

  var text: String? {
    didSet {
      label.text = text
    }
  }

  let activityIndictor: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
  let label: UILabel = UILabel()
  let blurEffect = UIBlurEffect(style: .light)
  let vibrancyView: UIVisualEffectView

  init(text: String) {
    self.text = text
    self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect))
    super.init(effect: blurEffect)
    self.setup()
  }

  required init?(coder aDecoder: NSCoder) {
    self.text = ""
    self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect))
    super.init(coder: aDecoder)
    self.setup()
  }

  func setup() {
    contentView.addSubview(vibrancyView)
    contentView.addSubview(activityIndictor)
    contentView.addSubview(label)
    activityIndictor.startAnimating()
  }

  override func didMoveToSuperview() {
    super.didMoveToSuperview()

    if let superview = self.superview {

      let width = superview.frame.size.width / 2.3
      let height: CGFloat = 50.0
      self.frame = CGRect(x: superview.frame.size.width / 2 - width / 2,
                      y: superview.frame.height / 2 - height / 2,
                      width: width,
                      height: height)
      vibrancyView.frame = self.bounds

      let activityIndicatorSize: CGFloat = 40
      activityIndictor.frame = CGRect(x: 5,
                                      y: height / 2 - activityIndicatorSize / 2,
                                      width: activityIndicatorSize,
                                      height: activityIndicatorSize)

      layer.cornerRadius = 8.0
      layer.masksToBounds = true
      label.text = text
      label.textAlignment = NSTextAlignment.center
      label.frame = CGRect(x: activityIndicatorSize + 5,
                           y: 0,
                           width: width - activityIndicatorSize - 15,
                           height: height)
      label.textColor = UIColor.gray
      label.font = UIFont.boldSystemFont(ofSize: 16)
    }
  }

  func show() {
    self.isHidden = false
  }

  func hide() {
    self.isHidden = true
  }
}

Swift 2

An example on how to use it is like this:

override func viewDidLoad() {
    super.viewDidLoad()

    // Create and add the view to the screen.
    let progressHUD = ProgressHUD(text: "Saving Photo")
    self.view.addSubview(progressHUD)
    // All done!

    self.view.backgroundColor = UIColor.blackColor()
}

Here is the UIView code:

import UIKit

class ProgressHUD: UIVisualEffectView {

    var text: String? {
        didSet {
            label.text = text
        }
    }
    let activityIndictor: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
    let label: UILabel = UILabel()
    let blurEffect = UIBlurEffect(style: .Light)
    let vibrancyView: UIVisualEffectView

    init(text: String) {
        self.text = text
        self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect))
        super.init(effect: blurEffect)
        self.setup()
    }

    required init(coder aDecoder: NSCoder) {
        self.text = ""
        self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect))
        super.init(coder: aDecoder)
        self.setup()

    }

    func setup() {
        contentView.addSubview(vibrancyView)
        vibrancyView.contentView.addSubview(activityIndictor)
        vibrancyView.contentView.addSubview(label)
        activityIndictor.startAnimating()
    }

    override func didMoveToSuperview() {
        super.didMoveToSuperview()

        if let superview = self.superview {

            let width = superview.frame.size.width / 2.3
            let height: CGFloat = 50.0
            self.frame = CGRectMake(superview.frame.size.width / 2 - width / 2,
                superview.frame.height / 2 - height / 2,
                width,
                height)
            vibrancyView.frame = self.bounds

            let activityIndicatorSize: CGFloat = 40
            activityIndictor.frame = CGRectMake(5, height / 2 - activityIndicatorSize / 2,
                activityIndicatorSize,
                activityIndicatorSize)

            layer.cornerRadius = 8.0
            layer.masksToBounds = true
            label.text = text
            label.textAlignment = NSTextAlignment.Center
            label.frame = CGRectMake(activityIndicatorSize + 5, 0, width - activityIndicatorSize - 15, height)
            label.textColor = UIColor.grayColor()
            label.font = UIFont.boldSystemFontOfSize(16)
        }
    }

    func show() {
        self.hidden = false
    }

    func hide() {
        self.hidden = true
    }
}

I hope this helps, please feel free to use this code wherever you need.