Programs & Examples On #Name value

Parse a URI String into Name-Value Collection

I had a go at a Kotlin version seeing how this is the top result in Google.

@Throws(UnsupportedEncodingException::class)
fun splitQuery(url: URL): Map<String, List<String>> {

    val queryPairs = LinkedHashMap<String, ArrayList<String>>()

    url.query.split("&".toRegex())
            .dropLastWhile { it.isEmpty() }
            .map { it.split('=') }
            .map { it.getOrEmpty(0).decodeToUTF8() to it.getOrEmpty(1).decodeToUTF8() }
            .forEach { (key, value) ->

                if (!queryPairs.containsKey(key)) {
                    queryPairs[key] = arrayListOf(value)
                } else {

                    if(!queryPairs[key]!!.contains(value)) {
                        queryPairs[key]!!.add(value)
                    }
                }
            }

    return queryPairs
}

And the extension methods

fun List<String>.getOrEmpty(index: Int) : String {
    return getOrElse(index) {""}
}

fun String.decodeToUTF8(): String { 
    URLDecoder.decode(this, "UTF-8")
}

Executing Javascript code "on the spot" in Chrome?

If you mean you want to execute the function inputted, yes, that is simple:

Use this JS code:

eval(document.getElementById( -- el ID -- ).value);

How do I access properties of a javascript object if I don't know the names?

You can use Object.keys(), "which returns an array of a given object's own enumerable property names, in the same order as we get with a normal loop."

You can use any object in place of stats:

_x000D_
_x000D_
var stats = {_x000D_
  a: 3,_x000D_
  b: 6,_x000D_
  d: 7,_x000D_
  erijgolekngo: 35_x000D_
}_x000D_
/*  this is the answer here  */_x000D_
for (var key in Object.keys(stats)) {_x000D_
  var t = Object.keys(stats)[key];_x000D_
  console.log(t + " value =: " + stats[t]);_x000D_
}
_x000D_
_x000D_
_x000D_

How should I log while using multiprocessing in Python?

QueueHandler is native in Python 3.2+, and does exactly this. It is easily replicated in previous versions.

Python docs have two complete examples: Logging to a single file from multiple processes

For those using Python < 3.2, just copy QueueHandler into your own code from: https://gist.github.com/vsajip/591589 or alternatively import logutils.

Each process (including the parent process) puts its logging on the Queue, and then a listener thread or process (one example is provided for each) picks those up and writes them all to a file - no risk of corruption or garbling.

How to use ConfigurationManager

Okay, it took me a while to see this, but there's no way this compiles:

return String.(ConfigurationManager.AppSettings[paramName]);

You're not even calling a method on the String type. Just do this:

return ConfigurationManager.AppSettings[paramName];

The AppSettings KeyValuePair already returns a string. If the name doesn't exist, it will return null.


Based on your edit you have not yet added a Reference to the System.Configuration assembly for the project you're working in.

FCM getting MismatchSenderId

For eliminate this error for mismatch sender Id In fcm

{"multicast_id":7751536172966571167,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"MismatchSenderId"}]}

there is error occured,

  1. So we required first, In FCM, register Application e.g MyDemoApplication

  2. After that FCM will generate server key i.e AIzaSyB9krC8mLHzO_TtECb5qg7NDZPxeG03jHU and sender Id i.e 346252831806 these format like these.

  3. After In Android Studio, our project is connect to these FCM created project i.e MyDemoApplication

  4. And most important step is there required to device token or registration id. These token must created in Android Studio..

  5. After that using Sender Id and API key in web API project u will be definitely getting notification

XPath OR operator for different nodes

All title nodes with zipcode or book node as parent:

Version 1:

//title[parent::zipcode|parent::book]

Version 2:

//bookstore/book/title|//bookstore/city/zipcode/title

Version 3: (results are sorted based on source data rather than the order of book then zipcode)

//title[../../../*[book or magazine] or ../../../../*[city/zipcode]]

or - used within true/false - a Boolean operator in xpath

| - a Union operator in xpath that appends the query to the right of the operator to the result set from the left query.

Java: recommended solution for deep cloning/copying an instance

Joshua Bloch's book has a whole chapter entitled "Item 10: Override Clone Judiciously" in which he goes into why overriding clone for the most part is a bad idea because the Java spec for it creates many problems.

He provides a few alternatives:

  • Use a factory pattern in place of a constructor:

         public static Yum newInstance(Yum yum);
    
  • Use a copy constructor:

         public Yum(Yum yum);
    

All of the collection classes in Java support the copy constructor (e.g. new ArrayList(l);)

How do I call a specific Java method on a click/submit event of a specific button in JSP?

If you have web.xml then

HTML/JSP

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <input type="submit" name="button1" value="Button 1" />
</form>

web.xml

<servlet>
        <display-name>Servlet Name</display-name>
        <servlet-name>myservlet</servlet-name>
        <servlet-class>package.SomeController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>myservlet</servlet-name>
    <url-pattern>/myservlet</url-pattern>
</servlet-mapping>

Java SomeController.java

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Write your code below");
}

Passing data from controller to view in Laravel

For Passing a single variable to view.

Inside Your controller create a method like:

function sleep()
{
        return view('welcome')->with('title','My App');
}

In Your route

Route::get('/sleep', 'TestController@sleep');

In Your View Welcome.blade.php. You can echo your variable like {{ $title }}

For An Array(multiple values) change,sleep method to :

function sleep()
{
        $data = array(
            'title'=>'My App',
            'Description'=>'This is New Application',
            'author'=>'foo'
            );
        return view('welcome')->with($data);
}

You can access you variable like {{ $author }}.

Django return redirect() with parameters

Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

/link/mybackend/?field1=value1&field2=value2&field3=value3

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

So your urlconf would be:

url(r'^link/(?P<backend>\w+?)/$', my_function)

and the view would look like:

def my_function(request, backend):
   data = request.GET

and the reverse would be (after importing urllib):

return "%s?%s" % (redirect('my_function', args=(backend,)),
                  urllib.urlencode(form.cleaned_data))

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

request.session['temp_data'] = form.cleaned_data

jquery - Click event not working for dynamically created button

the simple and easy way to do that is use on event:

$('body').on('click','#element',function(){
    //somthing
});

but we can say this is not the best way to do this. I suggest a another way to do this is use clone() method instead of using dynamic html. Write some html in you file for example:

<div id='div1'></div>

Now in the script tag make a clone of this div then all the properties of this div would follow with new element too. For Example:

var dynamicDiv = jQuery('#div1').clone(true);

Now use the element dynamicDiv wherever you want to add it or change its properties as you like. Now all jQuery functions will work with this element

How to change language settings in R

You can set this using the Sys.setenv() function. My R session defaults to English, so I'll set it to French and then back again:

> Sys.setenv(LANG = "fr")
> 2 + x
Erreur : objet 'x' introuvable
> Sys.setenv(LANG = "en")
> 2 + x
Error: object 'x' not found

A list of the abbreviations can be found here.

Sys.getenv() gives you a list of all the environment variables that are set.

Parse JSON String to JSON Object in C#.NET

Another choice besides JObject is System.Json.JsonValue for Weak-Typed JSON object.

It also has a JsonValue blob = JsonValue.Parse(json); you can use. The blob will most likely be of type JsonObject which is derived from JsonValue, but could be JsonArray. Check the blob.JsonType if you need to know.

And to answer you question, YES, you may replace json with the name of your actual variable that holds the JSON string. ;-D

There is a System.Json.dll you should add to your project References.

-Jesse

Elegant ways to support equivalence ("equality") in Python classes

The 'is' test will test for identity using the builtin 'id()' function which essentially returns the memory address of the object and therefore isn't overloadable.

However in the case of testing the equality of a class you probably want to be a little bit more strict about your tests and only compare the data attributes in your class:

import types

class ComparesNicely(object):

    def __eq__(self, other):
        for key, value in self.__dict__.iteritems():
            if (isinstance(value, types.FunctionType) or 
                    key.startswith("__")):
                continue

            if key not in other.__dict__:
                return False

            if other.__dict__[key] != value:
                return False

         return True

This code will only compare non function data members of your class as well as skipping anything private which is generally what you want. In the case of Plain Old Python Objects I have a base class which implements __init__, __str__, __repr__ and __eq__ so my POPO objects don't carry the burden of all that extra (and in most cases identical) logic.

how to measure running time of algorithms in python

I am not 100% sure what is meant by "running times of my algorithms written in python", so I thought I might try to offer a broader look at some of the potential answers.

  • Algorithms don't have running times; implementations can be timed, but an algorithm is an abstract approach to doing something. The most common and often the most valuable part of optimizing a program is analyzing the algorithm, usually using asymptotic analysis and computing the big O complexity in time, space, disk use and so forth.

    A computer cannot really do this step for you. This requires doing the math to figure out how something works. Optimizing this side of things is the main component to having scalable performance.

  • You can time your specific implementation. The nicest way to do this in Python is to use timeit. The way it seems most to want to be used is to make a module with a function encapsulating what you want to call and call it from the command line with python -m timeit ....

    Using timeit to compare multiple snippets when doing microoptimization, but often isn't the correct tool you want for comparing two different algorithms. It is common that what you want is asymptotic analysis, but it's possible you want more complicated types of analysis.

  • You have to know what to time. Most snippets aren't worth improving. You need to make changes where they actually count, especially when you're doing micro-optimisation and not improving the asymptotic complexity of your algorithm.

    If you quadruple the speed of a function in which your code spends 1% of the time, that's not a real speedup. If you make a 20% speed increase on a function in which your program spends 50% of the time, you have a real gain.

    To determine the time spent by a real Python program, use the stdlib profiling utilities. This will tell you where in an example program your code is spending its time.

What is a mixin, and why are they useful?

This answer aims to explain mixins with examples that are:

  • self-contained: short, with no need to know any libraries to understand the example.

  • in Python, not in other languages.

    It is understandable that there were examples from other languages such as Ruby since the term is much more common in those languages, but this is a Python thread.

It shall also consider the controversial question:

Is multiple inheritance necessary or not to characterize a mixin?

Definitions

I have yet to see a citation from an "authoritative" source clearly saying what is a mixin in Python.

I have seen 2 possible definitions of a mixin (if they are to be considered as different from other similar concepts such as abstract base classes), and people don't entirely agree on which one is correct.

The consensus may vary between different languages.

Definition 1: no multiple inheritance

A mixin is a class such that some method of the class uses a method which is not defined in the class.

Therefore the class is not meant to be instantiated, but rather serve as a base class. Otherwise the instance would have methods that cannot be called without raising an exception.

A constraint which some sources add is that the class may not contain data, only methods, but I don't see why this is necessary. In practice however, many useful mixins don't have any data, and base classes without data are simpler to use.

A classic example is the implementation of all comparison operators from only <= and ==:

class ComparableMixin(object):
    """This class has methods which use `<=` and `==`,
    but this class does NOT implement those methods."""
    def __ne__(self, other):
        return not (self == other)
    def __lt__(self, other):
        return self <= other and (self != other)
    def __gt__(self, other):
        return not self <= other
    def __ge__(self, other):
        return self == other or self > other

class Integer(ComparableMixin):
    def __init__(self, i):
        self.i = i
    def __le__(self, other):
        return self.i <= other.i
    def __eq__(self, other):
        return self.i == other.i

assert Integer(0) <  Integer(1)
assert Integer(0) != Integer(1)
assert Integer(1) >  Integer(0)
assert Integer(1) >= Integer(1)

# It is possible to instantiate a mixin:
o = ComparableMixin()
# but one of its methods raise an exception:
#o != o 

This particular example could have been achieved via the functools.total_ordering() decorator, but the game here was to reinvent the wheel:

import functools

@functools.total_ordering
class Integer(object):
    def __init__(self, i):
        self.i = i
    def __le__(self, other):
        return self.i <= other.i
    def __eq__(self, other):
        return self.i == other.i

assert Integer(0) < Integer(1)
assert Integer(0) != Integer(1)
assert Integer(1) > Integer(0)
assert Integer(1) >= Integer(1)

Definition 2: multiple inheritance

A mixin is a design pattern in which some method of a base class uses a method it does not define, and that method is meant to be implemented by another base class, not by the derived like in Definition 1.

The term mixin class refers to base classes which are intended to be used in that design pattern (TODO those that use the method, or those that implement it?)

It is not easy to decide if a given class is a mixin or not: the method could be just implemented on the derived class, in which case we're back to Definition 1. You have to consider the author's intentions.

This pattern is interesting because it is possible to recombine functionalities with different choices of base classes:

class HasMethod1(object):
    def method(self):
        return 1

class HasMethod2(object):
    def method(self):
        return 2

class UsesMethod10(object):
    def usesMethod(self):
        return self.method() + 10

class UsesMethod20(object):
    def usesMethod(self):
        return self.method() + 20

class C1_10(HasMethod1, UsesMethod10): pass
class C1_20(HasMethod1, UsesMethod20): pass
class C2_10(HasMethod2, UsesMethod10): pass
class C2_20(HasMethod2, UsesMethod20): pass

assert C1_10().usesMethod() == 11
assert C1_20().usesMethod() == 21
assert C2_10().usesMethod() == 12
assert C2_20().usesMethod() == 22

# Nothing prevents implementing the method
# on the base class like in Definition 1:

class C3_10(UsesMethod10):
    def method(self):
        return 3

assert C3_10().usesMethod() == 13

Authoritative Python occurrences

At the official documentatiton for collections.abc the documentation explicitly uses the term Mixin Methods.

It states that if a class:

  • implements __next__
  • inherits from a single class Iterator

then the class gets an __iter__ mixin method for free.

Therefore at least on this point of the documentation, mixin does not not require multiple inheritance, and is coherent with Definition 1.

The documentation could of course be contradictory at different points, and other important Python libraries might be using the other definition in their documentation.

This page also uses the term Set mixin, which clearly suggests that classes like Set and Iterator can be called Mixin classes.

In other languages

  • Ruby: Clearly does not require multiple inheritance for mixin, as mentioned in major reference books such as Programming Ruby and The Ruby programming Language

  • C++: A virtual method that is set =0 is a pure virtual method.

    Definition 1 coincides with the definition of an abstract class (a class that has a pure virtual method). That class cannot be instantiated.

    Definition 2 is possible with virtual inheritance: Multiple Inheritance from two derived classes

How To Use DateTimePicker In WPF?

I don't think this DateTimePicker has been mentioned before:

A WPF DateTimePicker That Works Like the One in Winforms

That one is in VB and has some bugs. I converted it to C# and made a new version with bug fixes.

DateTimePicker

Note: I used the Calendar control in WPFToolkit so that I could use .NET 3.5 instead of .NET 4. If you are using .NET 4, just remove references to "wpftc" in the XAML.

View google chrome's cached pictures

You can make a bookmark with this as the url:

javascript:
var cached_anchors = $$('a');
for (var i in cached_anchors) {
    var ca = cached_anchors[i];
    if(ca.href.search('sprite') < 0 && ca.href.search('.png') > -1 || ca.href.search('.gif') > -1 || ca.href.search('.jpg') > -1) {
        var a = document.createElement('a');
        a.href = ca.innerHTML;
        a.target = '_blank';

        var img = document.createElement('img');
        img.src = ca.innerHTML;
        img.style.maxHeight = '100px';

        a.appendChild(img);
        document.getElementsByTagName('body')[0].appendChild(a);
    }
}
document.getElementsByTagName('body')[0].removeChild(document.getElementsByTagName('table')[0]);
void(0);

Then just go to chrome://cache and then click your bookmark and it'll show you all the images.

Exception thrown in catch and finally clause

Finally clause is executed even when exception is thrown from anywhere in try/catch block.

Because it's the last to be executed in the main and it throws an exception, that's the exception that the callers see.

Hence the importance of making sure that the finally clause does not throw anything, because it can swallow exceptions from the try block.

How to reload / refresh model data from the server programmatically?

Before I show you how to reload / refresh model data from the server programmatically? I have to explain for you the concept of Data Binding. This is an extremely powerful concept that will truly revolutionize the way you develop. So may be you have to read about this concept from this link or this seconde link in order to unterstand how AngularjS work.

now I'll show you a sample example that exaplain how can you update your model from server.

HTML Code:

<div ng-controller="PersonListCtrl">
    <ul>
        <li ng-repeat="person in persons">
            Name: {{person.name}}, Age {{person.age}}
        </li>
    </ul>
   <button ng-click="updateData()">Refresh Data</button>
</div>

So our controller named: PersonListCtrl and our Model named: persons. go to your Controller js in order to develop the function named: updateData() that will be invoked when we are need to update and refresh our Model persons.

Javascript Code:

app.controller('adsController', function($log,$scope,...){

.....

$scope.updateData = function(){
$http.get('/persons').success(function(data) {
       $scope.persons = data;// Update Model-- Line X
     });
}

});

Now I explain for you how it work: when user click on button Refresh Data, the server will call to function updateData() and inside this function we will invoke our web service by the function $http.get() and when we have the result from our ws we will affect it to our model (Line X).Dice that affects the results for our model, our View of this list will be changed with new Data.

YAML equivalent of array of objects in JSON

Great answer above. Another way is to use the great yaml jq wrapper tool, yq at https://github.com/kislyuk/yq

Save your JSON example to a file, say ex.json and then

yq -y '.' ex.json

AAPL:
- shares: -75.088
  date: 11/27/2015
- shares: 75.088
  date: 11/26/2015

How to Pass data from child to parent component Angular

Register the EventEmitter in your child component as the @Output:

@Output() onDatePicked = new EventEmitter<any>();

Emit value on click:

public pickDate(date: any): void {
    this.onDatePicked.emit(date);
}

Listen for the events in your parent component's template:

<div>
    <calendar (onDatePicked)="doSomething($event)"></calendar>
</div>

and in the parent component:

public doSomething(date: any):void {
    console.log('Picked date: ', date);
}

It's also well explained in the official docs: Component interaction.

php form action php self

If you want to be secure use this:<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Embedding Base64 Images

Most modern desktop browsers such as Chrome, Mozilla and Internet Explorer support images encoded as data URL. But there are problems displaying data URLs in some mobile browsers: Android Stock Browser and Dolphin Browser won't display embedded JPEGs.

I reccomend you to use the following tools for online base64 encoding/decoding:

Check the "Format as Data URL" option to format as a Data URL.

Cannot read property 'getContext' of null, using canvas

I assume you have your JS file declared inside the <head> tag so it keeps it consistent, like standard, then in your JS make sure the canvas initialization is after the page is loaded:

window.onload = function () {
    var myCanvas = document.getElementById('canvas');
    var ctx = myCanvas.getContext('2d');
}

There is no need to use jQuery just to initialize a canvas, it's very evident most of the programmers all around the world use it unnecessarily and the accepted answer is a probe of that.

"for loop" with two variables?

I think you are looking for nested loops.

Example (based on your edit):

t1=[1,2,'Hello',(1,2),999,1.23]
t2=[1,'Hello',(1,2),999]

t3=[]

for it1, e1 in enumerate(t1):
    for it2, e2 in enumerate(t2):
        if e1==e2:
            t3.append((it1,it2,e1))

# t3=[(0, 0, 1), (2, 1, 'Hello'), (3, 2, (1, 2)), (4, 3, 999)]

Which can be reduced to a single comprehension:

[(it1,it2,e1) for it1, e1 in enumerate(t1) for it2, e2 in enumerate(t2) if e1==e2] 

But to find the common elements, you can just do:

print set(t1) & set(t2)
# set([(1, 2), 1, 'Hello', 999])

If your list contains non-hashable objects (like other lists, dicts) use a frozen set:

from collections import Iterable
s1=set(frozenset(e1) if isinstance(e1,Iterable) else e1 for e1 in t1)
s2=set(frozenset(e2) if isinstance(e2,Iterable) else e2 for e2 in t2)
print s1 & s2

CORS: credentials mode is 'include'

Customizing CORS for Angular 5 and Spring Security (Cookie base solution)

On the Angular side required adding option flag withCredentials: true for Cookie transport:

constructor(public http: HttpClient) {
}

public get(url: string = ''): Observable<any> {
    return this.http.get(url, { withCredentials: true });
}

On Java server-side required adding CorsConfigurationSource for configuration CORS policy:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        // This Origin header you can see that in Network tab
        configuration.setAllowedOrigins(Arrays.asList("http:/url_1", "http:/url_2")); 
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        configuration.setAllowedHeaders(Arrays.asList("content-type"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()...
    }
}

Method configure(HttpSecurity http) by default will use corsConfigurationSource for http.cors()

#define macro for debug printing in C?

For a portable (ISO C90) implementation, you could use double parentheses, like this;

#include <stdio.h>
#include <stdarg.h>

#ifndef NDEBUG
#  define debug_print(msg) stderr_printf msg
#else
#  define debug_print(msg) (void)0
#endif

void
stderr_printf(const char *fmt, ...)
{
  va_list ap;
  va_start(ap, fmt);
  vfprintf(stderr, fmt, ap);
  va_end(ap);
}

int
main(int argc, char *argv[])
{
  debug_print(("argv[0] is %s, argc is %d\n", argv[0], argc));
  return 0;
}

or (hackish, wouldn't recommend it)

#include <stdio.h>

#define _ ,
#ifndef NDEBUG
#  define debug_print(msg) fprintf(stderr, msg)
#else
#  define debug_print(msg) (void)0
#endif

int
main(int argc, char *argv[])
{
  debug_print("argv[0] is %s, argc is %d"_ argv[0] _ argc);
  return 0;
}

Should I test private methods or only public ones?

As quoted above, "If you don't test your private methods, how do you know they won't break?"

This is a major issue. One of the big points of unit tests is to know where, when, and how something broke ASAP. Thus decreasing a significant amount of development & QA effort. If all that is tested is the public, then you don't have honest coverage and delineation of the internals of the class.

I've found one of the best ways to do this is simply add the test reference to the project and put the tests in a class parallel to the private methods. Put in the appropriate build logic so that the tests don't build into the final project.

Then you have all the benefits of having these methods tested and you can find problems in seconds versus minutes or hours.

So in summary, yes, unit test your private methods.

PHP - Modify current object in foreach loop

Surely using array_map and if using a container implementing ArrayAccess to derive objects is just a smarter, semantic way to go about this?

Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.

For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN() clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.

<?php

$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);

vs

<?php

$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
    $arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);

If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr you could always $arr = array_map and be explicit.

How Can I Override Style Info from a CSS Class in the Body of a Page?

Either use the style attribute to add CSS inline on your divs, e.g.:

<div style="color:red"> ... </div>

... or create your own style sheet and reference it after the existing stylesheet then your style sheet should take precedence.

... or add a <style> element in the <head> of your HTML with the CSS you need, this will take precedence over an external style sheet.

You can also add !important after your style values to override other styles on the same element.

Update

Use one of my suggestions above and target the span of class style21, rather than the containing div. The style you are applying on the containing div will not be inherited by the span as it's color is set in the style sheet.

Can't concatenate 2 arrays in PHP

Try saying

$array[] = array('Item 2'); 

Although it looks like you're trying to add an array into an array, thus $array[][] but that's not what your title suggests.

How to keep footer at bottom of screen

Perhaps the easiest is to use position: absolute to fix to the bottom, then a suitable margin/padding to make sure that the other text doesn't spill over the top of it.

css:

<style>
  body {
    margin: 0 0 20px;
  }
  .footer {
    position: absolute;
    bottom: 0;
    height: 20px;
    background: #f0f0f0;
    width: 100%;
  }
</style>

Here is the html main content.

<div class="footer"> Here is the footer. </div>

Using routes in Express-js

Seems that only index.js get loaded when you require("./routes") . I used the following code in index.js to load the rest of the routes:

var fs = require('fs')
  , path = require('path');

fs.readdirSync(__dirname).forEach(function(file){
  var route_fname = __dirname + '/' + file;
  var route_name = path.basename(route_fname, '.js');
  if(route_name !== 'index' && route_name[0] !== "."){ 
    exports[route_name] = require(route_fname)[route_name];
  }
});

TokenMismatchException in VerifyCsrfToken.php Line 67

Are you redirecting it back after the post ? I had this issue and I was able to solve it by returning the same view instead of using the Redirect::back().

Use this return view()->with(), instead of Redirect::back().

Pressed <button> selector

You can do this with php if the button opens a new page.

For example if the button link to a page named pagename.php as, url: www.website.com/pagename.php the button will stay red as long as you stay on that page.

I exploded the url by '/' an got something like:

url[0] = pagename.php

<? $url = explode('/', substr($_SERVER['REQUEST_URI'], strpos('/',$_SERVER['REQUEST_URI'] )+1,strlen($_SERVER['REQUEST_URI']))); ?>


<html>
<head>
  <style>
    .btn{
     background:white;
     }
    .btn:hover,
    .btn-on{
     background:red;
     }
  </style>
</head>
<body>
   <a href="/pagename.php" class="btn <? if (url[0]='pagename.php') {echo 'btn-on';} ?>">Click Me</a>
</body>
</html>

note: I didn't try this code. It might need adjustments.

How to uninstall Apache with command line

If Apache was installed using NSIS installer it should have left an uninstaller. You should search inside Apache installation directory for executable named unistaller.exe or something like that. NSIS uninstallers support /S flag by default for silent uninstall. So you can run something like "C:\Program Files\<Apache installation dir here>\uninstaller.exe" /S

From NSIS documentation:

3.2.1 Common Options

/NCRC disables the CRC check, unless CRCCheck force was used in the script. /S runs the installer or uninstaller silently. See section 4.12 for more information. /D sets the default installation directory ($INSTDIR), overriding InstallDir and InstallDirRegKey. It must be the last parameter used in the command line and must not contain any quotes, even if the path contains spaces. Only absolute paths are supported.

How to define Singleton in TypeScript

Another option is to use Symbols in your module. This way you can protect your class, also if the final user of your API is using normal Javascript:

let _instance = Symbol();
export default class Singleton {

    constructor(singletonToken) {
        if (singletonToken !== _instance) {
            throw new Error("Cannot instantiate directly.");
        }
        //Init your class
    }

    static get instance() {
        return this[_instance] || (this[_instance] = new Singleton(_singleton))
    }

    public myMethod():string {
        return "foo";
    }
}

Usage:

var str:string = Singleton.instance.myFoo();

If the user is using your compiled API js file, also will get an error if he try to instantiate manually your class:

// PLAIN JAVASCRIPT: 
var instance = new Singleton(); //Error the argument singletonToken !== _instance symbol

setTimeout / clearTimeout problems

Not sure if this violates some good practice coding rule but I usually come out with this one:

if(typeof __t == 'undefined')
        __t = 0;
clearTimeout(__t);
__t = setTimeout(callback, 1000);

This prevent the need to declare the timer out of the function.

EDIT: this also don't declare a new variable at each invocation, but always recycle the same.

Hope this helps.

How to set response header in JAX-RS so that user sees download popup for Excel?

You don't need HttpServletResponse to set a header on the response. You can do it using javax.ws.rs.core.Response. Just make your method to return Response instead of entity:

return Response.ok(entity).header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build()

If you still want to use HttpServletResponse you can get it either injected to one of the class fields, or using property, or to method parameter:

@Path("/resource")
class MyResource {

  // one way to get HttpServletResponse
  @Context
  private HttpServletResponse anotherServletResponse;

  // another way
  Response myMethod(@Context HttpServletResponse servletResponse) {
      // ... code
  }
}

What is WebKit and how is it related to CSS?

Update: So apparently, WebKit is a HTML/CSS web browser rendering engine for Safari/Chrome. Are there such engines for IE/Opera/Firefox and what are the differences, pros and cons of using one over the other? Can I use WebKit features in Firefox for example?

Every browser is backed by a rendering engine to draw the HTML/CSS web page.

  • IE → Trident (discontinued)
  • Edge ? EdgeHTML (clean-up fork of Trident) (Edge switched to Blink in 2019)
  • Firefox → Gecko
  • Opera → Presto (no longer uses Presto since Feb 2013, consider Opera = Chrome, therefore Blink nowadays)
  • Safari → WebKit
  • Chrome → Blink (a fork of Webkit).

See Comparison of web browser engines for a list of comparisons in different areas.

The ultimate question... is WebKit supported by IE?

Not natively.

Calculate difference between two dates (number of days)?

In case someone wants numer of whole days as a double (a, b of type DateTime):

 (a.Date - b.Date).TotalDays

SQL Server : check if variable is Empty or NULL for WHERE clause

Old post but worth a look for someone who stumbles upon like me

ISNULL(NULLIF(ColumnName, ' '), NULL) IS NOT NULL

ISNULL(NULLIF(ColumnName, ' '), NULL) IS NULL

Declare and assign multiple string variables at the same time

Just a reminder: Implicit type var in multiple declaration is not allowed. There might be the following compilation errors.

var Foo = 0, Bar = 0;

Implicitly-typed variables cannot have multiple declarators

Similarly,

var Foo, Bar;

Implicitly-typed variables must be initialized

2D cross-platform game engine for Android and iOS?

LibGDX is one of the best engines I've ever used, works on almost all platforms, and performs twice as fast as cocos2d-x in most tests I've done. You can use any JVM language you like. Here's a 13 part tutorial in Java, and here's a bunch using jruby. There's a good skeletal animation tool that works with it here, and it has baked in support for tiled TMX maps as well. The ui framework is awesome, and it has a scene graph and actor style API similar to cocos2d scenes, sprites and actions. The community is awesome, updates are frequent, and the documentation is good. Don't let the java part scare you, it's fast, and you can use jruby or scala or whatever you like. I highly recommend it for 2d or 3d work, it supports both.

How can I run an EXE program from a Windows Service using C#?

First, we are going to create a Windows Service that runs under the System account. This service will be responsible for spawning an interactive process within the currently active User’s Session. This newly created process will display a UI and run with full admin rights. When the first User logs on to the computer, this service will be started and will be running in Session0; however the process that this service spawns will be running on the desktop of the currently logged on User. We will refer to this service as the LoaderService.

Next, the winlogon.exe process is responsible for managing User login and logout procedures. We know that every User who logs on to the computer will have a unique Session ID and a corresponding winlogon.exe process associated with their Session. Now, we mentioned above, the LoaderService runs under the System account. We also confirmed that each winlogon.exe process on the computer runs under the System account. Because the System account is the owner of both the LoaderService and the winlogon.exe processes, our LoaderService can copy the access token (and Session ID) of the winlogon.exe process and then call the Win32 API function CreateProcessAsUser to launch a process into the currently active Session of the logged on User. Since the Session ID located within the access token of the copied winlogon.exe process is greater than 0, we can launch an interactive process using that token.

Try this one. Subverting Vista UAC in Both 32 and 64 bit Architectures

How to get time (hour, minute, second) in Swift 3 using NSDate?

Swift 5+

extension Date {
    
    func get(_ type: Calendar.Component)-> String {
        let calendar = Calendar.current
        let t = calendar.component(type, from: self)
        return (t < 10 ? "0\(t)" : t.description)
    }
}

Usage:

print(Date().get(.year)) // => 2020
print(Date().get(.month)) // => 08
print(Date().get(.day)) // => 18 

How to print a double with two decimals in Android?

yourTextView.setText(String.format("Value of a: %.2f", a));

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

I ran into this problem and try using the flag -noverify which really works. It is because of the new bytecode verifier. So the flag should really work. I am using JDK 1.7.

Note: This would not work if you are using JDK 1.8

How to format a string as a telephone number in C#

 Label12.Text = Convert.ToInt64(reader[6]).ToString("(###) ###-#### ");

This is my example! I hope can help you with this. regards

How do I return clean JSON from a WCF Service?

In your IServece.cs add the following tag : BodyStyle = WebMessageBodyStyle.Bare

 [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "Getperson/{id}")]

    List<personClass> Getperson(string id);

Change R default library path using .libPaths in Rprofile.site fails to work

If you do not have admin-rights, it can also be helpful to open the Rprofile.site-file located in \R-3.1.0\etc and add:

.First <- function(){
  .libPaths("your path here")
}

This evaluates the .libPath() command directly at start

Jenkins could not run git

I had similar problem, the solution for Windows looks the same (my Jenkins is installed on a Windows machine):

Global settings:

Go to Manage jenkins -> Configure System -> Git installations add there the git exe path (for example: C:\Program Files\Git\bin\git.exe), or you can use environment variable.

For Jenkins version 2.121.3, Go to Manage jenkins -> Global tool configuration -> Git installations -> Path to Git executable: C:\Program Files\Git\bin\git.exe

Jenkins job side:

Go to Source code Management -> select git, add your repository, choose connection to repository (http/ssh) and add credentials and it should work.

Get an object's class name at runtime

The full TypeScript code

public getClassName() {
    var funcNameRegex = /function (.{1,})\(/;
    var results  = (funcNameRegex).exec(this["constructor"].toString());
    return (results && results.length > 1) ? results[1] : "";
}

How to echo in PHP, HTML tags

This will also work fine with double quotes. To echo any html_tag with double quotes we just need to remember one thing, Do not use any other double quotes(") in the middle.

<?php
    echo "
    <div>
        <h3><a href='https://stackoverflow.com/questions/3931351/how-to-echo-in-php-html-tags'>First</a></h3>
        <div>Lorem ipsum dolor sit amet.</div>
        </div>
    <div>";
?>

Notice here the link inside the PHP echo is enclosed within the single quotes. This is the precaution you should take while using the double quotes for this purpose.

How do I use two submit buttons, and differentiate between which one was used to submit the form?

Give each input a name attribute. Only the clicked input's name attribute will be sent to the server.

<input type="submit" name="publish" value="Publish">
<input type="submit" name="save" value="Save">

And then

<?php
    if (isset($_POST['publish'])) {
        # Publish-button was clicked
    }
    elseif (isset($_POST['save'])) {
        # Save-button was clicked
    }
?>

Edit: Changed value attributes to alt. Not sure this is the best approach for image buttons though, any particular reason you don't want to use input[type=image]?

Edit: Since this keeps getting upvotes I went ahead and changed the weird alt/value code to real submit inputs. I believe the original question asked for some sort of image buttons but there are so much better ways to achieve that nowadays instead of using input[type=image].

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

From your stack trace, EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) occurred because dispatch_group_t was released while it was still locking (waiting for dispatch_group_leave).

According to what you found, this was what happened :

  • dispatch_group_t group was created. group's retain count = 1.
  • -[self webservice:onCompletion:] captured the group. group's retain count = 2.
  • dispatch_async(...., ^{ dispatch_group_wait(group, ...) ... }); captured the group again. group's retain count = 3.
  • Exit the current scope. group was released. group's retain count = 2.
  • dispatch_group_leave was never called.
  • dispatch_group_wait was timeout. The dispatch_async block was completed. group was released. group's retain count = 1.
  • You called this method again. When -[self webservice:onCompletion:] was called again, the old onCompletion block was replaced with the new one. So, the old group was released. group's retain count = 0. group was deallocated. That resulted to EXC_BAD_INSTRUCTION.

To fix this, I suggest you should find out why -[self webservice:onCompletion:] didn't call onCompletion block, and fix it. Then make sure the next call to the method will happen after the previous call did finish.


In case you allow the method to be called many times whether the previous calls did finish or not, you might find someone to hold group for you :

  • You can change the timeout from 2 seconds to DISPATCH_TIME_FOREVER or a reasonable amount of time that all -[self webservice:onCompletion] should call their onCompletion blocks by the time. So that the block in dispatch_async(...) will hold it for you.
    OR
  • You can add group into a collection, such as NSMutableArray.

I think it is the best approach to create a dedicate class for this action. When you want to make calls to webservice, you then create an object of the class, call the method on it with the completion block passing to it that will release the object. In the class, there is an ivar of dispatch_group_t or dispatch_semaphore_t.

Load a WPF BitmapImage from a System.Drawing.Bitmap

It took me some time to get the conversion working both ways, so here are the two extension methods I came up with:

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Media.Imaging;

public static class BitmapConversion {

    public static Bitmap ToWinFormsBitmap(this BitmapSource bitmapsource) {
        using (MemoryStream stream = new MemoryStream()) {
            BitmapEncoder enc = new BmpBitmapEncoder();
            enc.Frames.Add(BitmapFrame.Create(bitmapsource));
            enc.Save(stream);

            using (var tempBitmap = new Bitmap(stream)) {
                // According to MSDN, one "must keep the stream open for the lifetime of the Bitmap."
                // So we return a copy of the new bitmap, allowing us to dispose both the bitmap and the stream.
                return new Bitmap(tempBitmap);
            }
        }
    }

    public static BitmapSource ToWpfBitmap(this Bitmap bitmap) {
        using (MemoryStream stream = new MemoryStream()) {
            bitmap.Save(stream, ImageFormat.Bmp);

            stream.Position = 0;
            BitmapImage result = new BitmapImage();
            result.BeginInit();
            // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
            // Force the bitmap to load right now so we can dispose the stream.
            result.CacheOption = BitmapCacheOption.OnLoad;
            result.StreamSource = stream;
            result.EndInit();
            result.Freeze();
            return result;
        }
    }
}

Split varchar into separate columns in Oracle

Depends on the consistency of the data - assuming a single space is the separator between what you want to appear in column one vs two:

SELECT SUBSTR(t.column_one, 1, INSTR(t.column_one, ' ')-1) AS col_one,
       SUBSTR(t.column_one, INSTR(t.column_one, ' ')+1) AS col_two
  FROM YOUR_TABLE t

Oracle 10g+ has regex support, allowing more flexibility depending on the situation you need to solve. It also has a regex substring method...

Reference:

nodemon not working: -bash: nodemon: command not found

Put --exec arg in single quotation.

e.g. I changed "nodemon --exec yarn build-langs" to "nodemon --exec 'yarn build-langs'" and worked.

0xC0000005: Access violation reading location 0x00000000

The problem here, as explained in other comments, is that the pointer is being dereference without being properly initialized. Operating systems like Linux keep the lowest addresses (eg first 32MB: 0x00_0000 -0x200_0000) out of the virtual address space of a process. This is done because dereferencing zeroed non-initialized pointers is a common mistake, like in this case. So when this type of mistake happens, instead of actually reading a random variable that happens to be at address 0x0 (but not the memory address the pointer would be intended for if initialized properly), the pointer would be reading from a memory address outside of the process's virtual address space. This causes a page fault, which results in a segmentation fault, and a signal is sent to the process to kill it. That's why you are getting the access violation error.

Setting up JUnit with IntelliJ IDEA

I needed to enable the JUnit plugin, after I linked my project with the jar files.

To enable the JUnit plugin, go to File->Settings, type "JUnit" in the search bar, and under "Plugins," check "JUnit.

vikingsteve's advice above will probably get the libraries linked right. Otherwise, open File->Project Structure, go to Libraries, hit the plus, and then browse to

C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 14.1.1\lib\

and add these jar files:

hamcrest-core-1.3.jar
junit-4.11.jar 
junit.jar 

Update div with jQuery ajax response html

You are setting the html of #showresults of whatever data is, and then replacing it with itself, which doesn't make much sense ?
I'm guessing you where really trying to find #showresults in the returned data, and then update the #showresults element in the DOM with the html from the one from the ajax call :

$('#submitform').click(function () {
    $.ajax({
        url: "getinfo.asp",
        data: {
            txtsearch: $('#appendedInputButton').val()
        },
        type: "GET",
        dataType: "html",
        success: function (data) {
            var result = $('<div />').append(data).find('#showresults').html();
            $('#showresults').html(result);
        },
        error: function (xhr, status) {
            alert("Sorry, there was a problem!");
        },
        complete: function (xhr, status) {
            //$('#showresults').slideDown('slow')
        }
    });
});

Call async/await functions in parallel

TL;DR

Use Promise.all for the parallel function calls, the answer behaviors not correctly when the error occurs.


First, execute all the asynchronous calls at once and obtain all the Promise objects. Second, use await on the Promise objects. This way, while you wait for the first Promise to resolve the other asynchronous calls are still progressing. Overall, you will only wait for as long as the slowest asynchronous call. For example:

// Begin first call and store promise without waiting
const someResult = someCall();

// Begin second call and store promise without waiting
const anotherResult = anotherCall();

// Now we await for both results, whose async processes have already been started
const finalResult = [await someResult, await anotherResult];

// At this point all calls have been resolved
// Now when accessing someResult| anotherResult,
// you will have a value instead of a promise

JSbin example: http://jsbin.com/xerifanima/edit?js,console

Caveat: It doesn't matter if the await calls are on the same line or on different lines, so long as the first await call happens after all of the asynchronous calls. See JohnnyHK's comment.


Update: this answer has a different timing in error handling according to the @bergi's answer, it does NOT throw out the error as the error occurs but after all the promises are executed. I compare the result with @jonny's tip: [result1, result2] = Promise.all([async1(), async2()]), check the following code snippet

_x000D_
_x000D_
const correctAsync500ms = () => {_x000D_
  return new Promise(resolve => {_x000D_
    setTimeout(resolve, 500, 'correct500msResult');_x000D_
  });_x000D_
};_x000D_
_x000D_
const correctAsync100ms = () => {_x000D_
  return new Promise(resolve => {_x000D_
    setTimeout(resolve, 100, 'correct100msResult');_x000D_
  });_x000D_
};_x000D_
_x000D_
const rejectAsync100ms = () => {_x000D_
  return new Promise((resolve, reject) => {_x000D_
    setTimeout(reject, 100, 'reject100msError');_x000D_
  });_x000D_
};_x000D_
_x000D_
const asyncInArray = async (fun1, fun2) => {_x000D_
  const label = 'test async functions in array';_x000D_
  try {_x000D_
    console.time(label);_x000D_
    const p1 = fun1();_x000D_
    const p2 = fun2();_x000D_
    const result = [await p1, await p2];_x000D_
    console.timeEnd(label);_x000D_
  } catch (e) {_x000D_
    console.error('error is', e);_x000D_
    console.timeEnd(label);_x000D_
  }_x000D_
};_x000D_
_x000D_
const asyncInPromiseAll = async (fun1, fun2) => {_x000D_
  const label = 'test async functions with Promise.all';_x000D_
  try {_x000D_
    console.time(label);_x000D_
    let [value1, value2] = await Promise.all([fun1(), fun2()]);_x000D_
    console.timeEnd(label);_x000D_
  } catch (e) {_x000D_
    console.error('error is', e);_x000D_
    console.timeEnd(label);_x000D_
  }_x000D_
};_x000D_
_x000D_
(async () => {_x000D_
  console.group('async functions without error');_x000D_
  console.log('async functions without error: start')_x000D_
  await asyncInArray(correctAsync500ms, correctAsync100ms);_x000D_
  await asyncInPromiseAll(correctAsync500ms, correctAsync100ms);_x000D_
  console.groupEnd();_x000D_
_x000D_
  console.group('async functions with error');_x000D_
  console.log('async functions with error: start')_x000D_
  await asyncInArray(correctAsync500ms, rejectAsync100ms);_x000D_
  await asyncInPromiseAll(correctAsync500ms, rejectAsync100ms);_x000D_
  console.groupEnd();_x000D_
})();
_x000D_
_x000D_
_x000D_

Moq, SetupGet, Mocking a property

ColumnNames is a property of type List<String> so when you are setting up you need to pass a List<String> in the Returns call as an argument (or a func which return a List<String>)

But with this line you are trying to return just a string

input.SetupGet(x => x.ColumnNames).Returns(temp[0]);

which is causing the exception.

Change it to return whole list:

input.SetupGet(x => x.ColumnNames).Returns(temp);

Java int to String - Integer.toString(i) vs new Integer(i).toString()

Here Integer.toString calls the static method in the class Integer. It does not require the object to call.

If you call new Integer(i) you first create an instance of type Integer, which is a full Java object encapsulating the value of your int i. Then you call the toString method on it to ask it to return a string representation of itself.

How to truncate float values?

use numpy.round

import numpy as np
precision = 3
floats = [1.123123123, 2.321321321321]
new_float = np.round(floats, precision)

Empty set literal?

There are few ways to create empty Set in Python :

  1. Using set() method
    This is the built-in method in python that creates Empty set in that variable.
  2. Using clear() method (creative Engineer Technique LOL)
    See this Example:

    sets={"Hi","How","are","You","All"}
    type(sets)  (This Line Output : set)
    sets.clear()
    print(sets)  (This Line Output : {})
    type(sets)  (This Line Output : set)

So, This are 2 ways to create empty Set.

Vertical alignment of text and icon in button

There is one rule that is set by font-awesome.css, which you need to override.

You should set overrides in your CSS files rather than inline, but essentially, the icon-ok class is being set to vertical-align: baseline; by default and which I've corrected here:

<button id="whatever" class="btn btn-large btn-primary" name="Continue" type="submit">
    <span>Continue</span>
    <i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>

Example here: http://jsfiddle.net/fPXFY/4/ and the output of which is:

enter image description here

I've downsized the font-size of the icon above in this instance to 30px, as it feels too big at 40px for the size of the button, but this is purely a personal viewpoint. You could increase the padding on the button to compensate if required:

<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">
    <span>Continue</span>
    <i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>

Producing: http://jsfiddle.net/fPXFY/5/ the output of which is:

enter image description here

javax.naming.NoInitialContextException - Java

If working on EJB client library:

You need to mention the argument for getting the initial context.

InitialContext ctx = new InitialContext();

If you do not, it will look in the project folder for properties file. Also you can include the properties credentials or values in your class file itself as follows:

Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
props.put(Context.PROVIDER_URL, "jnp://localhost:1099");

InitialContext ctx = new InitialContext(props);

URL_PKG_PREFIXES: Constant that holds the name of the environment property for specifying the list of package prefixes to use when loading in URL context factories.

The EJB client library is the primary library to invoke remote EJB components.
This library can be used through the InitialContext. To invoke EJB components the library creates an EJB client context via a URL context factory. The only necessary configuration is to parse the value org.jboss.ejb.client.naming for the java.naming.factory.url.pkgs property to instantiate an InitialContext.

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

This may not be the best answer for the above question, but the problem of mine was invalid dispose syntax and usage of lock(this) for a buffer object. It turned out the object was getting disposed from another thread because of "using" syntax. And the processing lock() was on a loose type.

// wrong lock syntax
lock(this) {
    // modify buffer object
}

I changed the locks to

private static readonly object _lockObject = new object();

lock(_lockObject) {
    // modify buffer object
}

And used suggested C# disposing syntax and the problem gone.

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposed)
            return;

        if (disposing)
        {
            // Free any managed objects here
            buffer?.Free();
        }

        disposed = true;
    }

How to print something to the console in Xcode?

@Logan said it perfectly. but i would like to add an alternative here,

if you want to view logs from just your application then you can make a custom method that keeps saving the log to a file in documents directory & then you can view that log file from your application.

There is one good advantage for developers of the app after the app has been released & users are downloading it. Because your app will be able to send logs & crash reports to the developers (of course with the permissions of the device user !!!) & it'll be the way to improve your application.

Let me know (To other SO users), if there is another way of doing the same thing. (Like default Apple feature or something)

Let me know if it helps or you want some more idea.

CSS hide scroll bar, but have element scrollable

I combined a couple of different answers in SO into the following snippet, which should work on all, if not most, modern browsers I believe. All you have to do is add the CSS class .disable-scrollbars onto the element you wish to apply this to.

.disable-scrollbars::-webkit-scrollbar {
    width: 0px;
    background: transparent; /* Chrome/Safari/Webkit */
}

.disable-scrollbars {
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none;  /* IE 10+ */
}

And if you want to use SCSS/SASS:

.disable-scrollbars {
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none;  /* IE 10+ */
  &::-webkit-scrollbar {
    width: 0px;
    background: transparent; /* Chrome/Safari/Webkit */
  }
}

Add Marker function with Google Maps API

Below code works for me:

<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
    var myCenter = new google.maps.LatLng(51.528308, -0.3817765);

    function initialize() {
           var mapProp = {
            center:myCenter,
            zoom:15,
            mapTypeId:google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("googleMap"), mapProp); 

        var marker = new google.maps.Marker({
            position: myCenter,
            icon: {
                url: '/images/marker.png',
                size: new google.maps.Size(70, 86), //marker image size
                origin: new google.maps.Point(0, 0), // marker origin
                anchor: new google.maps.Point(35, 86) // X-axis value (35, half of marker width) and 86 is Y-axis value (height of the marker).
            }
        });

        marker.setMap(map);

        }
        google.maps.event.addDomListener(window, 'load', initialize);

</script>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>

Reference link

Add Keypair to existing EC2 instance

You can't apply a keypair to a running instance. You can only use the new keypair to launch a new instance.

For recovery, if it's an EBS boot AMI, you can stop it, make a snapshot of the volume. Create a new volume based on it. And be able to use it back to start the old instance, create a new image, or recover data.

Though data at ephemeral storage will be lost.


Due to the popularity of this question and answer, I wanted to capture the information in the link that Rodney posted on his comment.

Credit goes to Eric Hammond for this information.

Fixing Files on the Root EBS Volume of an EC2 Instance

You can examine and edit files on the root EBS volume on an EC2 instance even if you are in what you considered a disastrous situation like:

  • You lost your ssh key or forgot your password
  • You made a mistake editing the /etc/sudoers file and can no longer gain root access with sudo to fix it
  • Your long running instance is hung for some reason, cannot be contacted, and fails to boot properly
  • You need to recover files off of the instance but cannot get to it

On a physical computer sitting at your desk, you could simply boot the system with a CD or USB stick, mount the hard drive, check out and fix the files, then reboot the computer to be back in business.

A remote EC2 instance, however, seems distant and inaccessible when you are in one of these situations. Fortunately, AWS provides us with the power and flexibility to be able to recover a system like this, provided that we are running EBS boot instances and not instance-store.

The approach on EC2 is somewhat similar to the physical solution, but we’re going to move and mount the faulty “hard drive” (root EBS volume) to a different instance, fix it, then move it back.

In some situations, it might simply be easier to start a new EC2 instance and throw away the bad one, but if you really want to fix your files, here is the approach that has worked for many:

Setup

Identify the original instance (A) and volume that contains the broken root EBS volume with the files you want to view and edit.

instance_a=i-XXXXXXXX

volume=$(ec2-describe-instances $instance_a |
  egrep '^BLOCKDEVICE./dev/sda1' | cut -f3)

Identify the second EC2 instance (B) that you will use to fix the files on the original EBS volume. This instance must be running in the same availability zone as instance A so that it can have the EBS volume attached to it. If you don’t have an instance already running, start a temporary one.

instance_b=i-YYYYYYYY

Stop the broken instance A (waiting for it to come to a complete stop), detach the root EBS volume from the instance (waiting for it to be detached), then attach the volume to instance B on an unused device.

ec2-stop-instances $instance_a
ec2-detach-volume $volume
ec2-attach-volume --instance $instance_b --device /dev/sdj $volume

ssh to instance B and mount the volume so that you can access its file system.

ssh ...instance b...

sudo mkdir -p 000 /vol-a
sudo mount /dev/sdj /vol-a

Fix It

At this point your entire root file system from instance A is available for viewing and editing under /vol-a on instance B. For example, you may want to:

  • Put the correct ssh keys in /vol-a/home/ubuntu/.ssh/authorized_keys
  • Edit and fix /vol-a/etc/sudoers
  • Look for error messages in /vol-a/var/log/syslog
  • Copy important files out of /vol-a/…

Note: The uids on the two instances may not be identical, so take care if you are creating, editing, or copying files that belong to non-root users. For example, your mysql user on instance A may have the same UID as your postfix user on instance B which could cause problems if you chown files with one name and then move the volume back to A.

Wrap Up

After you are done and you are happy with the files under /vol-a, unmount the file system (still on instance-B):

sudo umount /vol-a
sudo rmdir /vol-a

Now, back on your system with ec2-api-tools, continue moving the EBS volume back to it’s home on the original instance A and start the instance again:

ec2-detach-volume $volume
ec2-attach-volume --instance $instance_a --device /dev/sda1 $volume
ec2-start-instances $instance_a

Hopefully, you fixed the problem, instance A comes up just fine, and you can accomplish what you originally set out to do. If not, you may need to continue repeating these steps until you have it working.

Note: If you had an Elastic IP address assigned to instance A when you stopped it, you’ll need to reassociate it after starting it up again.

Remember! If your instance B was temporarily started just for this process, don’t forget to terminate it now.

Insert data into table with result from another select query

If table_2 is empty, then try the following insert statement:

insert into table_2 (itemid,location1) 
select itemid,quantity from table_1 where locationid=1

If table_2 already contains the itemid values, then try this update statement:

update table_2 set location1=
(select quantity from table_1 where locationid=1 and table_1.itemid = table_2.itemid)

Given a URL to a text file, what is the simplest way to read the contents of the text file?

Another way in Python 3 is to use the urllib3 package.

import urllib3

http = urllib3.PoolManager()
response = http.request('GET', target_url)
data = response.data.decode('utf-8')

This can be a better option than urllib since urllib3 boasts having

  • Thread safety.
  • Connection pooling.
  • Client-side SSL/TLS verification.
  • File uploads with multipart encoding.
  • Helpers for retrying requests and dealing with HTTP redirects.
  • Support for gzip and deflate encoding.
  • Proxy support for HTTP and SOCKS.
  • 100% test coverage.

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

How do I stop Notepad++ from showing autocomplete for all words in the file

Notepad++ provides 2 types of features:

  • Auto-completion that read the open file and provide suggestion of words and/or functions within the file
  • Suggestion with the arguments of functions (specific to the language)

Based on what you write, it seems what you want is auto-completion on function only + suggestion on arguments.

To do that, you just need to change a setting.

  1. Go to Settings > Preferences... > Auto-completion
  2. Check Enable Auto-completion on each input
  3. Select Function completion and not Word completion
  4. Check Function parameter hint on input (if you have this option)

On version 6.5.5 of Notepad++, I have this setting settings

Some documentation about auto-completion is available in Notepad++ Wiki.

Javascript onHover event

How about something like this?

<html>
<head>
<script type="text/javascript">

var HoverListener = {
  addElem: function( elem, callback, delay )
  {
    if ( delay === undefined )
    {
      delay = 1000;
    }

    var hoverTimer;

    addEvent( elem, 'mouseover', function()
    {
      hoverTimer = setTimeout( callback, delay );
    } );

    addEvent( elem, 'mouseout', function()
    {
      clearTimeout( hoverTimer );
    } );
  }
}

function tester()
{
  alert( 'hi' );
}

//  Generic event abstractor
function addEvent( obj, evt, fn )
{
  if ( 'undefined' != typeof obj.addEventListener )
  {
    obj.addEventListener( evt, fn, false );
  }
  else if ( 'undefined' != typeof obj.attachEvent )
  {
    obj.attachEvent( "on" + evt, fn );
  }
}

addEvent( window, 'load', function()
{
  HoverListener.addElem(
      document.getElementById( 'test' )
    , tester 
  );
  HoverListener.addElem(
      document.getElementById( 'test2' )
    , function()
      {
        alert( 'Hello World!' );
      }
    , 2300
  );
} );

</script>
</head>
<body>
<div id="test">Will alert "hi" on hover after one second</div>
<div id="test2">Will alert "Hello World!" on hover 2.3 seconds</div>
</body>
</html>

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

The operation is not allowed in chrome. You can either use a HTTP server(Tomcat) or you use Firefox instead.

How to add item to the beginning of List<T>?

Update: a better idea, set the "AppendDataBoundItems" property to true, then declare the "Choose item" declaratively. The databinding operation will add to the statically declared item.

<asp:DropDownList ID="ddl" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Value="0" Text="Please choose..."></asp:ListItem>
</asp:DropDownList>

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.appenddatabounditems.aspx

-Oisin

How to Set the Background Color of a JButton on the Mac OS

Have you tried setting the painted border false?

JButton button = new JButton();
button.setBackground(Color.red);
button.setOpaque(true);
button.setBorderPainted(false);

It works on my mac :)

Finding Key associated with max Value in a Java Map

given map

HashMap abc = new HashMap<>();

get all map entries with a maximum of values.

you can use any of the below methods in the filter to get respective map entries for sets of minimum or maximum values

Collections.max(abc.values())
Collections.min(abc.values())
Collections.max(abc.keys())
Collections.max(abc.keys())

abc.entrySet().stream().filter(entry -> entry.getValue() == Collections.max(abc.values()))

if only want to get the keys for the filter map

abc.entrySet()
       .stream()
       .filter(entry -> entry.getValue() == Collections.max(abc.values()))
       .map(Map.Entry::getKey);

if you want to get the values for the filtered map

abc.entrySet()
      .stream()
      .filter(entry -> entry.getValue() == Collections.max(abc.values()))
      .map(Map.Entry::getvalue)

if you want to get all such keys in a list:

abc.entrySet()
  .stream()
  .filter(entry -> entry.getValue() == Collections.max(abc.values()))
  .map(Map.Entry::getKey)
  .collect(Collectors.toList())

if you want to get all such values in a list:

abc.entrySet()
  .stream()
  .filter(entry -> entry.getValue() == Collections.max(abc.values()))
  .map(Map.Entry::getvalue)
  .collect(Collectors.toList())

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

I am using JUnit 4, and what worked for me is changing the IntelliJ settings for 'Gradle -> Run Tests Using' from 'Gradle (default)' to 'IntelliJ IDEA'.

enter image description here

Source of my fix: https://linked2ev.github.io/devsub/2019/09/30/Intellij-junit4-gradle-issue/

Purpose of Unions in C and C++

Technically it's undefined, but in reality most (all?) compilers treat it exactly the same as using a reinterpret_cast from one type to the other, the result of which is implementation defined. I wouldn't lose sleep over your current code.

how to implement Pagination in reactJs

I have tried to recreate the simple pagination example given by piotr-berebecki which was great. But when there will be a lot of pages then the pagination will overflow in the screen. So, I used previous and back button along with forward and backward button to stream back and forth between the pages. And for design part I have used bootstrap 3.

You can customize no of pages to display in pagination using the pagebound values. Make sure to use same value for upperPageBound and pageBound.

    class TodoApp extends React.Component {
          constructor() {
            super();
            this.state = {
              todos: ['a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z'],
              currentPage: 1,
              todosPerPage: 3,
              upperPageBound: 3,
              lowerPageBound: 0,
              isPrevBtnActive: 'disabled',
              isNextBtnActive: '',
              pageBound: 3
            };
            this.handleClick = this.handleClick.bind(this);
            this.btnDecrementClick = this.btnDecrementClick.bind(this);
            this.btnIncrementClick = this.btnIncrementClick.bind(this);
            this.btnNextClick = this.btnNextClick.bind(this);
            this.btnPrevClick = this.btnPrevClick.bind(this);
            // this.componentDidMount = this.componentDidMount.bind(this);
            this.setPrevAndNextBtnClass = this.setPrevAndNextBtnClass.bind(this);
          }
          componentDidUpdate() {
                $("ul li.active").removeClass('active');
                $('ul li#'+this.state.currentPage).addClass('active');
          }
          handleClick(event) {
            let listid = Number(event.target.id);
            this.setState({
              currentPage: listid
            });
            $("ul li.active").removeClass('active');
            $('ul li#'+listid).addClass('active');
            this.setPrevAndNextBtnClass(listid);
          }
          setPrevAndNextBtnClass(listid) {
            let totalPage = Math.ceil(this.state.todos.length / this.state.todosPerPage);
            this.setState({isNextBtnActive: 'disabled'});
            this.setState({isPrevBtnActive: 'disabled'});
            if(totalPage === listid && totalPage > 1){
                this.setState({isPrevBtnActive: ''});
            }
            else if(listid === 1 && totalPage > 1){
                this.setState({isNextBtnActive: ''});
            }
            else if(totalPage > 1){
                this.setState({isNextBtnActive: ''});
                this.setState({isPrevBtnActive: ''});
            }
        }
          btnIncrementClick() {
              this.setState({upperPageBound: this.state.upperPageBound + this.state.pageBound});
              this.setState({lowerPageBound: this.state.lowerPageBound + this.state.pageBound});
              let listid = this.state.upperPageBound + 1;
              this.setState({ currentPage: listid});
              this.setPrevAndNextBtnClass(listid);
        }
          btnDecrementClick() {
            this.setState({upperPageBound: this.state.upperPageBound - this.state.pageBound});
            this.setState({lowerPageBound: this.state.lowerPageBound - this.state.pageBound});
            let listid = this.state.upperPageBound - this.state.pageBound;
            this.setState({ currentPage: listid});
            this.setPrevAndNextBtnClass(listid);
        }
        btnPrevClick() {
            if((this.state.currentPage -1)%this.state.pageBound === 0 ){
                this.setState({upperPageBound: this.state.upperPageBound - this.state.pageBound});
                this.setState({lowerPageBound: this.state.lowerPageBound - this.state.pageBound});
            }
            let listid = this.state.currentPage - 1;
            this.setState({ currentPage : listid});
            this.setPrevAndNextBtnClass(listid);
        }
        btnNextClick() {
            if((this.state.currentPage +1) > this.state.upperPageBound ){
                this.setState({upperPageBound: this.state.upperPageBound + this.state.pageBound});
                this.setState({lowerPageBound: this.state.lowerPageBound + this.state.pageBound});
            }
            let listid = this.state.currentPage + 1;
            this.setState({ currentPage : listid});
            this.setPrevAndNextBtnClass(listid);
        }
          render() {
            const { todos, currentPage, todosPerPage,upperPageBound,lowerPageBound,isPrevBtnActive,isNextBtnActive } = this.state;
            // Logic for displaying current todos
            const indexOfLastTodo = currentPage * todosPerPage;
            const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
            const currentTodos = todos.slice(indexOfFirstTodo, indexOfLastTodo);

            const renderTodos = currentTodos.map((todo, index) => {
              return <li key={index}>{todo}</li>;
            });

            // Logic for displaying page numbers
            const pageNumbers = [];
            for (let i = 1; i <= Math.ceil(todos.length / todosPerPage); i++) {
              pageNumbers.push(i);
            }

            const renderPageNumbers = pageNumbers.map(number => {
                if(number === 1 && currentPage === 1){
                    return(
                        <li key={number} className='active' id={number}><a href='#' id={number} onClick={this.handleClick}>{number}</a></li>
                    )
                }
                else if((number < upperPageBound + 1) && number > lowerPageBound){
                    return(
                        <li key={number} id={number}><a href='#' id={number} onClick={this.handleClick}>{number}</a></li>
                    )
                }
            });
            let pageIncrementBtn = null;
            if(pageNumbers.length > upperPageBound){
                pageIncrementBtn = <li className=''><a href='#' onClick={this.btnIncrementClick}> &hellip; </a></li>
            }
            let pageDecrementBtn = null;
            if(lowerPageBound >= 1){
                pageDecrementBtn = <li className=''><a href='#' onClick={this.btnDecrementClick}> &hellip; </a></li>
            }
            let renderPrevBtn = null;
            if(isPrevBtnActive === 'disabled') {
                renderPrevBtn = <li className={isPrevBtnActive}><span id="btnPrev"> Prev </span></li>
            }
            else{
                renderPrevBtn = <li className={isPrevBtnActive}><a href='#' id="btnPrev" onClick={this.btnPrevClick}> Prev </a></li>
            }
            let renderNextBtn = null;
            if(isNextBtnActive === 'disabled') {
                renderNextBtn = <li className={isNextBtnActive}><span id="btnNext"> Next </span></li>
            }
            else{
                renderNextBtn = <li className={isNextBtnActive}><a href='#' id="btnNext" onClick={this.btnNextClick}> Next </a></li>
            }
            return (
              <div>
                  <ul>
                  {renderTodos}
                </ul>
                <ul id="page-numbers" className="pagination">
                  {renderPrevBtn}
                  {pageDecrementBtn}
                  {renderPageNumbers}
                  {pageIncrementBtn}
                  {renderNextBtn}
                </ul>
              </div>
            );
          }
        }


        ReactDOM.render(
          <TodoApp />,
          document.getElementById('app')
        );

Working demo link : https://codepen.io/mhmanandhar/pen/oEWBqx

Image : simple react pagination

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

Based on this Connect feedback I fixed it by closing all opened documents and restarting Visual Studio. I use Visual Studio 2015.

What is function overloading and overriding in php?

Strictly speaking, there's no difference, since you cannot do either :)

Function overriding could have been done with a PHP extension like APD, but it's deprecated and afaik last version was unusable.

Function overloading in PHP cannot be done due to dynamic typing, ie, in PHP you don't "define" variables to be a particular type. Example:

$a=1;
$a='1';
$a=true;
$a=doSomething();

Each variable is of a different type, yet you can know the type before execution (see the 4th one). As a comparison, other languages use:

int a=1;
String s="1";
bool a=true;
something a=doSomething();

In the last example, you must forcefully set the variable's type (as an example, I used data type "something").


Another "issue" why function overloading is not possible in PHP: PHP has a function called func_get_args(), which returns an array of current arguments, now consider the following code:

function hello($a){
  print_r(func_get_args());
}

function hello($a,$a){
  print_r(func_get_args());
}

hello('a');
hello('a','b');

Considering both functions accept any amount of arguments, which one should the compiler choose?


Finally, I'd like to point out why the above replies are partially wrong; function overloading/overriding is NOT equal to method overloading/overriding.

Where a method is like a function but specific to a class, in which case, PHP does allow overriding in classes, but again no overloading, due to language semantics.

To conclude, languages like Javascript allow overriding (but again, no overloading), however they may also show the difference between overriding a user function and a method:

/// Function Overriding ///

function a(){
   alert('a');
}
a=function(){
   alert('b');
}

a(); // shows popup with 'b'


/// Method Overriding ///

var a={
  "a":function(){
    alert('a');
  }
}
a.a=function(){
   alert('b');
}

a.a(); // shows popup with 'b'

How to store directory files listing into an array?

Here's a variant that lets you use a regex pattern for initial filtering, change the regex to be get the filtering you desire.

files=($(find -E . -type f -regex "^.*$"))
for item in ${files[*]}
do
  printf "   %s\n" $item
done

Sum values from an array of key-value pairs in JavaScript

Or in ES6

values.reduce((a, b) => a + b),

example:

[1,2,3].reduce((a, b)=>a+b) // return 6

Recommendation for compressing JPG files with ImageMagick

Once I needed to resize photos from camera for developing:

  • Original filesize: 2800 kB
  • Resolution: 3264x2448

Command:

mogrify -quality "97%" -resize 2048x2048 -filter Lanczos -interlace Plane -gaussian-blur 0.05 
  • Result filesize 753 kB
  • Resolution 2048x2048

and I can't see any changes in full screen with my 1920x1080 resolution monitor. 2048 resolution is the best for developing 10 cm photos at maximum quality of 360 dpi. I don't want to strip it.

edit: I noticed that I even get much better results without blurring. Without blurring filesize is 50% of original, but quality is better (when zooming).

UIButton: set image for selected-highlighted state

If you have a good reason to do that, this will do the trick

add these targets:

[button addTarget:self action:@selector(buttonTouchDown:) forControlEvents:UIControlEventTouchDown];
[button addTarget:self action:@selector(buttonTouchUp:) forControlEvents:UIControlEventTouchUpInside];


-(void)buttonTouchDown:(id)sender{
    UIButton *button=(UIButton *)sender;
    if(button.selected){
        [button setImage:[UIImage imageNamed:@"pressed.png"] forState:UIControlStateNormal];
    }
}

-(void)buttonTouchUp:(id)sender{
    UIButton *button=(UIButton *)sender;
    [button setImage:[UIImage imageNamed:@"normal.png"] forState:UIControlStateNormal];
}

How do I import other TypeScript files?

Quick Easy Process in Visual Studio

Drag and Drop the file with .ts extension from solution window to editor, it will generate inline reference code like..

/// <reference path="../../components/someclass.ts"/>

How to obtain the number of CPUs/cores in Linux from the command line?

Use below query to get core details

[oracle@orahost](TESTDB)$ grep -c ^processor /proc/cpuinfo
8

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

Understanding unique keys for array children in React.js

var TableRowItem = React.createClass({
  render: function() {

    var td = function() {
        return this.props.columns.map(function(c, i) {
          return <td key={i}>{this.props.data[c]}</td>;
        }, this);
      }.bind(this);

    return (
      <tr>{ td(this.props.item) }</tr>
    )
  }
});

This will sove the problem.

Can two Java methods have same name with different return types?

Only if their parameter declarations are different from memory.

IE8 support for CSS Media Query

IE didn't add media query support until IE9. So with IE8 you're out of luck.

DataGridView.Clear()

dataGridView1.DataSource=null;

JFrame Maximize window

i like this version:

import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.Toolkit;
import javax.swing.JFrame;

public class Test
{
    public static void main(String [] args)
    {
        final JFrame frame = new JFrame();
        final GraphicsConfiguration config = frame.getGraphicsConfiguration();

        final int left = Toolkit.getDefaultToolkit().getScreenInsets(config).left;
        final int right = Toolkit.getDefaultToolkit().getScreenInsets(config).right;
        final int top = Toolkit.getDefaultToolkit().getScreenInsets(config).top;
        final int bottom = Toolkit.getDefaultToolkit().getScreenInsets(config).bottom;

        final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        final int width = screenSize.width - left - right;
        final int height = screenSize.height - top - bottom;

        frame.setResizable(false);
        frame.setSize(width,height);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       
        frame.setVisible(true);
    }
}

Composer: The requested PHP extension ext-intl * is missing from your system

Just uncomment this line (to find it, simply search this line in editor):

;extension=php_sockets.dll

(Remove semicolon to uncomment)

For me, no need to restart XAMPP (in your case, WAMP). But if didn't work, restart it.

How to compile and run C files from within Notepad++ using NppExec plugin?

Here's a procedure for Perl, just adapt it for C. Hope it helps.

  • Open Notepad++
  • Type F6 to open the execute window
  • Write the following commands:
    • npp_save <-- Saves the current document
    • CD $(CURRENT_DIRECTORY) <-- Moves to the current directory
    • perl.exe -c -w "$(FILE_NAME)" <-- executes the command perl.exe -c -w , example: perl.exe -c -w test.pl (-c = compile -w = warnings)
  • Click on Save
  • Type a name to save the script (e.g. "Perl Compile")
  • Go to Menu Plugins -> Nppexec -> advanced options -> Menu Item (Note: this is right BELOW 'Menu Items *')
  • In the combobox titled 'Associated Script' select the script recently created in its dropdown menu, select Add/Modify and click OK -> OK
  • Restart Notepad++
  • Go to Settings -> Shortcut mapper -> Plugins -> search for the script name
  • Select the shortcut to use (ie Ctrl + 1), click OK
  • Verify that you can now run the script created with the shortcut selected.

How can I get the class name from a C++ object?

To get class name without mangling stuff you can use func macro in constructor:

class MyClass {
    const char* name;
    MyClass() {
        name = __func__;
    }
}

"Cross origin requests are only supported for HTTP." error when loading a local file

I have also been able to recreate this error message when using an anchor tag with the following href:

_x000D_
_x000D_
<a href="javascript:">Example a tag</a>
_x000D_
_x000D_
_x000D_

In my case an a tag was being used to get the 'Pointer Cursor' and the event was actually controlled by some jQuery on click event. I removed the href and added a class that applies:

_x000D_
_x000D_
cursor:pointer;
_x000D_
_x000D_
_x000D_

How to debug PDO database queries?

Sure you can debug using this mode {{ PDO::ATTR_ERRMODE }} Just add new line before your query then you will show the debug lines.

$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$db->query('SELECT *******');  

failed to open stream: HTTP wrapper does not support writeable connections

Instead of doing file_put_contents(***WebSiteURL***...) you need to use the server path to /cache/lang/file.php (e.g. /home/content/site/folders/filename.php).

You cannot open a file over HTTP and expect it to be written. Instead you need to open it using the local path.

using favicon with css

There is no explicit way to change the favicon globally using CSS that I know of. But you can use a simple trick to change it on the fly.

First just name, or rename, the favicon to "favicon.ico" or something similar that will be easy to remember, or is relevant for the site you're working on. Then add the link to the favicon in the head as you usually would. Then when you drop in a new favicon just make sure it's in the same directory as the old one, and that it has the same name, and there you go!

It's not a very elegant solution, and it requires some effort. But dropping in a new favicon in one place is far easier than doing a find and replace of all the links, or worse, changing them manually. At least this way doesn't involve messing with the code.

Of course dropping in a new favicon with the same name will delete the old one, so make sure to backup the old favicon in case of disaster, or if you ever want to go back to the old design.

How do I define a method in Razor?

Leaving alone any debates over when (if ever) it should be done, @functions is how you do it.

@functions {

    // Add code here.

}

pandas GroupBy columns with NaN (missing) values

Ancient topic, if someone still stumbles over this--another workaround is to convert via .astype(str) to string before grouping. That will conserve the NaN's.

df = pd.DataFrame({'a': ['1', '2', '3'], 'b': ['4', np.NaN, '6']})
df['b'] = df['b'].astype(str)
df.groupby(['b']).sum()
    a
b   
4   1
6   3
nan 2

How to list all the files in a commit?

I use this to get list of changed files in merge commit

? git log -m -1 --name-only --pretty="format:"
configs/anotherconfig.xml
configs/configsInRepo.xml

or

? git log -m -1 --name-status --pretty="format:"
A       configs/anotherconfig.xml
M       configs/configsInRepo.xml

Checking if element exists with Python Selenium

a)

from selenium.common.exceptions import NoSuchElementException        
def check_exists_by_xpath(xpath):
    try:
        webdriver.find_element_by_xpath(xpath)
    except NoSuchElementException:
        return False
    return True

b) use xpath - the most reliable. Moreover you can take the xpath as a standard throughout all your scripts and create functions as above mentions for universal use.

UPDATE: I wrote the initial answer over 4 years ago and at the time I thought xpath would be the best option. Now I recommend to use css selectors. I still recommend not to mix/use "by id", "by name" and etc and use one single approach instead.

Proper way to rename solution (and directories) in Visual Studio

To rename a website:

http://www.c-sharpcorner.com/Blogs/46334/rename-website-project-in-visual-studio-2013.aspx

locate and edit IISExpress's applicationhost.config, found here: C:\Users{username}\Documents\IISExpress\config

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Laravel 5 – Remove Public from URL

Here is the Best and shortest solution that works for me as of may, 2018 for Laravel 5.5

  1. just cut your .htaccess file from the /public directory to the root directory and replace it content with the following code:

    <IfModule mod_rewrite.c>
        <IfModule mod_negotiation.c>
           Options -MultiViews
        </IfModule>
    
        RewriteEngine On
    
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)/$ /$1 [L,R=301]
    
        RewriteCond %{REQUEST_URI} !(\.css|\.js|\.png|\.jpg|\.gif|robots\.txt)$ [NC]
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ server.php [L]
    
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_URI} !^/public/
        RewriteRule ^(css|js|images)/(.*)$ public/$1/$2 [L,NC]
    </IfModule>
    
  2. Just save the .htaccess file and that is all.

  3. Rename your server.php file to index.php. that is all enjoy!

How to delete a module in Android Studio

Assuming the following:

  • You are working with Android Studio 1.2.1 or 1.2.2 (I don't have the latest yet, will edit this again when I do).
  • Your Project Tool Window is displaying one of the following views: "Project", "Packages", "Android" or "Project Files"

You can delete an Android Studio module as follows:

  1. In the Project Tool Window click the module you want to delete.
  2. Between the Tool Bar and the Project Tool Window the tool bar you will see two "chips" that represent the path to the selected module, similar to: your-project-name > selected-module-name
  3. Right click on the selected-module-name chip. A context menu with multiple sections will appear. In the third section from the bottom there will be a section that contains "Reformat Code..", "Optimize Imports..." and "Delete".
  4. Select "Delete" and follow any prompts.

Android + Pair devices via bluetooth programmatically

if you have the BluetoothDevice object you can create bond(pair) from api 19 onwards with bluetoothDevice.createBond() method.

Edit

for callback, if the request was accepted or denied you will have to create a BroadcastReceiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED action

jQuery Set Selected Option Using Next

$('option:selected', 'select').removeAttr('selected').next('option').attr('selected', 'selected');

Check out working code here http://jsbin.com/ipewe/edit

Fit image to table cell [Pure HTML]

It's all about display: block :)

Updated:

Ok so you have the table, tr and td tags:

<table>
  <tr>
    <td>
      <!-- your image goes here -->
    </td>
  </tr>
</table>

Lets say your table or td (whatever define your width) has property width: 360px;. Now, when you try to replace the html comment with the actual image and set that image property for example width: 100%; which should fully fill out the td cell you will face the problem.

The problem is that your table cell (td) isn't properly filled with the image. You'll notice the space at the bottom of the cell which your image doesn't cover (it's like 5px of padding).

How to solve this in a simpliest way?

You are working with the tables, right? You just need to add the display property to your image so that it has the following:

img {
  width: 100%;
  display: block;
}

Spring REST Service: how to configure to remove null objects in json response

As of Jackson 2.0, @JsonSerialize(include = xxx) has been deprecated in favour of @JsonInclude

Making div content responsive

@media screen and (max-width : 760px) (for tablets and phones) and use with this: <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

Check box size change with CSS

Try this

<input type="checkbox" style="zoom:1.5;" />
/* The value 1.5 i.e., the size of checkbox will be increased by 0.5% */

Calculate age given the birth date in the format YYYYMMDD

One more possible solution with moment.js:

var moment = require('moment');
var startDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getFullYear() + 5); // Add 5 years to second date
console.log(moment.duration(endDate - startDate).years()); // This should returns 5

How do I escape a single quote ( ' ) in JavaScript?

You can escape a ' in JavaScript like \'

HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx

I've found a post here on Stackoverflow and implemented your design:

http://jsfiddle.net/bKsad/25/

Here's the original post: https://stackoverflow.com/a/5768262/1368423

Is that what you're looking for?

HTML:

<div class="container-fluid wrapper">

  <div class="row-fluid columns content"> 

    <div class="span2 article-tree">
      navigation column
    </div>

    <div class="span10 content-area">
      content column 
    </div>
  </div>

  <div class="footer">
     footer content
  </div>
</div>

CSS:

html, body {
    height: 100%;
}
.container-fluid {
    margin: 0 auto;
    height: 100%;
    padding: 20px 0;

    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

.columns {
    background-color: #C9E6FF;
    height: 100%;   
}

.content-area, .article-tree{
    background: #bada55;
    overflow:auto;
    height: 100%;
}

.footer {
    background: red;
    height: 20px;
}

MongoDB query with an 'or' condition

Query objects in Mongo by default AND expressions together. Mongo currently does not include an OR operator for such queries, however there are ways to express such queries.

Use "in" or "where".

Its gonna be something like this:

db.mycollection.find( { $where : function() { 
return ( this.startTime < Now() && this.expireTime > Now() || this.expireTime == null ); } } );

Adding external library into Qt Creator project

I would like to add for the sake of completeness that you can also add just the LIBRARY PATH where it will look for a dependent library (which may not be directly referenced in your code but a library you use may need it).

For comparison, this would correspond to what LIBPATH environment does but its kind of obscure in Qt Creator and not well documented.

The way i came around this is following:

LIBS += -L"$$_PRO_FILE_PWD_/Path_to_Psapi_lib/"

Essentially if you don't provide the actual library name, it adds the path to where it will search dependent libraries. The difference in syntax is small but this is very useful to supply just the PATH where to look for dependent libraries. It sometime is just a pain to supply each path individual library where you know they are all in certain folder and Qt Creator will pick them up.

CSS Font Border?

I created a comparison of all the solutions mentioned here to have a quick overview:

<h1>with mixin</h1>
<h2>with text-shadow</h2>
<h3>with css text-stroke-width</h3>

https://codepen.io/Grienauer/pen/GRRdRJr

Why use Ruby's attr_accessor, attr_reader and attr_writer?

You don't always want your instance variables to be fully accessible from outside of the class. There are plenty of cases where allowing read access to an instance variable makes sense, but writing to it might not (e.g. a model that retrieves data from a read-only source). There are cases where you want the opposite, but I can't think of any that aren't contrived off the top of my head.

How to recover closed output window in netbeans?

I had this same issue recently and none of the other fixes worked. I got it to show finally by switching to the "Services" tab, right-clicking on "Apache Tomcat or TomEE" and clicking "Restart".

What is the most efficient way to store tags in a database?

One item is going to have many tags. And one tag will belong to many items. This implies to me that you'll quite possibly need an intermediary table to overcome the many-to-many obstacle.

Something like:

Table: Items
Columns: Item_ID, Item_Title, Content

Table: Tags
Columns: Tag_ID, Tag_Title

Table: Items_Tags
Columns: Item_ID, Tag_ID

It might be that your web app is very very popular and need de-normalizing down the road, but it's pointless muddying the waters too early.

compareTo() vs. equals()

I believe equals and equalsIgnoreCase methods of String return true and false which is useful if you wanted to compare the values of the string object, But in case of implementing compareTo and compareToIgnoreCase methods returns positive, negative and zero value which will be useful in case of sorting.

Linux configure/make, --prefix?

Do configure --help and see what other options are available.

It is very common to provide different options to override different locations. By standard, --prefix overrides all of them, so you need to override config location after specifying the prefix. This course of actions usually works for every automake-based project.

The worse case scenario is when you need to modify the configure script, or even worse, generated makefiles and config.h headers. But yeah, for Xfce you can try something like this:

./configure --prefix=/home/me/somefolder/mybuild/output/target --sysconfdir=/etc 

I believe that should do it.

How to write hello world in assembler under Windows?

These are Win32 and Win64 examples using Windows API calls. They are for MASM rather than NASM, but have a look at them. You can find more details in this article.

This uses MessageBox instead of printing to stdout.

Win32 MASM

;---ASM Hello World Win32 MessageBox

.386
.model flat, stdcall
include kernel32.inc
includelib kernel32.lib
include user32.inc
includelib user32.lib

.data
title db 'Win32', 0
msg db 'Hello World', 0

.code

Main:
push 0            ; uType = MB_OK
push offset title ; LPCSTR lpCaption
push offset msg   ; LPCSTR lpText
push 0            ; hWnd = HWND_DESKTOP
call MessageBoxA
push eax          ; uExitCode = MessageBox(...)
call ExitProcess

End Main

Win64 MASM

;---ASM Hello World Win64 MessageBox

extrn MessageBoxA: PROC
extrn ExitProcess: PROC

.data
title db 'Win64', 0
msg db 'Hello World!', 0

.code
main proc
  sub rsp, 28h  
  mov rcx, 0       ; hWnd = HWND_DESKTOP
  lea rdx, msg     ; LPCSTR lpText
  lea r8,  title   ; LPCSTR lpCaption
  mov r9d, 0       ; uType = MB_OK
  call MessageBoxA
  add rsp, 28h  
  mov ecx, eax     ; uExitCode = MessageBox(...)
  call ExitProcess
main endp

End

To assemble and link these using MASM, use this for 32-bit executable:

ml.exe [filename] /link /subsystem:windows 
/defaultlib:kernel32.lib /defaultlib:user32.lib /entry:Main

or this for 64-bit executable:

ml64.exe [filename] /link /subsystem:windows 
/defaultlib:kernel32.lib /defaultlib:user32.lib /entry:main

Why does x64 Windows need to reserve 28h bytes of stack space before a call? That's 32 bytes (0x20) of shadow space aka home space, as required by the calling convention. And another 8 bytes to re-align the stack by 16, because the calling convention requires RSP be 16-byte aligned before a call. (Our main's caller (in the CRT startup code) did that. The 8-byte return address means that RSP is 8 bytes away from a 16-byte boundary on entry to a function.)

Shadow space can be used by a function to dump its register args next to where any stack args (if any) would be. A system call requires 30h (48 bytes) to also reserve space for r10 and r11 in addition to the previously mentioned 4 registers. But DLL calls are just function calls, even if they're wrappers around syscall instructions.

Fun fact: non-Windows, i.e. the x86-64 System V calling convention (e.g. on Linux) doesn't use shadow space at all, and uses up to 6 integer/pointer register args, and up to 8 FP args in XMM registers.


Using MASM's invoke directive (which knows the calling convention), you can use one ifdef to make a version of this which can be built as 32-bit or 64-bit.

ifdef rax
    extrn MessageBoxA: PROC
    extrn ExitProcess: PROC
else
    .386
    .model flat, stdcall
    include kernel32.inc
    includelib kernel32.lib
    include user32.inc
    includelib user32.lib
endif
.data
caption db 'WinAPI', 0
text    db 'Hello World', 0
.code
main proc
    invoke MessageBoxA, 0, offset text, offset caption, 0
    invoke ExitProcess, eax
main endp
end

The macro variant is the same for both, but you won't learn assembly this way. You'll learn C-style asm instead. invoke is for stdcall or fastcall while cinvoke is for cdecl or variable argument fastcall. The assembler knows which to use.

You can disassemble the output to see how invoke expanded.

How can I use NSError in my iPhone App?

extension NSError {
    static func defaultError() -> NSError {
        return NSError(domain: "com.app.error.domain", code: 0, userInfo: [NSLocalizedDescriptionKey: "Something went wrong."])
    }
}

which I can use NSError.defaultError() whenever I don't have valid error object.

let error = NSError.defaultError()
print(error.localizedDescription) //Something went wrong.

With MySQL, how can I generate a column containing the record index in a table?

Here comes the structure of template I used:

  select
          /*this is a row number counter*/
          ( select @rownum := @rownum + 1 from ( select @rownum := 0 ) d2 ) 
          as rownumber,
          d3.*
  from 
  ( select d1.* from table_name d1 ) d3

And here is my working code:

select     
           ( select @rownum := @rownum + 1 from ( select @rownum := 0 ) d2 ) 
           as rownumber,
           d3.*
from
(   select     year( d1.date ), month( d1.date ), count( d1.id )
    from       maindatabase d1
    where      ( ( d1.date >= '2013-01-01' ) and ( d1.date <= '2014-12-31' ) )
    group by   YEAR( d1.date ), MONTH( d1.date ) ) d3

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

There is a Powershell script buried in the msdb forums that will script all the tables and related objects:

# Script all tables in a database
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") 
    | out-null

$s = new-object ('Microsoft.SqlServer.Management.Smo.Server') '<Servername>'
$db = $s.Databases['<Database>']

$scrp = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') ($s)
$scrp.Options.AppendToFile = $True
$scrp.Options.ClusteredIndexes = $True
$scrp.Options.DriAll = $True
$scrp.Options.ScriptDrops = $False
$scrp.Options.IncludeHeaders = $False
$scrp.Options.ToFileOnly = $True
$scrp.Options.Indexes = $True
$scrp.Options.WithDependencies = $True
$scrp.Options.FileName = 'C:\Temp\<Database>.SQL'

foreach($item in $db.Tables) { $tablearray+=@($item) }
$scrp.Script($tablearray)

Write-Host "Scripting complete"

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

Try this. Just add an empty option. This will solve your problem.

<select onchange="jsFunction()">
    <option></option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>?

How to capture a JFrame's close button click event?

Override windowClosing Method.

public void windowClosing(WindowEvent e)

It is invoked when a window is in the process of being closed. The close operation can be overridden at this point.

Getting multiple keys of specified value of a generic Dictionary?

A dictionary doesn't keep an hash of the values, only the keys, so any search over it using a value is going to take at least linear time. Your best bet is to simply iterate over the elements in the dictionary and keep track of the matching keys or switch to a different data structure, perhaps maintain two dictionary mapping key->value and value->List_of_keys. If you do the latter you will trade storage for look up speed. It wouldn't take much to turn @Cybis example into such a data structure.

How to change an Eclipse default project into a Java project

Joe's approach is actually the most effective means that I have found for doing this conversation. To elaborate a little bit more on it, you should right click on the project in the package explorer in eclipse and then select to delete it without removing directory or its contents. Next, you select to create a Java project (File -> New -> Java Project) and in the Contents part of the New Java Project dialog box, select 'Create project from existing source'.

The advantage this approach is that source folders will be properly identified. I found that mucking around with the .project file can lead to the entire directory being considered a source folder which is not what you want.

async for loop in node.js

I've reduced your code sample to the following lines to make it easier to understand the explanation of the concept.

var results = [];
var config = JSON.parse(queries);
for (var key in config) {
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
    });
}
res.writeHead( ... );
res.end(results);

The problem with the previous code is that the search function is asynchronous, so when the loop has ended, none of the callback functions have been called. Consequently, the list of results is empty.

To fix the problem, you have to put the code after the loop in the callback function.

    search(query, function(result) {
        results.push(result);
        // Put res.writeHead( ... ) and res.end(results) here
    });

However, since the callback function is called multiple times (once for every iteration), you need to somehow know that all callbacks have been called. To do that, you need to count the number of callbacks, and check whether the number is equal to the number of asynchronous function calls.

To get a list of all keys, use Object.keys. Then, to iterate through this list, I use .forEach (you can also use for (var i = 0, key = keys[i]; i < keys.length; ++i) { .. }, but that could give problems, see JavaScript closure inside loops – simple practical example).

Here's a complete example:

var results = [];
var config = JSON.parse(queries);
var onComplete = function() {
    res.writeHead( ... );
    res.end(results);
};
var keys = Object.keys(config);
var tasksToGo = keys.length;
if (tasksToGo === 0) {
   onComplete();
} else {
    // There is at least one element, so the callback will be called.
    keys.forEach(function(key) {
        var query = config[key].query;
        search(query, function(result) {
            results.push(result);
            if (--tasksToGo === 0) {
                // No tasks left, good to go
                onComplete();
            }
        });
    });
}

Note: The asynchronous code in the previous example are executed in parallel. If the functions need to be called in a specific order, then you can use recursion to get the desired effect:

var results = [];
var config = JSON.parse(queries);
var keys = Object.keys(config);
(function next(index) {
    if (index === keys.length) { // No items left
        res.writeHead( ... );
        res.end(results);
        return;
    }
    var key = keys[index];
    var query = config[key].query;
    search(query, function(result) {
        results.push(result);
        next(index + 1);
    });
})(0);

What I've shown are the concepts, you could use one of the many (third-party) NodeJS modules in your implementation, such as async.

How to tell if browser/tab is active

If you are trying to do something similar to the Google search page when open in Chrome, (where certain events are triggered when you 'focus' on the page), then the hover() event may help.

$(window).hover(function() {
  // code here...
});

CodeIgniter: How to use WHERE clause and OR clause

You can use or_where() for that - example from the CI docs:

$this->db->where('name !=', $name);

$this->db->or_where('id >', $id); 

// Produces: WHERE name != 'Joe' OR id > 50

How to generate unique ID with node.js

Extending from YaroslavGaponov's answer, the simplest implementation is just using Math.random().

Math.random()

Mathematically, the chances of fractions being the same in a real space [0, 1] is theoretically 0. Probability-wise it is approximately close to 0 for a default length of 16 decimals in node.js. And this implementation should also reduce arithmetic overflows as no operations are performed. Also, it is more memory efficient compared to a string as Decimals occupy less memory than strings.

I call this the "Fractional-Unique-ID".

Wrote code to generate 1,000,000 Math.random() numbers and could not find any duplicates (at least for default decimal points of 16). See code below (please provide feedback if any):

random_numbers = [] 
for (i = 0; i < 1000000; i++) { 
   random_numbers.push(Math.random()); 
   //random_numbers.push(Math.random().toFixed(13)) //depends decimals default 16 
} 

if (i === 1000000) { 
   console.log("Before checking duplicate"); 
   console.log(random_numbers.length); 
   console.log("After checking duplicate"); 
   random_set = new Set(random_numbers); // Set removes duplicates
   console.log([...random_set].length); // length is still the same after removing
} 

How do I break out of a loop in Perl?

For Perl one-liners with implicit loops (using -n or -p command line options), use last or last LINE to break out of the loop that iterates over input records. For example, these simple examples all print the first 2 lines of the input:

echo 1 2 3 4 | xargs -n1 | perl -ne 'last if $. == 3; print;'
echo 1 2 3 4 | xargs -n1 | perl -ne 'last LINE if $. == 3; print;'
echo 1 2 3 4 | xargs -n1 | perl -pe 'last if $. == 3;'
echo 1 2 3 4 | xargs -n1 | perl -pe 'last LINE if $. == 3;'

All print:

1
2

The perl one-liners use these command line flags:
-e : tells Perl to look for code in-line, instead of in a file.
-n : loop over the input one line at a time, assigning it to $_ by default.
-p : same as -n, also add print after each loop iteration over the input.

SEE ALSO:

last docs
last, next, redo, continue - an illustrated example
perlrun: command line switches docs


More examples of last in Perl one-liners:

Break one liner command line script after first match
Print the first N lines of a huge file

How to check if cursor exists (open status)

You can use the CURSOR_STATUS function to determine its state.

IF CURSOR_STATUS('global','myCursor')>=-1
BEGIN
 DEALLOCATE myCursor
END

End of File (EOF) in C

That's a lot of questions.

  1. Why EOF is -1: usually -1 in POSIX system calls is returned on error, so i guess the idea is "EOF is kind of error"

  2. any boolean operation (including !=) returns 1 in case it's TRUE, and 0 in case it's FALSE, so getchar() != EOF is 0 when it's FALSE, meaning getchar() returned EOF.

  3. in order to emulate EOF when reading from stdin press Ctrl+D

Javac is not found

do this: 1. run CMD (WIN+R then type in CMD) 2. Type this:

set PATH=%PATH%; java installation path\bin

Replace "java installation path" with the directory JDK is installed in, such as C:\Program Files (x86)\Java. Be sure to add the \bin after the JDK directory, because this points to "javac" and "java" (BIN stands for "binaries")

This way, you can run the Java compiler from anywhere. It is impossible to CD to the JDK directory because it has a space in Program Files, and DOS will not let you CD to these directories.

Redirect pages in JSP?

Hello there: If you need more control on where the link should redirect to, you could use this solution.

Ie. If the user is clicking in the CHECKOUT link, but you want to send him/her to checkout page if its registered(logged in) or registration page if he/she isn't.

You could use JSTL core LIKE:

<!--include the library-->
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>

<%--create a var to store link--%>
<core:set var="linkToRedirect">
  <%--test the condition you need--%>
  <core:choose>
    <core:when test="${USER IS REGISTER}">
      checkout.jsp
    </core:when>
    <core:otherwise>
      registration.jsp
    </core:otherwise>
  </core:choose>
</core:set>

EXPLAINING: is the same as...

 //pseudo code
 if(condition == true)
   set linkToRedirect = checkout.jsp
 else
   set linkToRedirect = registration.jsp

THEN: in simple HTML...

<a href="your.domain.com/${linkToRedirect}">CHECKOUT</a>

Objective-C: Extract filename from path string

Taken from the NSString reference, you can use :

NSString *theFileName = [[string lastPathComponent] stringByDeletingPathExtension];

The lastPathComponent call will return thefile.ext, and the stringByDeletingPathExtension will remove the extension suffix from the end.

Make code in LaTeX look *nice*

The listings package is quite nice and very flexible (e.g. different sizes for comments and code).

Why am I getting a "401 Unauthorized" error in Maven?

In my case I removed the server logon credentials for central from my setting.

    <server> 
        <id>central</id>
        <username>admin</username> 
        <password>******</password> 
    </server>

   <mirror>
        <id>central</id>
        <mirrorOf>central</mirrorOf>
        <name>maven-central</name>
        <url>http://www.localhost:8081/repository/maven-central/</url>
   </mirror> 

I don't know why I did that, but its completely wrong since the central maven repo can be accessed anonymously. See my debug output that led to my error identification and resolution.

[DEBUG] Using connector BasicRepositoryConnector with priority 0.0 for http://www.localhost:8081/repository/maven-central/ with username=admin, password=***

Comparing user-inputted characters in C

Because comparison doesn't work that way. 'Y' || 'y' is a logical-or operator; it returns 1 (true) if either of its arguments is true. Since 'Y' and 'y' are both true, you're comparing *answer with 1.

What you want is if(*answer == 'Y' || *answer == 'y') or perhaps:

switch (*answer) {
  case 'Y':
  case 'y':
    /* Code for Y */
    break;
  default:
    /* Code for anything else */
}

CodeIgniter: 404 Page Not Found on Live Server

Solved the issue. Change your class name to make only the first letter capitalized. so if you got something like 'MyClass' change it to 'Myclass'. apply it to both the file name and class name.

Preserve Line Breaks From TextArea When Writing To MySQL

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

step 1:

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

In query enter $textToStore....

step 2:

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

It works

How to install plugin for Eclipse from .zip

To install the plug-in, unzip the file into the Eclipse installation directory (or the plug-in directory depending on how the plug-in is packaged). The plug-in will not appear until you have restarted your workspace (Reboot Eclipse).

Failed to execute 'atob' on 'Window'

here's an updated fiddle where the user's input is saved in local storage automatically. each time the fiddle is re-run or the page is refreshed the previous state is restored. this way you do not need to prompt users to save, it just saves on it's own.

http://jsfiddle.net/tZPg4/9397/

stack overflow requires I include some code with a jsFiddle link so please ignore snippet:

localStorage.setItem(...)

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

My situation was a bit different.

  • JAVA_HOME was set properly to point to 1.7
  • Other Maven projects were working/building fine with 1.7 features.
  • PATH was set properly.
  • Everything was up-to-date.

Still my simple new Maven project was not working. What I noticed was the difference in the logs when I ran mvn clean install. For my older Maven projects, it showed

[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ oldProject---

But for my new project it showed:

[INFO] --- maven-compiler-plugin:2.0.2:compile (default-compile) @ newProject ---

So, I looked at the POM.xml and noticed this thing in the old project's POM:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Basically, this plugin tells which compiler version to use for compilation. Just added it to the new project's POM.xml and things worked.

Hope it is useful to someone.

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

The reason is your current ruby environment, you got a different version of bundler with the version in Gemfile.lock.

  • Safe way, install bundler with the same version in Gemfile.lock, this won't break anything if there is some incampatibly thing happened.
  • Hard way, just remove Gemfile.lock, and run bundle install.

Running EXE with parameters

To start the process with parameters, you can use following code:

string filename = Path.Combine(cPath,"HHTCtrlp.exe");
var proc = System.Diagnostics.Process.Start(filename, cParams);

To kill/exit the program again, you can use following code:

proc.CloseMainWindow(); 
proc.Close();

differences in application/json and application/x-www-form-urlencoded

The first case is telling the web server that you are posting JSON data as in:

{ Name : 'John Smith', Age: 23}

The second option is telling the web server that you will be encoding the parameters in the URL as in:

Name=John+Smith&Age=23

Recursive mkdir() system call on Unix

Here's another take on mkpath(), using recursion, which is both small and readable. It makes use of strdupa() to avoid altering the given dir string argument directly and to avoid using malloc() & free(). Make sure to compile with -D_GNU_SOURCE to activate strdupa() ... meaning this code only works on GLIBC, EGLIBC, uClibc, and other GLIBC compatible C libraries.

int mkpath(char *dir, mode_t mode)
{
    if (!dir) {
        errno = EINVAL;
        return 1;
    }

    if (strlen(dir) == 1 && dir[0] == '/')
        return 0;

    mkpath(dirname(strdupa(dir)), mode);

    return mkdir(dir, mode);
}

After input both here and from Valery Frolov, in the Inadyn project, the following revised version of mkpath() has now been pushed to libite

int mkpath(char *dir, mode_t mode)
{
    struct stat sb;

    if (!dir) {
        errno = EINVAL;
        return 1;
    }

    if (!stat(dir, &sb))
        return 0;

    mkpath(dirname(strdupa(dir)), mode);

    return mkdir(dir, mode);
}

It uses one more syscall, but otoh the code is more readable now.

How to use the ProGuard in Android Studio?

NB.: Now instead of

runProguard false

you'll need to use

minifyEnabled false

Laravel - Session store not set on request

In my case (using Laravel 5.3) adding only the following 2 middleware allowed me to access session data in my API routes:

  • \App\Http\Middleware\EncryptCookies::class
  • \Illuminate\Session\Middleware\StartSession::class

Whole declaration ($middlewareGroups in Kernel.php):

'api' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Session\Middleware\StartSession::class,
            'throttle:60,1',
            'bindings',
        ],

Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal

TL;DR

For JDK 11 try this:

To handle this problem in a clean way, I suggest to use brew and jenv.

For Java 11 follow this 2 steps, first :

JAVA_VERSION=11
brew reinstall jenv 
brew reinstall openjdk@${JAVA_VERSION}
jenv add /usr/local/opt/openjdk@${JAVA_VERSION}/
jenv global ${JAVA_VERSION}

And add this at end of your shell config scripts
~/.bashrc or ~/.zshrc

export PATH="$HOME/.jenv/bin:$PATH"
eval "$(jenv init -)"
export JAVA_HOME="$HOME/.jenv/versions/`jenv version-name`"

Problem solved!

Then restart your shell and try to execute java -version

Note: If you have this problem, your current JDK version is not existent or misconfigured (or may be you have only JRE).

How do I get to IIS Manager?

To open IIS Manager, click Start, type inetmgr in the Search Programs and Files box, and then press ENTER.

if the IIS Manager doesn't open that means you need to install it.

So, Follow the instruction at this link: https://docs.microsoft.com/en-us/iis/install/installing-iis-7/installing-iis-on-windows-vista-and-windows-7

Get contentEditable caret index position

window.getSelection - vs - document.selection

This one works for me:

_x000D_
_x000D_
function getCaretCharOffset(element) {_x000D_
  var caretOffset = 0;_x000D_
_x000D_
  if (window.getSelection) {_x000D_
    var range = window.getSelection().getRangeAt(0);_x000D_
    var preCaretRange = range.cloneRange();_x000D_
    preCaretRange.selectNodeContents(element);_x000D_
    preCaretRange.setEnd(range.endContainer, range.endOffset);_x000D_
    caretOffset = preCaretRange.toString().length;_x000D_
  } _x000D_
_x000D_
  else if (document.selection && document.selection.type != "Control") {_x000D_
    var textRange = document.selection.createRange();_x000D_
    var preCaretTextRange = document.body.createTextRange();_x000D_
    preCaretTextRange.moveToElementText(element);_x000D_
    preCaretTextRange.setEndPoint("EndToEnd", textRange);_x000D_
    caretOffset = preCaretTextRange.text.length;_x000D_
  }_x000D_
_x000D_
  return caretOffset;_x000D_
}_x000D_
_x000D_
_x000D_
// Demo:_x000D_
var elm = document.querySelector('[contenteditable]');_x000D_
elm.addEventListener('click', printCaretPosition)_x000D_
elm.addEventListener('keydown', printCaretPosition)_x000D_
_x000D_
function printCaretPosition(){_x000D_
  console.log( getCaretCharOffset(elm), 'length:', this.textContent.trim().length )_x000D_
}
_x000D_
<div contenteditable>some text here <i>italic text here</i> some other text here <b>bold text here</b> end of text</div>
_x000D_
_x000D_
_x000D_

The calling line depends on event type, for key event use this:

getCaretCharOffsetInDiv(e.target) + ($(window.getSelection().getRangeAt(0).startContainer.parentNode).index());

for mouse event use this:

getCaretCharOffsetInDiv(e.target.parentElement) + ($(e.target).index())

on these two cases I take care for break lines by adding the target index

Replace a value in a data frame based on a conditional (`if`) statement

Easier to convert nm to characters and then make the change:

junk$nm <- as.character(junk$nm)
junk$nm[junk$nm == "B"] <- "b"

EDIT: And if indeed you need to maintain nm as factors, add this in the end:

junk$nm <- as.factor(junk$nm)

How can I clear the SQL Server query cache?

Eight different ways to clear the plan cache

1. Remove all elements from the plan cache for the entire instance

DBCC FREEPROCCACHE;

Use this to clear the plan cache carefully. Freeing the plan cache causes, for example, a stored procedure to be recompiled instead of reused from the cache. This can cause a sudden, temporary decrease in query performance.

2. Flush the plan cache for the entire instance and suppress the regular completion message

"DBCC execution completed. If DBCC printed error messages, contact your system administrator."

DBCC FREEPROCCACHE WITH NO_INFOMSGS;

3. Flush the ad hoc and prepared plan cache for the entire instance

DBCC FREESYSTEMCACHE ('SQL Plans');

4. Flush the ad hoc and prepared plan cache for one resource pool

DBCC FREESYSTEMCACHE ('SQL Plans', 'LimitedIOPool');

5. Flush the entire plan cache for one resource pool

DBCC FREEPROCCACHE ('LimitedIOPool');

6. Remove all elements from the plan cache for one database (does not work in SQL Azure)

-- Get DBID from one database name first
DECLARE @intDBID INT;
SET @intDBID = (SELECT [dbid] 
                FROM master.dbo.sysdatabases 
                WHERE name = N'AdventureWorks2014');

DBCC FLUSHPROCINDB (@intDBID);

7. Clear plan cache for the current database

USE AdventureWorks2014;
GO
-- New in SQL Server 2016 and SQL Azure
ALTER DATABASE SCOPED CONFIGURATION CLEAR PROCEDURE_CACHE;

8. Remove one query plan from the cache

USE AdventureWorks2014;
GO

-- Run a stored procedure or query
EXEC dbo.uspGetEmployeeManagers 9;

-- Find the plan handle for that query 
-- OPTION (RECOMPILE) keeps this query from going into the plan cache
SELECT cp.plan_handle, cp.objtype, cp.usecounts, 
DB_NAME(st.dbid) AS [DatabaseName]
FROM sys.dm_exec_cached_plans AS cp CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS st 
WHERE OBJECT_NAME (st.objectid)
LIKE N'%uspGetEmployeeManagers%' OPTION (RECOMPILE); 

-- Remove the specific query plan from the cache using the plan handle from the above query 
DBCC FREEPROCCACHE (0x050011007A2CC30E204991F30200000001000000000000000000000000000000000000000000000000000000);
 

Source 1 2 3

Entity Framework Core: A second operation started on this context before a previous operation completed

I think this answer still can help some one and save many times. I solved a similar issue by changing IQueryable to List(or to array, collection...).

For example:

var list=_context.table1.where(...);

to

var list=_context.table1.where(...).ToList(); //or ToArray()...

Difference between Static and final?

The static keyword can be used in 4 scenarios

  • static variables
  • static methods
  • static blocks of code
  • static nested class

Let's look at static variables and static methods first.

Static variable

  • It is a variable which belongs to the class and not to object (instance).
  • Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.
  • A single copy to be shared by all instances of the class.
  • A static variable can be accessed directly by the class name and doesn’t need any object.
  • Syntax: Class.variable

Static method

  • It is a method which belongs to the class and not to the object (instance).
  • A static method can access only static data. It can not access non-static data (instance variables) unless it has/creates an instance of the class.
  • A static method can call only other static methods and can not call a non-static method from it unless it has/creates an instance of the class.
  • A static method can be accessed directly by the class name and doesn’t need any object.
  • Syntax: Class.methodName()
  • A static method cannot refer to this or super keywords in anyway.

Static class

Java also has "static nested classes". A static nested class is just one which doesn't implicitly have a reference to an instance of the outer class.

Static nested classes can have instance methods and static methods.

There's no such thing as a top-level static class in Java.

Side note:

main method is static since it must be be accessible for an application to run before any instantiation takes place.

final keyword is used in several different contexts to define an entity which cannot later be changed.

  • A final class cannot be subclassed. This is done for reasons of security and efficiency. Accordingly, many of the Java standard library classes are final, for example java.lang.System and java.lang.String. All methods in a final class are implicitly final.

  • A final method can't be overridden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.

  • A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a blank final variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared; otherwise, a compile-time error occurs in both cases.

Note: If the variable is a reference, this means that the variable cannot be re-bound to reference another object. But the object that it references is still mutable, if it was originally mutable.

When an anonymous inner class is defined within the body of a method, all variables declared final in the scope of that method are accessible from within the inner class. Once it has been assigned, the value of the final variable cannot change.

How to get the difference between two dictionaries in Python?

What about this? Not as pretty but explicit.

orig_dict = {'a' : 1, 'b' : 2}
new_dict = {'a' : 2, 'v' : 'hello', 'b' : 2}

updates = {}
for k2, v2 in new_dict.items():
    if k2 in orig_dict:    
        if v2 != orig_dict[k2]:
            updates.update({k2 : v2})
    else:
        updates.update({k2 : v2})

#test it
#value of 'a' was changed
#'v' is a completely new entry
assert all(k in updates for k in ['a', 'v'])

How to change the URI (URL) for a remote Git repository?

if you cloned your local will automatically consist,

remote URL where it gets cloned.

you can check it using git remote -v

if you want to made change in it,

git remote set-url origin https://github.io/my_repo.git

here,

origin - your branch

if you want to overwrite existing branch you can still use it.. it will override your existing ... it will do,

git remote remove url
and 
git remote add origin url

for you...

error code 1292 incorrect date value mysql

I happened to be working in localhost , in windows 10, using WAMP, as it turns out, Wamp has a really accessible configuration interface to change the MySQL configuration. You just need to go to the Wamp panel, then to MySQL, then to settings and change the mode to sql-mode: none.(essentially disabling the strict mode) The following picture illustrates this.

enter image description here

What's the best way of scraping data from a website?

Yes you can do it yourself. It is just a matter of grabbing the sources of the page and parsing them the way you want.

There are various possibilities. A good combo is using python-requests (built on top of urllib2, it is urllib.request in Python3) and BeautifulSoup4, which has its methods to select elements and also permits CSS selectors:

import requests
from BeautifulSoup4 import BeautifulSoup as bs
request = requests.get("http://foo.bar")
soup = bs(request.text) 
some_elements = soup.find_all("div", class_="myCssClass")

Some will prefer xpath parsing or jquery-like pyquery, lxml or something else.

When the data you want is produced by some JavaScript, the above won't work. You either need python-ghost or Selenium. I prefer the latter combined with PhantomJS, much lighter and simpler to install, and easy to use:

from selenium import webdriver
client = webdriver.PhantomJS()
client.get("http://foo")
soup = bs(client.page_source)

I would advice to start your own solution. You'll understand Scrapy's benefits doing so.

ps: take a look at scrapely: https://github.com/scrapy/scrapely

pps: take a look at Portia, to start extracting information visually, without programming knowledge: https://github.com/scrapinghub/portia

Google Map API v3 — set bounds and center

The answers are perfect for adjust map boundaries for markers but if you like to expand Google Maps boundaries for shapes like polygons and circles, you can use following codes:

For Circles

bounds.union(circle.getBounds());

For Polygons

polygon.getPaths().forEach(function(path, index)
{
    var points = path.getArray();
    for(var p in points) bounds.extend(points[p]);
});

For Rectangles

bounds.union(overlay.getBounds());

For Polylines

var path = polyline.getPath();

var slat, blat = path.getAt(0).lat();
var slng, blng = path.getAt(0).lng();

for(var i = 1; i < path.getLength(); i++)
{
    var e = path.getAt(i);
    slat = ((slat < e.lat()) ? slat : e.lat());
    blat = ((blat > e.lat()) ? blat : e.lat());
    slng = ((slng < e.lng()) ? slng : e.lng());
    blng = ((blng > e.lng()) ? blng : e.lng());
}

bounds.extend(new google.maps.LatLng(slat, slng));
bounds.extend(new google.maps.LatLng(blat, blng));

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

You can't update with a number greater than 1 for datatype number(2,2) is because, the first parameter is the total number of digits in the number and the second one (.i.e 2 here) is the number of digits in decimal part. I guess you can insert or update data < 1. i.e. 0.12, 0.95 etc.

Please check NUMBER DATATYPE in NUMBER Datatype.

Scheduling Python Script to run every hour accurately

One option is to write a C/C++ wrapper that executes the python script on a regular basis. Your end-user would run the C/C++ executable, which would remain running in the background, and periodically execute the python script. This may not be the best solution, and may not work if you don't know C/C++ or want to keep this 100% python. But it does seem like the most user-friendly approach, since people are used to clicking on executables. All of this assumes that python is installed on your end user's computer.

Another option is to use cron job/Task Scheduler but to put it in the installer as a script so your end user doesn't have to do it.

Got a NumberFormatException while trying to parse a text file for objects

NumberFormatException invoke when you ll try to convert inavlid String for eg:"abc" value to integer..

this is valid string is eg"123". in your case split by space..

split(" "); will split line by " " by space..

IndexError: tuple index out of range ----- Python

A tuple consists of a number of values separated by commas. like

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345

tuple are index based (and also immutable) in Python.

Here in this case x = rows[1][1] + " " + rows[1][2] have only two index 0, 1 available but you are trying to access the 3rd index.

Count characters in textarea

Well, this is not that different from what have been said, but this works very well in all browsers.

The idea is to delete any text which overflows the defined length.

function countTextAreaChar(txtarea, l){
    var len = $(txtarea).val().length;
    if (len > l) $(txtarea).val($(txtarea).val().slice(0, l));
    else $('#charNum').text(l - len);
    }

The HTMl code would be:

<div id="charNum"></div>
<textarea onkeyup="countTextAreaChar(this, 10)" class="textareaclass" id="smallword" rows="40" cols="30" name="smallword"></textarea>

Install IPA with iTunes 11

For iTunes 12, drag the .ipa file from the Finder to the Apps area NOT inside your device (in iTunes)... alternately, you can just double click on the .ipa in the Finder.

Important note: you have to change Version and/or Build number. Otherwise, you get no notice from iTunes at all...

Then switch to your device in iTunes, and install or update the application.

Then hit sync.

Stop form from submitting , Using Jquery

This is a JQuery code for Preventing Submit

$('form').submit(function (e) {
            if (radioButtonValue !== "0") {
                e.preventDefault();
            }
        });

ORA-01461: can bind a LONG value only for insert into a LONG column-Occurs when querying

Applications using JDBC 10.1 has got a bug (Doc ID 370438.1) and can throw the same ORA-01461 exception while working with UTF8 character set database even though inserted characters are less than the maximum size of the column.

Recommended Solution: - Use 10gR2 JDBC drivers or higher in such case.

HTH

Unique on a dataframe with only selected columns

Here are a couple dplyr options that keep non-duplicate rows based on columns id and id2:

library(dplyr)                                        
df %>% distinct(id, id2, .keep_all = TRUE)
df %>% group_by(id, id2) %>% filter(row_number() == 1)
df %>% group_by(id, id2) %>% slice(1)

Java Reflection Performance

Interestingly enough, settting setAccessible(true), which skips the security checks, has a 20% reduction in cost.

Without setAccessible(true)

new A(), 70 ns
A.class.newInstance(), 214 ns
new A(), 84 ns
A.class.newInstance(), 229 ns

With setAccessible(true)

new A(), 69 ns
A.class.newInstance(), 159 ns
new A(), 85 ns
A.class.newInstance(), 171 ns

ssl_error_rx_record_too_long and Apache SSL

In my case I had to change the <VirtualHost *> back to <VirtualHost *:80> (which is the default on Ubuntu). Otherwise, the port 443 wasn't using SSL and was sending plain HTML back to the browser.

You can check whether this is your case quite easily: just connect to your server http://www.example.com:443. If you see plain HTML, your Apache is not using SSL on port 443 at all, most probably due to a VirtualHost misconfiguration.

Cheers!

How do I replace NA values with zeros in an R dataframe?

An easy way to write it is with if_na from hablar:

library(dplyr)
library(hablar)

df <- tibble(a = c(1, 2, 3, NA, 5, 6, 8))

df %>% 
  mutate(a = if_na(a, 0))

which returns:

      a
  <dbl>
1     1
2     2
3     3
4     0
5     5
6     6
7     8

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

For data import scripts, to replace "IF NOT EXISTS", in a way, there's a slightly awkward formulation that nevertheless works:

DO
$do$
BEGIN
PERFORM id
FROM whatever_table;

IF NOT FOUND THEN
-- INSERT stuff
END IF;
END
$do$;

Casting to string in JavaScript

if you are ok with null, undefined, NaN, 0, and false all casting to '' then (s ? s+'' : '') is faster.

see http://jsperf.com/cast-to-string/8

note - there are significant differences across browsers at this time.

How do I make JavaScript beep?

The top answer was correct at the time but is now wrong; you can do it in pure javascript. But the one answer using javascript doesn't work any more, and the other answers are pretty limited or don't use pure javascript.

I made my own solution that works well and lets you control the volume, frequency, and wavetype.

//if you have another AudioContext class use that one, as some browsers have a limit
var audioCtx = new (window.AudioContext || window.webkitAudioContext || window.audioContext);

//All arguments are optional:

//duration of the tone in milliseconds. Default is 500
//frequency of the tone in hertz. default is 440
//volume of the tone. Default is 1, off is 0.
//type of tone. Possible values are sine, square, sawtooth, triangle, and custom. Default is sine.
//callback to use on end of tone
function beep(duration, frequency, volume, type, callback) {
    var oscillator = audioCtx.createOscillator();
    var gainNode = audioCtx.createGain();

    oscillator.connect(gainNode);
    gainNode.connect(audioCtx.destination);

    if (volume){gainNode.gain.value = volume;}
    if (frequency){oscillator.frequency.value = frequency;}
    if (type){oscillator.type = type;}
    if (callback){oscillator.onended = callback;}

    oscillator.start(audioCtx.currentTime);
    oscillator.stop(audioCtx.currentTime + ((duration || 500) / 1000));
};

Someone suggested I edit this to note it only works on some browsers. However Audiocontext seems to be supported on all modern browsers, as far as I can tell. It isn't supported on IE, but that has been discontinued by Microsoft. If you have any issues with this on a specific browser please report it.

ActiveModel::ForbiddenAttributesError when creating new user

If using ActiveAdmin don't forget that there is also a permit_params in the model register block:

ActiveAdmin.register Api::V1::Person do
  permit_params :name, :address, :etc
end

These need to be set along with those in the controller:

def api_v1_person_params
  params.require(:api_v1_person).permit(:name, :address, :etc)
end

Otherwise you will get the error:

ActiveModel::ForbiddenAttributesError

How to convert/parse from String to char in java?

An Essay way :

public class CharToInt{  
public static void main(String[] poo){  
String ss="toyota";
for(int i=0;i<ss.length();i++)
  {
     char c = ss.charAt(i); 
    // int a=c;  
     System.out.println(c); } } 
} 

For Output see this link: Click here

Thanks :-)

List names of all tables in a SQL Server 2012 schema

Your should really use the INFORMATION_SCHEMA views in your database:

USE <your_database_name>
GO
SELECT * FROM INFORMATION_SCHEMA.TABLES

You can then filter that by table schema and/or table type, e.g.

SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'

window.onload vs document.onload

According to Parsing HTML documents - The end,

  1. The browser parses the HTML source and runs deferred scripts.

  2. A DOMContentLoaded is dispatched at the document when all the HTML has been parsed and have run. The event bubbles to the window.

  3. The browser loads resources (like images) that delay the load event.

  4. A load event is dispatched at the window.

Therefore, the order of execution will be

  1. DOMContentLoaded event listeners of window in the capture phase
  2. DOMContentLoaded event listeners of document
  3. DOMContentLoaded event listeners of window in the bubble phase
  4. load event listeners (including onload event handler) of window

A bubble load event listener (including onload event handler) in document should never be invoked. Only capture load listeners might be invoked, but due to the load of a sub-resource like a stylesheet, not due to the load of the document itself.

_x000D_
_x000D_
window.addEventListener('DOMContentLoaded', function() {_x000D_
  console.log('window - DOMContentLoaded - capture'); // 1st_x000D_
}, true);_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
  console.log('document - DOMContentLoaded - capture'); // 2nd_x000D_
}, true);_x000D_
document.addEventListener('DOMContentLoaded', function() {_x000D_
  console.log('document - DOMContentLoaded - bubble'); // 2nd_x000D_
});_x000D_
window.addEventListener('DOMContentLoaded', function() {_x000D_
  console.log('window - DOMContentLoaded - bubble'); // 3rd_x000D_
});_x000D_
_x000D_
window.addEventListener('load', function() {_x000D_
  console.log('window - load - capture'); // 4th_x000D_
}, true);_x000D_
document.addEventListener('load', function(e) {_x000D_
  /* Filter out load events not related to the document */_x000D_
  if(['style','script'].indexOf(e.target.tagName.toLowerCase()) < 0)_x000D_
    console.log('document - load - capture'); // DOES NOT HAPPEN_x000D_
}, true);_x000D_
document.addEventListener('load', function() {_x000D_
  console.log('document - load - bubble'); // DOES NOT HAPPEN_x000D_
});_x000D_
window.addEventListener('load', function() {_x000D_
  console.log('window - load - bubble'); // 4th_x000D_
});_x000D_
_x000D_
window.onload = function() {_x000D_
  console.log('window - onload'); // 4th_x000D_
};_x000D_
document.onload = function() {_x000D_
  console.log('document - onload'); // DOES NOT HAPPEN_x000D_
};
_x000D_
_x000D_
_x000D_

Ignore .pyc files in git repository

You have probably added them to the repository before putting *.pyc in .gitignore.
First remove them from the repository.

How to create an array from a CSV file using PHP and the fgetcsv function

Like you said in your title, fgetcsv is the way to go. It's pretty darn easy to use.

$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
  //$line is an array of the csv elements
  print_r($line);
}
fclose($file);

You'll want to put more error checking in there in case fopen() fails, but this works to read a CSV file line by line and parse the line into an array.