Programs & Examples On #Xstream

XStream is a simple Java library to serialize objects to XML and back again.

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

I had the same problem and got it resolved by deleting .m2 maven repo (C:\Users\user\ .m2)

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

This should fix the error

<plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-resources-plugin</artifactId>
     <version>2.7</version>
     <dependencies>
         <dependency>
             <groupId>org.apache.maven.shared</groupId>
             <artifactId>maven-filtering</artifactId>
             <version>1.3</version>
          </dependency>
      </dependencies>
</plugin>

Maven Java EE Configuration Marker with Java Server Faces 1.2

The m2e plugin generate project configuration every time when you update project (Maven->Update Project ... That action overrides facets setting configured manually in Eclipse. Therefore you have to configure it on pom level. By setting properties in pom file you can tell m2e plugin what to do.

Enable/Disable the JAX-RS/JPA/JSF Configurators at the pom.xml level The optional JAX-RS, JPA and JSF configurators can be enabled or disabled at a workspace level from Window > Preferences > Maven > Java EE Integration. Now, you can have a finer grain control on these configurators directly from your pom.xml properties :

Adding false in your pom properties section will disable the JAX-RS configurator Adding false in your pom properties section will disable the JPA configurator Adding false in your pom properties section will disable the JSF configurator The pom settings always override the workspace preferences. So if you have, for instance the JPA configurator disabled at the workspace level, using true will enable it on your project anyway. (http://wiki.eclipse.org/M2E-WTP/New_and_Noteworthy/1.0.0)

CXF: No message body writer found for class - automatically mapping non-simple resources

You can also configure CXFNonSpringJAXRSServlet (assuming JSONProvider is used):

<init-param>
  <param-name>jaxrs.providers</param-name>
  <param-value>
      org.apache.cxf.jaxrs.provider.JSONProvider
      (writeXsiType=false)
  </param-value> 
</init-param>

Maven2: Missing artifact but jars are in place

After running eclipse:clean eclipse:eclipse its worked for me. enter image description here

How to serialize object to CSV file?

You can use gererics to work for any class

public class FileUtils<T> {
public String createReport(String filePath, List<T> t) {
    if (t.isEmpty()) {
        return null;
    }

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

    addDataToReport(t.get(0), reportData, 0);

    for (T k : t) {
        addDataToReport(k, reportData, 1);
    }
    return !dumpReport(filePath, reportData) ? null : filePath;
}

public static Boolean dumpReport(String filePath, List<String> lines) {
    Boolean isFileCreated = false;

    
    String[] dirs = filePath.split(File.separator);
    String baseDir = "";
    for (int i = 0; i < dirs.length - 1; i++) {
        baseDir += " " + dirs[i];
    }
    baseDir = baseDir.replace(" ", "/");
    
    File base = new File(baseDir);
    base.mkdirs();

    File file = new File(filePath);
    try {
        if (!file.exists())
            file.createNewFile();
    } catch (Exception e) {
        e.printStackTrace();
        return isFileCreated;
    }

    try (BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(file), System.getProperty("file.encoding")))) {
        for (String line : lines) {
            writer.write(line + System.lineSeparator());
        }
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

void addDataToReport(T t, List<String> reportData, int index) {
    String[] jsonObjectAsArray = new Gson().toJson(t).replace("{", "").replace("}", "").split(",\"");
    StringBuilder row = new StringBuilder();

    for (int i = 0; i < jsonObjectAsArray.length; i++) {
        String str = jsonObjectAsArray[i];
        str = str.replaceFirst(":", "_").split("_")[index];

        if (i == 0) {
            if (str != null) {
                row.append(str.replace("\"", ""));
            } else {
                row.append("N/A");
            }
        } else {
            if (str != null) {
                row.append(", " + str.replace("\"", ""));
            } else {
                row.append(", N/A");
            }
        }
    }
    reportData.add(row.toString());
}

How to convert XML to java.util.Map and vice versa

I used the approach with the custom converter:

public static class MapEntryConverter implements Converter {

    public boolean canConvert(Class clazz) {
        return AbstractMap.class.isAssignableFrom(clazz);
    }

    public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {

        AbstractMap map = (AbstractMap) value;
        for (Object obj : map.entrySet()) {
            Entry entry = (Entry) obj;
            writer.startNode(entry.getKey().toString());
            context.convertAnother(entry.getValue());
            writer.endNode();
        }
    }

    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        // dunno, read manual and do it yourself ;)
    }

}

But i changed the the serialization of the maps value to delegate to the MarshallingContext. This should improve the solution to work for composite map values and nested maps as well.

Error importing Seaborn module in Python

You can try using Seaborn. It works for both 2.7 as well as 3.6. You can install it by running:

pip install seaborn

Replace Div Content onclick

Here's an approach:

HTML:

<div id="1">
    My Content 1
</div>

<div id="2" style="display:none;">
    My Dynamic Content
</div>
<button id="btnClick">Click me!</button>

jQuery:

$('#btnClick').on('click',function(){
    if($('#1').css('display')!='none'){
    $('#2').html('Here is my dynamic content').show().siblings('div').hide();
    }else if($('#2').css('display')!='none'){
        $('#1').show().siblings('div').hide();
    }
});


JsFiddle:
http://jsfiddle.net/ha6qp7w4/
http://jsfiddle.net/ha6qp7w4/4 <--- Commented

How to make a function wait until a callback has been called using node.js

One way to achieve this is to wrap the API call into a promise and then use await to wait for the result.

// let's say this is the API function with two callbacks,
// one for success and the other for error
function apiFunction(query, successCallback, errorCallback) {
    if (query == "bad query") {
        errorCallback("problem with the query");
    }
    successCallback("Your query was <" + query + ">");
}

// myFunction wraps the above API call into a Promise
// and handles the callbacks with resolve and reject
function apiFunctionWrapper(query) {
    return new Promise((resolve, reject) => {
        apiFunction(query,(successResponse) => {
            resolve(successResponse);
        }, (errorResponse) => {
            reject(errorResponse);
        });
    });
}

// now you can use await to get the result from the wrapped api function
// and you can use standard try-catch to handle the errors
async function businessLogic() {
    try {
        const result = await apiFunctionWrapper("query all users");
        console.log(result);
        
        // the next line will fail
        const result2 = await apiFunctionWrapper("bad query");
    } catch(error) {
        console.error("ERROR:" + error);
    }
}

// call the main function
businessLogic();

Output:

Your query was <query all users>
ERROR:problem with the query

Should try...catch go inside or outside a loop?

I'll put my $0.02 in. Sometimes you wind up needing to add a "finally" later on in your code (because who ever writes their code perfectly the first time?). In those cases, suddenly it makes more sense to have the try/catch outside the loop. For example:

try {
    for(int i = 0; i < max; i++) {
        String myString = ...;
        float myNum = Float.parseFloat(myString);
        dbConnection.update("MY_FLOATS","INDEX",i,"VALUE",myNum);
    }
} catch (NumberFormatException ex) {
    return null;
} finally {
    dbConnection.release();  // Always release DB connection, even if transaction fails.
}

Because if you get an error, or not, you only want to release your database connection (or pick your favorite type of other resource...) once.

True and False for && logic and || Logic table

I think You ask for Boolean algebra which describes the output of various operations performed on boolean variables. Just look at the article on Wikipedia.

Loop through JSON object List

Be careful, d is the list.

for (var i = 0; i < result.d.length; i++) { 
    alert(result.d[i].employeename);
}

CreateProcess: No such file or directory

So this is a stupid error message because it doesn't tell you what file it can't find.

Run the command again with the verbose flag gcc -v to see what gcc is up to.

In my case, it happened it was trying to call cc1plus. I checked, I don't have that. Installed mingw's C++ compiler and then I did.

How to make a page redirect using JavaScript?

You can achieve this using the location object.

location.href = "http://someurl"; 

Typescript - multidimensional array initialization

You can do the following (which I find trivial, but its actually correct). For anyone trying to find how to initialize a two-dimensional array in TypeScript (like myself).

Let's assume that you want to initialize a two-dimensional array, of any type. You can do the following

const myArray: any[][] = [];

And later, when you want to populate it, you can do the following:

myArray.push([<your value goes here>]);

A short example of the above can be the following:

const myArray: string[][] = [];
myArray.push(["value1", "value2"]);

Accessing variables from other functions without using global variables

If another function needs to use a variable you pass it to the function as an argument.

Also global variables are not inherently nasty and evil. As long as they are used properly there is no problem with them.

Aren't promises just callbacks?

Promises are not callbacks. A promise represents the future result of an asynchronous operation. Of course, writing them the way you do, you get little benefit. But if you write them the way they are meant to be used, you can write asynchronous code in a way that resembles synchronous code and is much more easy to follow:

api().then(function(result){
    return api2();
}).then(function(result2){
    return api3();
}).then(function(result3){
     // do work
});

Certainly, not much less code, but much more readable.

But this is not the end. Let's discover the true benefits: What if you wanted to check for any error in any of the steps? It would be hell to do it with callbacks, but with promises, is a piece of cake:

api().then(function(result){
    return api2();
}).then(function(result2){
    return api3();
}).then(function(result3){
     // do work
}).catch(function(error) {
     //handle any error that may occur before this point
});

Pretty much the same as a try { ... } catch block.

Even better:

api().then(function(result){
    return api2();
}).then(function(result2){
    return api3();
}).then(function(result3){
     // do work
}).catch(function(error) {
     //handle any error that may occur before this point
}).then(function() {
     //do something whether there was an error or not
     //like hiding an spinner if you were performing an AJAX request.
});

And even better: What if those 3 calls to api, api2, api3 could run simultaneously (e.g. if they were AJAX calls) but you needed to wait for the three? Without promises, you should have to create some sort of counter. With promises, using the ES6 notation, is another piece of cake and pretty neat:

Promise.all([api(), api2(), api3()]).then(function(result) {
    //do work. result is an array contains the values of the three fulfilled promises.
}).catch(function(error) {
    //handle the error. At least one of the promises rejected.
});

Hope you see Promises in a new light now.

How do Mockito matchers work?

Mockito matchers are static methods and calls to those methods, which stand in for arguments during calls to when and verify.

Hamcrest matchers (archived version) (or Hamcrest-style matchers) are stateless, general-purpose object instances that implement Matcher<T> and expose a method matches(T) that returns true if the object matches the Matcher's criteria. They are intended to be free of side effects, and are generally used in assertions such as the one below.

/* Mockito */  verify(foo).setPowerLevel(gt(9000));
/* Hamcrest */ assertThat(foo.getPowerLevel(), is(greaterThan(9000)));

Mockito matchers exist, separate from Hamcrest-style matchers, so that descriptions of matching expressions fit directly into method invocations: Mockito matchers return T where Hamcrest matcher methods return Matcher objects (of type Matcher<T>).

Mockito matchers are invoked through static methods such as eq, any, gt, and startsWith on org.mockito.Matchers and org.mockito.AdditionalMatchers. There are also adapters, which have changed across Mockito versions:

  • For Mockito 1.x, Matchers featured some calls (such as intThat or argThat) are Mockito matchers that directly accept Hamcrest matchers as parameters. ArgumentMatcher<T> extended org.hamcrest.Matcher<T>, which was used in the internal Hamcrest representation and was a Hamcrest matcher base class instead of any sort of Mockito matcher.
  • For Mockito 2.0+, Mockito no longer has a direct dependency on Hamcrest. Matchers calls phrased as intThat or argThat wrap ArgumentMatcher<T> objects that no longer implement org.hamcrest.Matcher<T> but are used in similar ways. Hamcrest adapters such as argThat and intThat are still available, but have moved to MockitoHamcrest instead.

Regardless of whether the matchers are Hamcrest or simply Hamcrest-style, they can be adapted like so:

/* Mockito matcher intThat adapting Hamcrest-style matcher is(greaterThan(...)) */
verify(foo).setPowerLevel(intThat(is(greaterThan(9000))));

In the above statement: foo.setPowerLevel is a method that accepts an int. is(greaterThan(9000)) returns a Matcher<Integer>, which wouldn't work as a setPowerLevel argument. The Mockito matcher intThat wraps that Hamcrest-style Matcher and returns an int so it can appear as an argument; Mockito matchers like gt(9000) would wrap that entire expression into a single call, as in the first line of example code.

What matchers do/return

when(foo.quux(3, 5)).thenReturn(true);

When not using argument matchers, Mockito records your argument values and compares them with their equals methods.

when(foo.quux(eq(3), eq(5))).thenReturn(true);    // same as above
when(foo.quux(anyInt(), gt(5))).thenReturn(true); // this one's different

When you call a matcher like any or gt (greater than), Mockito stores a matcher object that causes Mockito to skip that equality check and apply your match of choice. In the case of argumentCaptor.capture() it stores a matcher that saves its argument instead for later inspection.

Matchers return dummy values such as zero, empty collections, or null. Mockito tries to return a safe, appropriate dummy value, like 0 for anyInt() or any(Integer.class) or an empty List<String> for anyListOf(String.class). Because of type erasure, though, Mockito lacks type information to return any value but null for any() or argThat(...), which can cause a NullPointerException if trying to "auto-unbox" a null primitive value.

Matchers like eq and gt take parameter values; ideally, these values should be computed before the stubbing/verification starts. Calling a mock in the middle of mocking another call can interfere with stubbing.

Matcher methods can't be used as return values; there is no way to phrase thenReturn(anyInt()) or thenReturn(any(Foo.class)) in Mockito, for instance. Mockito needs to know exactly which instance to return in stubbing calls, and will not choose an arbitrary return value for you.

Implementation details

Matchers are stored (as Hamcrest-style object matchers) in a stack contained in a class called ArgumentMatcherStorage. MockitoCore and Matchers each own a ThreadSafeMockingProgress instance, which statically contains a ThreadLocal holding MockingProgress instances. It's this MockingProgressImpl that holds a concrete ArgumentMatcherStorageImpl. Consequently, mock and matcher state is static but thread-scoped consistently between the Mockito and Matchers classes.

Most matcher calls only add to this stack, with an exception for matchers like and, or, and not. This perfectly corresponds to (and relies on) the evaluation order of Java, which evaluates arguments left-to-right before invoking a method:

when(foo.quux(anyInt(), and(gt(10), lt(20)))).thenReturn(true);
[6]      [5]  [1]       [4] [2]     [3]

This will:

  1. Add anyInt() to the stack.
  2. Add gt(10) to the stack.
  3. Add lt(20) to the stack.
  4. Remove gt(10) and lt(20) and add and(gt(10), lt(20)).
  5. Call foo.quux(0, 0), which (unless otherwise stubbed) returns the default value false. Internally Mockito marks quux(int, int) as the most recent call.
  6. Call when(false), which discards its argument and prepares to stub method quux(int, int) identified in 5. The only two valid states are with stack length 0 (equality) or 2 (matchers), and there are two matchers on the stack (steps 1 and 4), so Mockito stubs the method with an any() matcher for its first argument and and(gt(10), lt(20)) for its second argument and clears the stack.

This demonstrates a few rules:

  • Mockito can't tell the difference between quux(anyInt(), 0) and quux(0, anyInt()). They both look like a call to quux(0, 0) with one int matcher on the stack. Consequently, if you use one matcher, you have to match all arguments.

  • Call order isn't just important, it's what makes this all work. Extracting matchers to variables generally doesn't work, because it usually changes the call order. Extracting matchers to methods, however, works great.

    int between10And20 = and(gt(10), lt(20));
    /* BAD */ when(foo.quux(anyInt(), between10And20)).thenReturn(true);
    // Mockito sees the stack as the opposite: and(gt(10), lt(20)), anyInt().
    
    public static int anyIntBetween10And20() { return and(gt(10), lt(20)); }
    /* OK */  when(foo.quux(anyInt(), anyIntBetween10And20())).thenReturn(true);
    // The helper method calls the matcher methods in the right order.
    
  • The stack changes often enough that Mockito can't police it very carefully. It can only check the stack when you interact with Mockito or a mock, and has to accept matchers without knowing whether they're used immediately or abandoned accidentally. In theory, the stack should always be empty outside of a call to when or verify, but Mockito can't check that automatically. You can check manually with Mockito.validateMockitoUsage().

  • In a call to when, Mockito actually calls the method in question, which will throw an exception if you've stubbed the method to throw an exception (or require non-zero or non-null values). doReturn and doAnswer (etc) do not invoke the actual method and are often a useful alternative.

  • If you had called a mock method in the middle of stubbing (e.g. to calculate an answer for an eq matcher), Mockito would check the stack length against that call instead, and likely fail.

  • If you try to do something bad, like stubbing/verifying a final method, Mockito will call the real method and also leave extra matchers on the stack. The final method call may not throw an exception, but you may get an InvalidUseOfMatchersException from the stray matchers when you next interact with a mock.

Common problems

  • InvalidUseOfMatchersException:

    • Check that every single argument has exactly one matcher call, if you use matchers at all, and that you haven't used a matcher outside of a when or verify call. Matchers should never be used as stubbed return values or fields/variables.

    • Check that you're not calling a mock as a part of providing a matcher argument.

    • Check that you're not trying to stub/verify a final method with a matcher. It's a great way to leave a matcher on the stack, and unless your final method throws an exception, this might be the only time you realize the method you're mocking is final.

  • NullPointerException with primitive arguments: (Integer) any() returns null while any(Integer.class) returns 0; this can cause a NullPointerException if you're expecting an int instead of an Integer. In any case, prefer anyInt(), which will return zero and also skip the auto-boxing step.

  • NullPointerException or other exceptions: Calls to when(foo.bar(any())).thenReturn(baz) will actually call foo.bar(null), which you might have stubbed to throw an exception when receiving a null argument. Switching to doReturn(baz).when(foo).bar(any()) skips the stubbed behavior.

General troubleshooting

  • Use MockitoJUnitRunner, or explicitly call validateMockitoUsage in your tearDown or @After method (which the runner would do for you automatically). This will help determine whether you've misused matchers.

  • For debugging purposes, add calls to validateMockitoUsage in your code directly. This will throw if you have anything on the stack, which is a good warning of a bad symptom.

Calculate distance between two latitude-longitude points? (Haversine formula)

here is an example in postgres sql (in km, for miles version, replace 1.609344 by 0.8684 version)

CREATE OR REPLACE FUNCTION public.geodistance(alat float, alng float, blat  

float, blng  float)
  RETURNS float AS
$BODY$
DECLARE
    v_distance float;
BEGIN

    v_distance = asin( sqrt(
            sin(radians(blat-alat)/2)^2 
                + (
                    (sin(radians(blng-alng)/2)^2) *
                    cos(radians(alat)) *
                    cos(radians(blat))
                )
          )
        ) * cast('7926.3352' as float) * cast('1.609344' as float) ;


    RETURN v_distance;
END 
$BODY$
language plpgsql VOLATILE SECURITY DEFINER;
alter function geodistance(alat float, alng float, blat float, blng float)
owner to postgres;

How to force a list to be vertical using html css

Hope this is your structure:

   <ul> 
     <li>
        <div ><img.. /><p>text</p></div>
    </li>
     <li>
        <div ><img.. /><p>text</p></div>
    </li>
     <li>
        <div ><img.. /><p>text</p></div>
    </li>
   </ul> 

By default, it will be add one after another row:

-----
-----
-----

if you want to make it vertical, just add float left to li, give width and height, make sure that content will not break the width:

|  |  |
|  |  |

li
{
   display:block;
   float:left;
   width:300px; /* adjust */
   height:150px; /* adjust */
   padding: 5px; /*adjust*/
}

Android disable screen timeout while app is running

this is the best way to solve this

 getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

Fastest JSON reader/writer for C++

https://github.com/quartzjer/js0n

Ugliest interface possible, but does what you ask. Zero allocations.

http://zserge.com/jsmn.html Another zero-allocation approach.

The solutions posted above all do dynamic memory allocation, hence will be inevitably end up slower at some point, depending on the data structure - and will be dangerous to include in a heap constrained environment like an embedded system.

Benchmarks of vjson, rapidjson and sajson here : http://chadaustin.me/2013/01/json-parser-benchmarking/ if you are interested in that sort of thing.

And to answer your "writer" part of the question i doubt that you could beat an efficient

printf("{%s:%s}",name,value)

implementation with any library - assuming your printf/sprintf implementation itself is lightweight of course.

EDIT: actually let me take that back, RapidJson allows on-stack allocation only through its MemoryPoolAllocator and actually makes this a default for its GenericReader. I havent done the comparison but i would expect it to be more robust than anything else listed here. It also doesnt have any dependencies, and it doesnt throw exceptions which probably makes it ultimately suitable for embedded. Fully header based lib so, easy to include anywhere.

how to hide a vertical scroll bar when not needed

Add this class in .css class

.scrol  { 
font: bold 14px Arial; 
border:1px solid black; 
width:100% ; 
color:#616D7E; 
height:20px; 
overflow:scroll; 
overflow-y:scroll;
overflow-x:hidden;
}

and use the class in div. like here.

<div> <p class = "scrol" id = "title">-</p></div>

I have attached image , you see the out put of the above code enter image description here

How to get these two divs side-by-side?

I found the below code very useful, it might help anyone who comes searching here

_x000D_
_x000D_
<html>_x000D_
<body>_x000D_
    <div style="width: 50%; height: 50%; background-color: green; float:left;">-</div>_x000D_
    <div style="width: 50%; height: 50%; background-color: blue; float:right;">-</div>_x000D_
    <div style="width: 100%; height: 50%; background-color: red; clear:both">-</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Run a mySQL query as a cron job?

Try creating a shell script like the one below:

#!/bin/bash

mysql --user=[username] --password=[password] --database=[db name] --execute="DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) ,  timestamp ) >=7"

You can then add this to the cron

Getting a better understanding of callback functions in JavaScript

You should check if the callback exists, and is an executable function:

if (callback && typeof(callback) === "function") {
    // execute the callback, passing parameters as necessary
    callback();
}

A lot of libraries (jQuery, dojo, etc.) use a similar pattern for their asynchronous functions, as well as node.js for all async functions (nodejs usually passes error and data to the callback). Looking into their source code would help!

jQuery hover and class selector

This can be achieved in CSS using the :hover pseudo-class. (:hover doesn't work on <div>s in IE6)

HTML:

<div id="menu">
   <a class="menuItem" href=#>Bla</a>
   <a class="menuItem" href=#>Bla</a>
   <a class="menuItem" href=#>Bla</a>
</div>

CSS:

.menuItem{
  height:30px;
  width:100px;
  background-color:#000;
}
.menuItem:hover {
  background-color:#F00;
}

Link and execute external JavaScript file hosted on GitHub

When a file is uploaded to github you can use it as external source or free hosting. Troy Alford has explained it well above. But to make it easier let me tell you some easy steps then you can use a github raw file in your site:

Here is your file's link:

https://raw.githubusercontent.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js

Now to execute it you have to remove https:// and the dot( . ) between raw and githubusercontent

Like this:

rawgithubusercontent.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js

Now when you will visit this link you will get a link that can be used to call your javascript:

Here is the final link:

https://rawgit.com/mindmup/bootstrap-wysiwyg/master/bootstrap-wysiwyg.js

Similarly if you host a css file you have to do it as mentioned above. It is the easiest way to get simple link to call your external css or javascript file hosted on github.

I hope this is helpful.

Referance URL: http://101helper.blogspot.com/2015/11/store-blogger-codes-on-github-boost-blogger-speed.html

How to call URL action in MVC with javascript function?

I'm going to give you 2 way's to call an action from the client side

first

If you just want to navigate to an action you should call just use the follow

window.location = "/Home/Index/" + youid

Notes: that you action need to handle a get type called

Second

If you need to render a View you could make the called by ajax

//this if you want get the html by get
public ActionResult Foo()
{
    return View(); //this return the render html   
}

And the client called like this "Assuming that you're using jquery"

$.get('your controller path', parameters to the controler , function callback)

or

$.ajax({
    type: "GET",
    url: "your controller path",
    data: parameters to the controler
    dataType: "html",
    success: your function
});

or

$('your selector').load('your controller path') 

Update

In your ajax called make this change to pass the data to the action

function onDropDownChange(e) {
var url = '/Home/Index' 
$.ajax({
        type: "GET",
        url: url,
        data: { id = e.value}, <--sending the values to the server
        dataType: "html",
        success : function (data) {
            //put your code here
        }
    });
}

UPDATE 2

You cannot do this in your callback 'windows.location ' if you want it's go render a view, you need to put a div in your view and do something like this

in the view where you are that have the combo in some place

<div id="theNewView"> </div> <---you're going to load the other view here

in the javascript client

$.ajax({
        type: "GET",
        url: url,
        data: { id = e.value}, <--sending the values to the server
        dataType: "html",
        success : function (data) {
            $('div#theNewView').html(data);
        }
    });
}

With this i think that you solve your problem

How to add parameters into a WebRequest?

The code below differs from all other code because at the end it prints the response string in the console that the request returns. I learned in previous posts that the user doesn't get the response Stream and displays it.

//Visual Basic Implementation Request and Response String
  Dim params = "key1=value1&key2=value2"
    Dim byteArray = UTF8.GetBytes(params)
    Dim url = "https://okay.com"
    Dim client = WebRequest.Create(url)
    client.Method = "POST"
    client.ContentType = "application/x-www-form-urlencoded"
    client.ContentLength = byteArray.Length
    Dim stream = client.GetRequestStream()

    //sending the data
    stream.Write(byteArray, 0, byteArray.Length)
    stream.Close()

//getting the full response in a stream        
Dim response = client.GetResponse().GetResponseStream()

//reading the response 
Dim result = New StreamReader(response)

//Writes response string to Console
    Console.WriteLine(result.ReadToEnd())
    Console.ReadKey()

How to get value by key from JObject?

This should help -

var json = "{'@STARTDATE': '2016-02-17 00:00:00.000',  '@ENDDATE': '2016-02-18 23:59:00.000' }";
var fdate = JObject.Parse(json)["@STARTDATE"];

list all files in the folder and also sub folders

Using you current code, make this tweak:

public void listf(String directoryName, List<File> files) {
    File directory = new File(directoryName);

    // Get all files from a directory.
    File[] fList = directory.listFiles();
    if(fList != null)
        for (File file : fList) {      
            if (file.isFile()) {
                files.add(file);
            } else if (file.isDirectory()) {
                listf(file.getAbsolutePath(), files);
            }
        }
    }
}

Folder structure for a Node.js project

This is indirect answer, on the folder structure itself, very related.

A few years ago I had same question, took a folder structure but had to do a lot directory moving later on, because the folder was meant for a different purpose than that I have read on internet, that is, what a particular folder does has different meanings for different people on some folders.

Now, having done multiple projects, in addition to explanation in all other answers, on the folder structure itself, I would strongly suggest to follow the structure of Node.js itself, which can be seen at: https://github.com/nodejs/node. It has great detail on all, say linters and others, what file and folder structure they have and where. Some folders have a README that explains what is in that folder.

Starting in above structure is good because some day a new requirement comes in and but you will have a scope to improve as it is already followed by Node.js itself which is maintained over many years now.

Hope this helps.

Cannot open include file with Visual Studio

I found this post because I was having the same error in Microsoft Visual C++. (Though it seems it's cause was a little different, than the above posted question.)

I had placed the file, I was trying to include, in the same directory, but it still could not be found.

My include looked like this: #include <ftdi.h>

But When I changed it to this: #include "ftdi.h" then it found it.

Java Object Null Check for method

public static double calculateInventoryTotal(Book[] arrayBooks) {

    final AtomicReference<BigDecimal> total = new AtomicReference<>(BigDecimal.ZERO);
    Optional.ofNullable(arrayBooks).map(Arrays::asList).ifPresent(books -> books.forEach(book -> total.accumulateAndGet(book.getPrice(), BigDecimal::add)));
    return total.get().doubleValue();

}

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

Get the _id of inserted document in Mongo database in NodeJS

@JSideris, sample code for getting insertedId.

db.collection(COLLECTION).insertOne(data, (err, result) => {
    if (err) 
      return err;
    else 
      return result.insertedId;
  });

Rails filtering array of objects by attribute value

If your attachments are

@attachments = Job.find(1).attachments

This will be array of attachment objects

Use select method to filter based on file_type.

@logos = @attachments.select { |attachment| attachment.file_type == 'logo' }
@images = @attachments.select { |attachment| attachment.file_type == 'image' }

This will not trigger any db query.

Filter values only if not null using lambda in Java8

you can use this

List<Car> requiredCars = cars.stream()
    .filter (t->  t!= null && StringUtils.startsWith(t.getName(),"M"))
    .collect(Collectors.toList());

Android: Getting a file URI from a content URI?

Trying to handle the URI with content:// scheme by calling ContentResolver.query()is not a good solution. On HTC Desire running 4.2.2 you could get NULL as a query result.

Why not to use ContentResolver instead? https://stackoverflow.com/a/29141800/3205334

Regex for string contains?

Just don't anchor your pattern:

/Test/

The above regex will check for the literal string "Test" being found somewhere within it.

Switch case with conditions

You should not use switch for this scenario. This is the proper approach:

var cnt = $("#div1 p").length;

alert(cnt);

if (cnt >= 10 && cnt <= 20)
{
   alert('10');
}
else if (cnt >= 21 && cnt <= 30)
{
   alert('21');
}
else if (cnt >= 31 && cnt <= 40)
{
   alert('31');
}
else 
{
   alert('>41');
}

How do I add more members to my ENUM-type column in MySQL?

ALTER TABLE
    `table_name`
MODIFY COLUMN
    `column_name2` enum(
        'existing_value1',
        'existing_value2',
        'new_value1',
        'new_value2'
    )
NOT NULL AFTER `column_name1`;

Get element type with jQuery

Use Nodename over tagName :

nodeName contains all functionalities of tagName, plus a few more. Therefore nodeName is always the better choice.

see DOM Core

Get text of label with jquery

Try using the html() function.

$('#<%=Label1.ClientID%>').html();

You're also missing the # to make it an ID you're searching for. Without the #, it's looking for a tag type.

Split string with PowerShell and do something with each token

Another way to accomplish this is a combination of Justus Thane's and mklement0's answers. It doesn't make sense to do it this way when you look at a one liner example, but when you're trying to mass-edit a file or a bunch of filenames it comes in pretty handy:

$test = '   One      for the money   '
$option = [System.StringSplitOptions]::RemoveEmptyEntries
$($test.split(' ',$option)).foreach{$_}

This will come out as:

One
for
the
money

Java ResultSet how to check if there are any results

ResultSet rs = rs.executeQuery();
if(rs.next())
{
  rs = rs.executeQuery();
  while(rs.next())
  {
    //do code part
  }
}
else
{
  //else if no result set
}

It is better to re execute query because when we call if(rs.next()){....} first row of ResultSet will be executed and after it inside while(rs.next()){....} we'll get result from next line. So I think re-execution of query inside if is the better option.

Bootstrap dropdown not working

Here what i did is .....

Just removed bootstrap.min.js from my Project and added bootstrap.js to it and it started working........

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                  "~/Scripts/bootstrap.js"
                  //"~/Scripts/bootstrap.min.js"));

Div with horizontal scrolling only

The solution is fairly straight forward. To ensure that we don't impact the width of the cells in the table, we'll turn off white-space. To ensure we get a horizontal scroll bar, we'll turn on overflow-x. And that's pretty much it:

.container {
    width: 30em;
    overflow-x: auto;
    white-space: nowrap;
}

You can see the end-result here, or in the animation below. If the table determines the height of your container, you should not need to explicitly set overflow-y to hidden. But understand that is also an option.

enter image description here

Get device token for push notification

And the Swift version of the Wasif's answer:

Swift 2.x

var token = deviceToken.description.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>"))
token = token.stringByReplacingOccurrencesOfString(" ", withString: "")
print("Token is \(token)")

Update for Swift 3

let deviceTokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()

How to check if any fields in a form are empty in php

your form is missing the method...

<form name="registrationform" action="register.php" method="post"> //here

anywyas to check the posted data u can use isset()..

Determine if a variable is set and is not NULL

if(!isset($firstname) || trim($firstname) == '')
{
   echo "You did not fill out the required fields.";
}

How merge two objects array in angularjs?

This works for me :

$scope.array1 = $scope.array1.concat(array2)

In your case it would be :

$scope.actions.data = $scope.actions.data.concat(data)

How do I split a string, breaking at a particular character?

You can use split to split the text.

As an alternative, you can also use match as follow

_x000D_
_x000D_
var str = 'john smith~123 Street~Apt 4~New York~NY~12345';_x000D_
matches = str.match(/[^~]+/g);_x000D_
_x000D_
console.log(matches);_x000D_
document.write(matches);
_x000D_
_x000D_
_x000D_

The regex [^~]+ will match all the characters except ~ and return the matches in an array. You can then extract the matches from it.

Runnable with a parameter?

You could put it in a function.

String paramStr = "a parameter";
Runnable myRunnable = createRunnable(paramStr);

private Runnable createRunnable(final String paramStr){

    Runnable aRunnable = new Runnable(){
        public void run(){
            someFunc(paramStr);
        }
    };

    return aRunnable;

}

(When I used this, my parameter was an integer ID, which I used to make a hashmap of ID --> myRunnables. That way, I can use the hashmap to post/remove different myRunnable objects in a handler.)

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

Basically, you need to redirect out of that page but it still can make a problem while your internet slow (Redirect header from serverside)

Example of basic scenario :

Click on submit button twice

Way to solve

  • Client side

  • Server side

    • Using differentiate based hashing timestamp / timestamp when request was sent.
    • Userequest tokens. When the main loads up assign a temporary request tocken which if repeated is ignored.

What is SOA "in plain english"?

Only one suggestion:-

Read SOA Concepts, Technology and Design by Thomas Erl.

It has very beautifully given the details about SOA in plain English and with case studies.

Difference between Interceptor and Filter in Spring MVC

From HandlerIntercepter's javadoc:

HandlerInterceptor is basically similar to a Servlet Filter, but in contrast to the latter it just allows custom pre-processing with the option of prohibiting the execution of the handler itself, and custom post-processing. Filters are more powerful, for example they allow for exchanging the request and response objects that are handed down the chain. Note that a filter gets configured in web.xml, a HandlerInterceptor in the application context.

As a basic guideline, fine-grained handler-related pre-processing tasks are candidates for HandlerInterceptor implementations, especially factored-out common handler code and authorization checks. On the other hand, a Filter is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.

With that being said:

So where is the difference between Interceptor#postHandle() and Filter#doFilter()?

postHandle will be called after handler method invocation but before the view being rendered. So, you can add more model objects to the view but you can not change the HttpServletResponse since it's already committed.

doFilter is much more versatile than the postHandle. You can change the request or response and pass it to the chain or even block the request processing.

Also, in preHandle and postHandle methods, you have access to the HandlerMethod that processed the request. So, you can add pre/post-processing logic based on the handler itself. For example, you can add a logic for handler methods that have some annotations.

What is the best practise in which use cases it should be used?

As the doc said, fine-grained handler-related pre-processing tasks are candidates for HandlerInterceptor implementations, especially factored-out common handler code and authorization checks. On the other hand, a Filter is well-suited for request content and view content handling, like multipart forms and GZIP compression. This typically shows when one needs to map the filter to certain content types (e.g. images), or to all requests.

How to find out which package version is loaded in R?

Use the following code to obtain the version of R packages installed in the system:

installed.packages(fields = c ("Package", "Version"))

How do I write a backslash (\) in a string?

The backslash ("\") character is a special escape character used to indicate other special characters such as new lines (\n), tabs (\t), or quotation marks (\").

If you want to include a backslash character itself, you need two backslashes or use the @ verbatim string:

var s = "\\Tasks";
// or 
var s = @"\Tasks";

Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.

Generally speaking, most C# .NET developers tend to favour using the @ verbatim strings when building file/folder paths since it saves them from having to write double backslashes all the time and they can directly copy/paste the path, so I would suggest that you get in the habit of doing the same.


That all said, in this case, I would actually recommend you use the Path.Combine utility method as in @lordkain's answer as then you don't need to worry about whether backslashes are already included in the paths and accidentally doubling-up the slashes or omitting them altogether when combining parts of paths.

How to create a private class method?

Just for the completeness, we can also avoid declaring private_class_method in a separate line. I personally don't like this usage but good to know that it exists.

private_class_method  def self.method_name
 ....
end

Easier way to debug a Windows service

The best option is to use the 'System.Diagnostics' namespace.

Enclose your code in if else block for debug mode and release mode as shown below to switch between debug and release mode in visual studio,

#if DEBUG  // for debug mode
       **Debugger.Launch();**  //debugger will hit here
       foreach (var job in JobFactory.GetJobs())
            {
                //do something 
            }

#else    // for release mode
      **Debugger.Launch();**  //debugger will hit here
     // write code here to do something in Release mode.

#endif

How to list AD group membership for AD users using input list?

The below code will return username group membership using the samaccountname. You can modify it to get input from a file or change the query to get accounts with non expiring passwords etc

$location = "c:\temp\Peace2.txt"
$users = (get-aduser -filter *).samaccountname
$le = $users.length
for($i = 0; $i -lt $le; $i++){
  $output = (get-aduser $users[$i] | Get-ADPrincipalGroupMembership).name
  $users[$i] + " " + $output 
  $z =  $users[$i] + " " + $output 
  add-content $location $z
}

Sample Output:

Administrator Domain Users Administrators Schema Admins Enterprise Admins Domain Admins Group Policy Creator Owners
Guest Domain Guests Guests
krbtgt Domain Users Denied RODC Password Replication Group
Redacted Domain Users CompanyUsers Production
Redacted Domain Users CompanyUsers Production
Redacted Domain Users CompanyUsers Production

Apache error: _default_ virtualhost overlap on port 443

On a vanilla Apache2 install in CentOS, when you install mod_ssl it will automatically add a configuration file in:

{apache_dir}/conf.d/ssl.conf

This configuration file contains a default virtual host definition for port 443, named default:443. If you also have your own virtual host definition for 443 (i.e. in httpd.conf) then you will have a confict. Since the conf.d files are included first, they will win over yours.

To solve the conflict you can either remove the virtual host definition from conf.d/ssl.conf or update it to your own settings.

Select multiple columns in data.table by their numeric indices

From v1.10.2 onwards, you can also use ..

dt <- data.table(a=1:2, b=2:3, c=3:4)

keep_cols = c("a", "c")

dt[, ..keep_cols]

How to clear cache in Yarn?

Also note that the cached directory is located in ~/.yarn-cache/:

yarn cache clean: cleans that directory

yarn cache list: shows the list of cached dependencies

yarn cache dir: prints out the path of your cached directory

Check if all values in list are greater than a certain number

 a = [[a, 2], [b, 3], [c, 4], [d, 5], [a, 1], [b, 6], [e, 7], [h, 8]]

I need this from above one

 a = [[a, 3], [b, 9], [c, 4], [d, 5], [e, 7], [h, 8]]
a.append([0, 0])
for i in range(len(a)):
     for j in range(i + 1, len(a) - 1):
            if a[i][0] == a[j][0]:
                    a[i][1] += a[j][1]
                    del a[j]
a.pop()
        

How can I show the table structure in SQL Server query?

For SQL Server, if using a newer version, you can use

select *
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME='tableName'

There are different ways to get the schema. Using ADO.NET, you can use the schema methods. Use the DbConnection's GetSchema method or the DataReader'sGetSchemaTable method.

Provided that you have a reader for the for the query, you can do something like this:

using(DbCommand cmd = ...)
using(var reader = cmd.ExecuteReader())
{
    var schema = reader.GetSchemaTable();
    foreach(DataRow row in schema.Rows)
    {
        Debug.WriteLine(row["ColumnName"] + " - " + row["DataTypeName"])
    }
}

See this article for further details.

Sequence Permission in Oracle

To grant a permission:

grant select on schema_name.sequence_name to user_or_role_name;

To check which permissions have been granted

select * from all_tab_privs where TABLE_NAME = 'sequence_name'

Does hosts file exist on the iPhone? How to change it?

This doesn't directly answer your question, but it does solve your problem...

What make of router do you have? Your router firmware may allow you to set DNS records for your local network. This is what I do with the Tomato firmware

ImportError: DLL load failed: The specified module could not be found

For Windows 10 x64 and Python:

Open a Visual Studio x64 command prompt, and use dumpbin:

dumpbin /dependents [Python Module DLL or PYD file]

If you do not have Visual Studio installed, it is possible to download dumpbin elsewhere, or use another utility such as Dependency Walker.

Note that all other answers (to date) are simply random stabs in the dark, whereas this method is closer to a sniper rifle with night vision.

Case study 1

  1. I switched on Address Sanitizer for a Python module that I wrote using C++ using MSVC and CMake.

  2. It was giving this error: ImportError: DLL load failed: The specified module could not be found

  3. Opened a Visual Studio x64 command prompt.

  4. Under Windows, a .pyd file is a .dll file in disguise, so we want to run dumpbin on this file.

  5. cd MyLibrary\build\lib.win-amd64-3.7\Debug

  6. dumpbin /dependents MyLibrary.cp37-win_amd64.pyd which prints this:

    Microsoft (R) COFF/PE Dumper Version 14.27.29112.0
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    
    Dump of file MyLibrary.cp37-win_amd64.pyd
    
    File Type: DLL
    
      Image has the following dependencies:
    
        clang_rt.asan_dbg_dynamic-x86_64.dll
        gtestd.dll
        tbb_debug.dll
        python37.dll
        KERNEL32.dll
        MSVCP140D.dll
        VCOMP140D.DLL
        VCRUNTIME140D.dll
        VCRUNTIME140_1D.dll
        ucrtbased.dll
    
      Summary
    
         1000 .00cfg
        D6000 .data
         7000 .idata
        46000 .pdata
       341000 .rdata
        23000 .reloc
         1000 .rsrc
       856000 .text
    
  7. Searched for clang_rt.asan_dbg_dynamic-x86_64.dll, copied it into the same directory, problem solved.

  8. Alternatively, could update the environment variable PATH to point to the directory with the missing .dll.

Please feel free to add your own case studies here! I've made it a community wiki answer.

Node.js heap out of memory

For angular project bundling, I've added the below line to my pakage.json file in the scripts section.

"build-prod": "node --max_old_space_size=5120 ./node_modules/@angular/cli/bin/ng build --prod --base-href /"

Now, to bundle my code, I use npm run build-prod instead of ng build --requiredFlagsHere

hope this helps!

How can I get screen resolution in java?

These three functions return the screen size in Java. This code accounts for multi-monitor setups and task bars. The included functions are: getScreenInsets(), getScreenWorkingArea(), and getScreenTotalArea().

Code:

/**
 * getScreenInsets, This returns the insets of the screen, which are defined by any task bars
 * that have been set up by the user. This function accounts for multi-monitor setups. If a
 * window is supplied, then the the monitor that contains the window will be used. If a window
 * is not supplied, then the primary monitor will be used.
 */
static public Insets getScreenInsets(Window windowOrNull) {
    Insets insets;
    if (windowOrNull == null) {
        insets = Toolkit.getDefaultToolkit().getScreenInsets(GraphicsEnvironment
                .getLocalGraphicsEnvironment().getDefaultScreenDevice()
                .getDefaultConfiguration());
    } else {
        insets = windowOrNull.getToolkit().getScreenInsets(
                windowOrNull.getGraphicsConfiguration());
    }
    return insets;
}

/**
 * getScreenWorkingArea, This returns the working area of the screen. (The working area excludes
 * any task bars.) This function accounts for multi-monitor setups. If a window is supplied,
 * then the the monitor that contains the window will be used. If a window is not supplied, then
 * the primary monitor will be used.
 */
static public Rectangle getScreenWorkingArea(Window windowOrNull) {
    Insets insets;
    Rectangle bounds;
    if (windowOrNull == null) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        insets = Toolkit.getDefaultToolkit().getScreenInsets(ge.getDefaultScreenDevice()
                .getDefaultConfiguration());
        bounds = ge.getDefaultScreenDevice().getDefaultConfiguration().getBounds();
    } else {
        GraphicsConfiguration gc = windowOrNull.getGraphicsConfiguration();
        insets = windowOrNull.getToolkit().getScreenInsets(gc);
        bounds = gc.getBounds();
    }
    bounds.x += insets.left;
    bounds.y += insets.top;
    bounds.width -= (insets.left + insets.right);
    bounds.height -= (insets.top + insets.bottom);
    return bounds;
}

/**
 * getScreenTotalArea, This returns the total area of the screen. (The total area includes any
 * task bars.) This function accounts for multi-monitor setups. If a window is supplied, then
 * the the monitor that contains the window will be used. If a window is not supplied, then the
 * primary monitor will be used.
 */
static public Rectangle getScreenTotalArea(Window windowOrNull) {
    Rectangle bounds;
    if (windowOrNull == null) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        bounds = ge.getDefaultScreenDevice().getDefaultConfiguration().getBounds();
    } else {
        GraphicsConfiguration gc = windowOrNull.getGraphicsConfiguration();
        bounds = gc.getBounds();
    }
    return bounds;
}

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

I had this problem. I searched the internet, took all advices, changes configurations, but the problem is still there. Finally with the help of the server administrator, he found that the problem lies in MySQL database column definition. one of the columns in the a table was assigned to 'Longtext' which leads to allocate 4,294,967,295 bites of memory. It seems working OK if you don't use MySqli prepare statement, but once you use prepare statement, it tries to allocate that amount of memory. I changed the column type to Mediumtext which needs 16,777,215 bites of memory space. The problem is gone. Hope this help.

How to put a horizontal divisor line between edit text's in a activity

Use This..... You will love it

 <TextView
    android:layout_width="fill_parent"
    android:layout_height="1px"
    android:text=" "
    android:background="#anycolor"
    android:id="@+id/textView"/>

Difficulty with ng-model, ng-repeat, and inputs

You get into a difficult situation when it is necessary to understand how scopes, ngRepeat and ngModel with NgModelController work. Also try to use 1.0.3 version. Your example will work a little differently.

You can simply use solution provided by jm-

But if you want to deal with the situation more deeply, you have to understand:

  • how AngularJS works;
  • scopes have a hierarchical structure;
  • ngRepeat creates new scope for every element;
  • ngRepeat build cache of items with additional information (hashKey); on each watch call for every new item (that is not in the cache) ngRepeat constructs new scope, DOM element, etc. More detailed description.
  • from 1.0.3 ngModelController rerenders inputs with actual model values.

How your example "Binding to each element directly" works for AngularJS 1.0.3:

  • you enter letter 'f' into input;
  • ngModelController changes model for item scope (names array is not changed) => name == 'Samf', names == ['Sam', 'Harry', 'Sally'];
  • $digest loop is started;
  • ngRepeat replaces model value from item scope ('Samf') by value from unchanged names array ('Sam');
  • ngModelController rerenders input with actual model value ('Sam').

How your example "Indexing into the array" works:

  • you enter letter 'f' into input;
  • ngModelController changes item in names array => `names == ['Samf', 'Harry', 'Sally'];
  • $digest loop is started;
  • ngRepeat can't find 'Samf' in cache;
  • ngRepeat creates new scope, adds new div element with new input (that is why the input field loses focus - old div with old input is replaced by new div with new input);
  • new values for new DOM elements are rendered.

Also, you can try to use AngularJS Batarang and see how changes $id of the scope of div with input in which you enter.

Unit Testing: DateTime.Now

Using ITimeProvider we were forced to take it into special shared common project that must be referenced from the rest of other projects. But this complicated the control of dependencies.

We searched for the ITimeProvider in the .NET framework. We searched for the NuGet package, and found one that can't work with DateTimeOffset.

So we came up with our own solution, which depends only on the types of the standard library. We're using an instance of Func<DateTimeOffset>.

How to use

public class ThingThatNeedsTimeProvider
{
    private readonly Func<DateTimeOffset> now;
    private int nextId;

    public ThingThatNeedsTimeProvider(Func<DateTimeOffset> now)
    {
        this.now = now;
        this.nextId = 1;
    }

    public (int Id, DateTimeOffset CreatedAt) MakeIllustratingTuple()
    {
        return (nextId++, now());
    }
}

How to register

Autofac

builder.RegisterInstance<Func<DateTimeOffset>>(() => DateTimeOffset.Now);

(For future editors: append your cases here).

How to unit test

public void MakeIllustratingTuple_WhenCalled_FillsCreatedAt()
{
    DateTimeOffset expected = CreateRandomDateTimeOffset();
    DateTimeOffset StubNow() => expected;
    var thing = new ThingThatNeedsTimeProvider(StubNow);

    var (_, actual) = thing.MakeIllustratingTuple();

    Assert.AreEqual(expected, actual);
}

How to return part of string before a certain character?

And note that first argument of subString is 0 based while second is one based.

Example:

String str= "0123456";
String sbstr= str.substring(0,5);

Output will be sbstr= 01234 and not sbstr = 012345

convert HTML ( having Javascript ) to PDF using JavaScript

You can do it using a jquery,

Use this code to link the button...

$(document).ready(function() {
    $("#button_id").click(function() {
        window.print();
        return false;
    });
});

This link may be also helpful: jQuery Print HTML Pdf Page Options Link

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

This answer is intended as an addendum to the highest rated answer on this thread by paaacman. I just wanted to add some helpful detail for users like myself who don't know their way around Windows 10 as well.

Windows 10 runs IIS (Internet Information Services, Microsoft's web server software) automatically during Startup on Port 80. In order to use Apache Server on that port, IIS must be stopped.

paaacman's response refers to the IIS server as "W3SVC", or the "World Wide Web Publishing Service". I suppose that's because Windows 10 runs IIS as a service. In order to disable it or modify how the service runs, you need to know where to find "Services" in your system.

I found the easiest way there was to click on the search button next to the start menu button in the Windows 10 taskbar and type "Administrative Tools". You can either hit return or click on the "Administrative Tools" link that Windows finds for you.

A control panel window will open with a list of tools. The one you want is "Services." Double-click it.

Another window will open called "Services." Locate the one named "World Wide Web Publishing Service." Some other users in this thread have listed what it is called in other languages, if your list is not in English.

If you only want to turn off the IIS server for this Windows session, but want it to run automatically again the next time you start up Windows, right-click "World Wide Web Publishing Service" and choose "Stop." The server will stop, and Port 80 will be freed up for Apache (or whatever else you want to use it for).

If you want to prevent the IIS server from running automatically when you start up Windows in the future, right-click "World Wide Web Publishing Serivce" and select "Properties." In the window that appears, locate the "Startup type" dropdown, and set it "Manual." Click "Apply" or "OK" to save your changes. You should be all set.

How to map atan2() to degrees 0-360

Here's some javascript. Just input x and y values.

var angle = (Math.atan2(x,y) * (180/Math.PI) + 360) % 360;

Add / remove input field dynamically with jQuery

I took the liberty of putting together a jsFiddle illustrating the functionality of building a custom form using jQuery. Here it is...

EDIT: Updated the jsFiddle to include remove buttons for each field.

EDIT: As per the request in the last comment, code from the jsFiddle is below.

EDIT: As per Abhishek's comment, I have updated the jsFiddle (and code below) to cater for scenarios where duplicate field IDs might arise.

HTML:

<fieldset id="buildyourform">
    <legend>Build your own form!</legend>
</fieldset>
<input type="button" value="Preview form" class="add" id="preview" />
<input type="button" value="Add a field" class="add" id="add" />

JavaScript:

$(document).ready(function() {
    $("#add").click(function() {
        var lastField = $("#buildyourform div:last");
        var intId = (lastField && lastField.length && lastField.data("idx") + 1) || 1;
        var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
        fieldWrapper.data("idx", intId);
        var fName = $("<input type=\"text\" class=\"fieldname\" />");
        var fType = $("<select class=\"fieldtype\"><option value=\"checkbox\">Checked</option><option value=\"textbox\">Text</option><option value=\"textarea\">Paragraph</option></select>");
        var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
        removeButton.click(function() {
            $(this).parent().remove();
        });
        fieldWrapper.append(fName);
        fieldWrapper.append(fType);
        fieldWrapper.append(removeButton);
        $("#buildyourform").append(fieldWrapper);
    });
    $("#preview").click(function() {
        $("#yourform").remove();
        var fieldSet = $("<fieldset id=\"yourform\"><legend>Your Form</legend></fieldset>");
        $("#buildyourform div").each(function() {
            var id = "input" + $(this).attr("id").replace("field","");
            var label = $("<label for=\"" + id + "\">" + $(this).find("input.fieldname").first().val() + "</label>");
            var input;
            switch ($(this).find("select.fieldtype").first().val()) {
                case "checkbox":
                    input = $("<input type=\"checkbox\" id=\"" + id + "\" name=\"" + id + "\" />");
                    break;
                case "textbox":
                    input = $("<input type=\"text\" id=\"" + id + "\" name=\"" + id + "\" />");
                    break;
                case "textarea":
                    input = $("<textarea id=\"" + id + "\" name=\"" + id + "\" ></textarea>");
                    break;    
            }
            fieldSet.append(label);
            fieldSet.append(input);
        });
        $("body").append(fieldSet);
    });
});

CSS:

body
{
    font-family:Gill Sans MT;
    padding:10px;
}
fieldset
{
    border: solid 1px #000;
    padding:10px;
    display:block;
    clear:both;
    margin:5px 0px;
}
legend
{
    padding:0px 10px;
    background:black;
    color:#FFF;
}
input.add
{
    float:right;
}
input.fieldname
{
    float:left;
    clear:left;
    display:block;
    margin:5px;
}
select.fieldtype
{
    float:left;
    display:block;
    margin:5px;
}
input.remove
{
    float:left;
    display:block;
    margin:5px;
}
#yourform label
{
    float:left;
    clear:left;
    display:block;
    margin:5px;
}
#yourform input, #yourform textarea
{
    float:left;
    display:block;
    margin:5px;
}

Android: textview hyperlink

This is my working implementation

private void showMessage()
    {

        lblMessage.setText("");

        List<String> messages = db.getAllGCMMessages();

        for (int k = messages.size() - 1; k >= 0; --k)
         {

            String message  =  messages.get(k).toString();
            lblMessage.append(message + "\n\n");

         }
     Linkify.addLinks(lblMessage, Linkify.ALL);
  }

and to change color of hyperlinks , i editted my xml for textview -

 android:textColorLink="#69463d"

How do you enable mod_rewrite on any OS?

if it related to hosting site then ask to your hosting or if you want to enable it in local machine then check this youtube step by step tutorial related to enabling rewrite module in wamp apache https://youtu.be/xIspOX9FuVU?t=1m43s
Wamp server icon -> Apache -> Apache Modules and check the rewrite module option it should be checked but after that wamp require restart all services

Regular expression for first and last name

I have searched and searched and played and played with it and although it is not perfect it may help others making the attempt to validate first and last names that have been provided as one variable.

In my case, that variable is $name.

I used the following code for my PHP:

    if (preg_match('/\b([A-Z]{1}[a-z]{1,30}[- ]{0,1}|[A-Z]{1}[- \']{1}[A-Z]{0,1}  
    [a-z]{1,30}[- ]{0,1}|[a-z]{1,2}[ -\']{1}[A-Z]{1}[a-z]{1,30}){2,5}/', $name)  
    # there is no space line break between in the above "if statement", any that   
    # you notice or perceive are only there for formatting purposes.  
    # 
    # pass - successful match - do something
    } else {
    # fail - unsuccessful match - do something

I am learning RegEx myself but I do have the explanation for the code as provided by RegEx buddy.
Here it is:

Assert position at a word boundary «\b»

Match the regular expression below and capture its match into backreference number 1
«([A-Z]{1}[a-z]{1,30}[- ]{0,1}|[A-Z]{1}[- \']{1}[A-Z]{0,1}[a-z]{1,30}[- ]{0,1}|[a-z]{1,2}[ -\']{1}[A-Z]{1}[a-z]{1,30}){2,5}»

Between 2 and 5 times, as many times as possible, giving back as needed (greedy) «{2,5}»

* I NEED SOME HELP HERE WITH UNDERSTANDING THE RAMIFICATIONS OF THIS NOTE *

Note: I repeated the capturing group itself. The group will capture only the last iteration. Put a capturing group around the repeated group to capture all iterations. «{2,5}»

Match either the regular expression below (attempting the next alternative only if this one fails) «[A-Z]{1}[a-z]{1,30}[- ]{0,1}»

Match a single character in the range between “A” and “Z” «[A-Z]{1}»

Exactly 1 times «{1}»

Match a single character in the range between “a” and “z” «[a-z]{1,30}»

Between one and 30 times, as many times as possible, giving back as needed (greedy) «{1,30}»

Match a single character present in the list “- ” «[- ]{0,1}»

Between zero and one times, as many times as possible, giving back as needed (greedy) «{0,1}»

Or match regular expression number 2 below (attempting the next alternative only if this one fails) «[A-Z]{1}[- \']{1}[A-Z]{0,1}[a-z]{1,30}[- ]{0,1}»

Match a single character in the range between “A” and “Z” «[A-Z]{1}»

Exactly 1 times «{1}»

Match a single character present in the list below «[- \']{1}»

Exactly 1 times «{1}»

One of the characters “- ” «- » A ' character «\'»

Match a single character in the range between “A” and “Z” «[A-Z]{0,1}»

Between zero and one times, as many times as possible, giving back as needed (greedy) «{0,1}»

Match a single character in the range between “a” and “z” «[a-z]{1,30}»

Between one and 30 times, as many times as possible, giving back as needed (greedy) «{1,30}»

Match a single character present in the list “- ” «[- ]{0,1}»

Between zero and one times, as many times as possible, giving back as needed (greedy) «{0,1}»

Or match regular expression number 3 below (the entire group fails if this one fails to match) «[a-z]{1,2}[ -\']{1}[A-Z]{1}[a-z]{1,30}»

Match a single character in the range between “a” and “z” «[a-z]{1,2}»

Between one and 2 times, as many times as possible, giving back as needed (greedy) «{1,2}»

Match a single character in the range between “ ” and “'” «[ -\']{1}»

Exactly 1 times «{1}»

Match a single character in the range between “A” and “Z” «[A-Z]{1}»

Exactly 1 times «{1}»

Match a single character in the range between “a” and “z” «[a-z]{1,30}»

Between one and 30 times, as many times as possible, giving back as needed (greedy) «{1,30}»

I know this validation totally assumes that every person filling out the form has a western name and that may eliminates the vast majority of folks in the world. However, I feel like this is a step in the proper direction. Perhaps this regular expression is too basic for the gurus to address simplistically or maybe there is some other reason that I was unable to find the above code in my searches. I spent way too long trying to figure this bit out, you will probably notice just how foggy my mind is on all this if you look at my test names below.

I tested the code on the following names and the results are in parentheses to the right of each name.

  1. STEVE SMITH (fail)
  2. Stev3 Smith (fail)
  3. STeve Smith (fail)
  4. Steve SMith (fail)
  5. Steve Sm1th (passed on the Steve Sm)
  6. d'Are to Beaware (passed on the Are to Beaware)
  7. Jo Blow (passed)
  8. Hyoung Kyoung Wu (passed)
  9. Mike O'Neal (passed)
  10. Steve Johnson-Smith (passed)
  11. Jozef-Schmozev Hiemdel (passed)
  12. O Henry Smith (passed)
  13. Mathais d'Arras (passed)
  14. Martin Luther King Jr (passed)
  15. Downtown-James Brown (passed)
  16. Darren McCarty (passed)
  17. George De FunkMaster (passed)
  18. Kurtis B-Ball Basketball (passed)
  19. Ahmad el Jeffe (passed)

If you have basic names, there must be more than one up to five for the above code to work, that are similar to those that I used during testing, this code might be for you.

If you have any improvements, please let me know. I am just in the early stages (first few months of figuring out RegEx.

Thanks and good luck, Steve

How should I do integer division in Perl?

You can cast ints in Perl:

int(5/1.5) = 3;

How to get a key in a JavaScript object by its value?

I use this function:

Object.prototype.getKey = function(value){
  for(var key in this){
    if(this[key] == value){
      return key;
    }
  }
  return null;
};

Usage:

// ISO 639: 2-letter codes
var languageCodes = {
  DA: 'Danish',
  DE: 'German',
  DZ: 'Bhutani',
  EL: 'Greek',
  EN: 'English',
  EO: 'Esperanto',
  ES: 'Spanish'
};

var key = languageCodes.getKey('Greek');
console.log(key); // EL

Python class returning value

I think you are very confused about what is occurring.

In Python, everything is an object:

  • [] (a list) is an object
  • 'abcde' (a string) is an object
  • 1 (an integer) is an object
  • MyClass() (an instance) is an object
  • MyClass (a class) is also an object
  • list (a type--much like a class) is also an object

They are all "values" in the sense that they are a thing and not a name which refers to a thing. (Variables are names which refer to values.) A value is not something different from an object in Python.

When you call a class object (like MyClass() or list()), it returns an instance of that class. (list is really a type and not a class, but I am simplifying a bit here.)

When you print an object (i.e. get a string representation of an object), that object's __str__ or __repr__ magic method is called and the returned value printed.

For example:

>>> class MyClass(object):
...     def __str__(self):
...             return "MyClass([])"
...     def __repr__(self):
...             return "I am an instance of MyClass at address "+hex(id(self))
... 
>>> m = MyClass()
>>> print m
MyClass([])
>>> m
I am an instance of MyClass at address 0x108ed5a10
>>> 

So what you are asking for, "I need that MyClass return a list, like list(), not the instance info," does not make any sense. list() returns a list instance. MyClass() returns a MyClass instance. If you want a list instance, just get a list instance. If the issue instead is what do these objects look like when you print them or look at them in the console, then create a __str__ and __repr__ method which represents them as you want them to be represented.

Update for new question about equality

Once again, __str__ and __repr__ are only for printing, and do not affect the object in any other way. Just because two objects have the same __repr__ value does not mean they are equal!

MyClass() != MyClass() because your class does not define how these would be equal, so it falls back to the default behavior (of the object type), which is that objects are only equal to themselves:

>>> m = MyClass()
>>> m1 = m
>>> m2 = m
>>> m1 == m2
True
>>> m3 = MyClass()
>>> m1 == m3
False

If you want to change this, use one of the comparison magic methods

For example, you can have an object that is equal to everything:

>>> class MyClass(object):
...     def __eq__(self, other):
...             return True
... 
>>> m1 = MyClass()
>>> m2 = MyClass()
>>> m1 == m2
True
>>> m1 == m1
True
>>> m1 == 1
True
>>> m1 == None
True
>>> m1 == []
True

I think you should do two things:

  1. Take a look at this guide to magic method use in Python.
  2. Justify why you are not subclassing list if what you want is very list-like. If subclassing is not appropriate, you can delegate to a wrapped list instance instead:

    class MyClass(object):
        def __init__(self):
            self._list = []
        def __getattr__(self, name):
            return getattr(self._list, name)
    
        # __repr__ and __str__ methods are automatically created
        # for every class, so if we want to delegate these we must
        # do so explicitly
        def __repr__(self):
            return "MyClass(%s)" % repr(self._list)
        def __str__(self):
            return "MyClass(%s)" % str(self._list)
    

    This will now act like a list without being a list (i.e., without subclassing list).

    >>> c = MyClass()
    >>> c.append(1)
    >>> c
    MyClass([1])
    

failed to lazily initialize a collection of role

Try swich fetchType from LAZY to EAGER

...
@OneToMany(fetch=FetchType.EAGER)
private Set<NodeValue> nodeValues;
...

But in this case your app will fetch data from DB anyway. If this query very hard - this may impact on performance. More here: https://docs.oracle.com/javaee/6/api/javax/persistence/FetchType.html

==> 73

Convert laravel object to array

$foo = Bar::getBeers(); $foo = $foo->toArray();

Can we add div inside table above every <tr>?

You can't put a div directly inside a table but you can put div inside td or th element.

For that you need to do is make sure the div is inside an actual table cell, a td or th element, so do that:

HTML:-

<tr>
  <td>
    <div>
      <p>I'm text in a div.</p>
    </div>
  </td>
</tr>

For more information :-

http://css-tricks.com/using-divs-inside-tables/

How to exclude a directory from ant fileset, based on directories contents

There is actually an example for this type of issue in the Ant documentation. It makes use of Selectors (mentioned above) and mappers. See last example in http://ant.apache.org/manual/Types/dirset.html :

<dirset id="dirset" dir="${workingdir}">
   <present targetdir="${workingdir}">
        <mapper type="glob" from="*" to="*/${markerfile}" />
   </present>
</dirset>

Selects all directories somewhere under ${workingdir} which contain a ${markerfile}.

How can I simulate an anchor click via jquery?

Try to avoid inlining your jQuery calls like that. Put a script tag at the top of the page to bind to the click event:

<script type="text/javascript">
$(function(){
    $('#thickboxButton').click(function(){
        $('#thickboxId').click();
    });
});
</script>

<input id="thickboxButton" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>

Edit:

If you're trying to simulate a user physically clicking the link, then I don't believe that is possible. A workaround would be to update the button's click event to change the window.location in Javascript:

<script type="text/javascript">
$(function(){
    $('#thickboxButton').click(function(){
        window.location = $('#thickboxId').attr('href');
    });
});
</script>

Edit 2:

Now that I realize that Thickbox is a custom jQuery UI widget, I found the instructions here:

Instructions:

  • Create a link element (<a href>)

  • Give the link a class attribute with a value of thickbox (class="thickbox")

  • In the href attribute of the link add the following anchor: #TB_inline

  • In the href attribute after the #TB_inline add the following query string on to the anchor:

    ?height=300&width=300&inlineId=myOnPageContent

  • Change the values of height, width, and inlineId in the query accordingly (inlineID is the ID value of the element that contains the content you would like to show in a ThickBox.

  • Optionally you may add modal=true to the query string (e.g. #TB_inline?height=155&width=300&inlineId=hiddenModalContent&modal=true) so that closing a ThickBox will require calling the tb_remove() function from within the ThickBox. See the hidden modal content example, where you must click yes or no to close the ThickBox.

Frequency table for a single variable

Maybe .value_counts()?

>>> import pandas
>>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])
>>> my_series
0       1
1       2
2       2
3       3
4       3
5       3
6    fred
7     1.8
8     1.8
>>> counts = my_series.value_counts()
>>> counts
3       3
2       2
1.8     2
fred    1
1       1
>>> len(counts)
5
>>> sum(counts)
9
>>> counts["fred"]
1
>>> dict(counts)
{1.8: 2, 2: 2, 3: 3, 1: 1, 'fred': 1}

Clearing NSUserDefaults

You can remove the application's persistent domain like this:

NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];

In Swift 3 and later:

if let bundleID = Bundle.main.bundleIdentifier {
    UserDefaults.standard.removePersistentDomain(forName: bundleID)
}

This is similar to the answer by @samvermette but is a little bit cleaner IMO.

How can I dynamically switch web service addresses in .NET without a recompile?

When you generate a web reference and click on the web reference in the Solution Explorer. In the properties pane you should see something like this:

Web Reference Properties

Changing the value to dynamic will put an entry in your app.config.

Here is the CodePlex article that has more information.

Google Maps: how to get country, state/province/region, city given a lat/long value?

@Szkíta Had a great solution by creating a function that gets the address parts in a named array. Here is a compiled solution for those who want to use plain JavaScript.

Function to convert results to the named array:

function getAddressParts(obj) {

    var address = [];

    obj.address_components.forEach( function(el) {
        address[el.types[0]] = el.short_name;
    });

    return address;

} //getAddressParts()

Geocode the LAT/LNG values:

geocoder.geocode( { 'location' : latlng }, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {
        var addressParts =  getAddressParts(results[0]);

        // the city
        var city = addressParts.locality;

        // the state
        var state = addressParts.administrative_area_level_1;
    }

});

get the selected index value of <select> tag in php

As you said..

$Gender  = isset($_POST["gender"]); ' it returns a empty string 

because, you haven't mention method type either use POST or GET, by default it will use GET method. On the other side, you are trying to retrieve your value by using POST method, but in the form you haven't mentioned POST method. Which means miss-match method will result for empty.

Try this code..

<form name="signup_form"  action="./signup.php" onsubmit="return validateForm()"   method="post">
<table> 
  <tr> <td> First Name    </td><td> <input type="text" name="fname" size=10/></td></tr>
  <tr> <td> Last Name     </td><td> <input type="text" name="lname" size=10/></td></tr>
  <tr> <td> Your Email    </td><td> <input type="text" name="email" size=10/></td></tr>
  <tr> <td> Re-type Email </td><td> <input type="text" name="remail"size=10/></td></tr>
  <tr> <td> Password      </td><td> <input type="password" name="paswod" size=10/> </td></tr>
  <tr> <td> Gender        </td><td> <select name="gender">
  <option value="select">                Select </option>    
  <option value="male">   Male   </option>
  <option value="female"> Female </option></select></td></tr> 
  <tr> <td> <input type="submit" value="Sign up" id="signup"/> </td> </tr>
 </table>
 </form>

and on signup page

$Gender  = $_POST["gender"];

i'm sure.. now, you will get the value..

Unable to create migrations after upgrading to ASP.NET Core 2.0

I got the same issue since I was referring old- Microsoft.EntityFrameworkCore.Tools.DotNet

<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />

After upgrading to the newer version it got resolved

Push Notifications in Android Platform

C2DM: your app-users must have the gmail account.

MQTT: when your connection reached to 1024, it will stop work because of it used "select model " of linux.

There is a free push service and api for android, you can try it: http://push-notification.org

Python Library Path

import sys
sys.path

How to use count and group by at the same select statement

I know this is an old post, in SQL Server:

select  isnull(town,'TOTAL') Town, count(*) cnt
from    user
group by town WITH ROLLUP

Town         cnt
Copenhagen   58
NewYork      58
Athens       58
TOTAL        174

How to add System.Windows.Interactivity to project?

Alternative solution is to modify your current Visual Studio installation in the Visual Studio Installer

Win+R %ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vs_installer.exe

adding the Blend for Visual Studio SDK for .NET 'Individual component' under 'SDKs, libraries, and frameworks':

enter image description here after adding this component System.Windows.Interactivity should appear in its regular location Add Reference/Assemblies/Extensions.


It appears this would only work for VS2017 or earlier. For later versions, please refer to other answers.

Detect if Visual C++ Redistributable for Visual Studio 2012 is installed

you can search in registry.Actually I do'nt have vs2012 but I have vs2010.

There are 3 different (but very similar) registry keys for each of the 3 platform packages. Each key has a DWORD value called “Installed” with a value of 1.

  • HKLM\SOFTWARE\Microsoft\VisualStudio\10.0\VC\VCRedist\x86

  • HKLM\SOFTWARE\Microsoft\VisualStudio\10.0\VC\VCRedist\x64

  • HKLM\SOFTWARE\Microsoft\VisualStudio\10.0\VC\VCRedist\ia64

You can use registry function for that......

Convert unix time stamp to date in java

Java 8 introduces the Instant.ofEpochSecond utility method for creating an Instant from a Unix timestamp, this can then be converted into a ZonedDateTime and finally formatted, e.g.:

final DateTimeFormatter formatter = 
    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

final long unixTime = 1372339860;
final String formattedDtm = Instant.ofEpochSecond(unixTime)
        .atZone(ZoneId.of("GMT-4"))
        .format(formatter);

System.out.println(formattedDtm);   // => '2013-06-27 09:31:00'

I thought this might be useful for people who are using Java 8.

How can I make Java print quotes, like "Hello"?

Escape double-quotes in your string: "\"Hello\""

More on the topic (check 'Escape Sequences' part)

error_reporting(E_ALL) does not produce error

In your php.ini file check for display_errors. I think it is off.

<?php
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

How to set the context path of a web application in Tomcat 7.0

In Tomcat 9.0, I only have to change the following in the server.xml

<Context docBase="web" path="/web" reloadable="true" source="org.eclipse.jst.jee.server:web"/>

to

<Context docBase="web" path="" reloadable="true" source="org.eclipse.jst.jee.server:web"/>

Detect encoding and make everything UTF-8

Ÿ is Mojibake for ß. In your database, you may have hex

DF if the column is "latin1",
C39F if the column is utf8 -- OR -- it is latin1, but "double-encoded"
C383C5B8 if double-encoded into a utf8 column

You should not use any encoding/decoding functions in PHP; instead, you should set up the database and the connection to it correctly.

If MySQL is involved, see: Trouble with utf8 characters; what I see is not what I stored

This could be due to the service endpoint binding not using the HTTP protocol

I think there is serialization problem, you can find exact error just need to add below code in service config in <configuration> section.

After config update "App_tracelog.svclog" file will create, where your service exist just need to open .svclog file and find red color line on left side panel which is error and see its description for more info.

I hope this will help to find your error.

<configuration>
...
...

<system.diagnostics>
    <sources>
      <source name="System.ServiceModel.MessageLogging" switchValue="Warning, ActivityTracing">
        <listeners>
          <add name="ServiceModelTraceListener" />
        </listeners>
      </source>
      <source name="System.ServiceModel" switchValue="Verbose,ActivityTracing">
        <listeners>
          <add name="ServiceModelTraceListener" />
        </listeners>
      </source>
      <source name="System.Runtime.Serialization" switchValue="Verbose,ActivityTracing">
        <listeners>
          <add name="ServiceModelTraceListener" />
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add initializeData="App_tracelog.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="ServiceModelTraceListener" traceOutputOptions="Timestamp" />
    </sharedListeners>
  </system.diagnostics>

  </configuration>

Update: If you will not able to find updated "App_tracelog.svclog" file then please find "<some GUID>App_tracelog.svclog" like "a39e3026-5dd8-4d39-842a-04d486615eedApp_tracelog.svclog"

Practical uses for AtomicInteger

You can implement non-blocking locks using compareAndSwap (CAS) on atomic integers or longs. The "Tl2" Software Transactional Memory paper describes this:

We associate a special versioned write-lock with every transacted memory location. In its simplest form, the versioned write-lock is a single word spinlock that uses a CAS operation to acquire the lock and a store to release it. Since one only needs a single bit to indicate that the lock is taken, we use the rest of the lock word to hold a version number.

What it is describing is first read the atomic integer. Split this up into an ignored lock-bit and the version number. Attempt to CAS write it as the lock-bit cleared with the current version number to the lock-bit set and the next version number. Loop until you succeed and your are the thread which owns the lock. Unlock by setting the current version number with the lock-bit cleared. The paper describes using the version numbers in the locks to coordinate that threads have a consistent set of reads when they write.

This article describes that processors have hardware support for compare and swap operations making the very efficient. It also claims:

non-blocking CAS-based counters using atomic variables have better performance than lock-based counters in low to moderate contention

How to make jQuery UI nav menu horizontal?

Just think about the jquery-ui menu as being the verticle dropdown when you hover over a topic on your main horizonal menu. That way, you have a separate jquery ui menu for each topic on your main menu. The horizonal main menu is just a collection of float:left divs wrapped in a mainmenu div. You then use the hover in and hover out to pop up each menu.

$('.mainmenuitem').hover(
    function(){ 
        $(this).addClass('ui-state-focus');
        $(this).addClass('ui-corner-all');
        $(this).addClass('ui-state-hover');
        $(this).addClass('ui-state-active');
        $(this).addClass('mainmenuhighlighted');
        // trigger submenu
        var position=$(this).offset();
        posleft=position.left;
        postop=position.top;
        submenu=$(this).attr('submenu');
        showSubmenu(posleft,postop,submenu);    
    },
    function(){ 
        $(this).removeClass('ui-state-focus');
        $(this).removeClass('ui-corner-all');
        $(this).removeClass('ui-state-hover');
        $(this).removeClass('ui-state-active');
        $(this).removeClass('mainmenuhighlighted');
        // remove submenu
        $('.submenu').hide();
    }
    );

The showSubmenu function is simple - it just positions the submenu and shows it.

function showSubmenu(left,top,submenu){
    var tPosX=left;
    var tPosY=top+28;
    $('#'+submenu).css({left:tPosX, top:tPosY,position:'absolute'});
    $('#'+submenu).show();
}

You then need to make sure the submenu is visible while your cursor is on it and disappears when you leave (this should be in your document.ready function.

$('.submenu').hover(
            function(){ 
                $(this).show();
            },
            function(){ 
                $(this).hide();
            }
            );

Also don't forget to hide your submenus to start with - in the document.ready function

$(".submenu" ).hide();

See the full code here

http://jsfiddle.net/R4nyn/

How can I create a copy of an Oracle table without copying the data?

Simply write a query like:

create table new_table as select * from old_table where 1=2;

where new_table is the name of the new table that you want to create and old_table is the name of the existing table whose structure you want to copy, this will copy only structure.

CSS root directory

/Images/myImage.png

this has to be in root of your domain/subdomain

http://website.to/Images/myImage.png

and it will work

However, I think it would work like this, too

  • images
    • yourimage.png
  • styles
    • style.css

style.css:

body{
    background: url(../images/yourimage.png);
}

What is the difference between T(n) and O(n)?

A chart could make the previous answers easier to understand:

T-Notation - Same order | O-Notation - Upper bound

T(n) - Same order O(n) - Upper bound

In English,

On the left, note that there is an upper bound and a lower bound that are both of the same order of magnitude (i.e. g(n) ). Ignore the constants, and if the upper bound and lower bound have the same order of magnitude, one can validly say f(n) = T(g(n)) or f(n) is in big theta of g(n).

Starting with the right, the simpler example, it is saying the upper bound g(n) is simply the order of magnitude and ignores the constant c (just as all big O notation does).

Java: int[] array vs int array[]

From JLS http://docs.oracle.com/javase/specs/jls/se5.0/html/arrays.html#10.2

Here are examples of declarations of array variables that do not create arrays:

int[ ] ai;          // array of int
short[ ][ ] as;         // array of array of short
Object[ ]   ao,     // array of Object
        otherAo;    // array of Object
Collection<?>[ ] ca;        // array of Collection of unknown type
short       s,      // scalar short 
        aas[ ][ ];  // array of array of short

Here are some examples of declarations of array variables that create array objects:

Exception ae[ ] = new Exception[3]; 
Object aao[ ][ ] = new Exception[2][3];
int[ ] factorial = { 1, 1, 2, 6, 24, 120, 720, 5040 };
char ac[ ] = { 'n', 'o', 't', ' ', 'a', ' ',
                 'S', 't', 'r', 'i', 'n', 'g' }; 
String[ ] aas = { "array", "of", "String", };

The [ ] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example:

byte[ ] rowvector, colvector, matrix[ ];

This declaration is equivalent to:

byte rowvector[ ], colvector[ ], matrix[ ][ ];

Confirmation before closing of tab/browser

Simply

function goodbye(e) {
        if(!e) e = window.event;
        //e.cancelBubble is supported by IE - this will kill the bubbling process.
        e.cancelBubble = true;
        e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog

        //e.stopPropagation works in Firefox.
        if (e.stopPropagation) {
            e.stopPropagation();
            e.preventDefault();
        }
    }
window.onbeforeunload=goodbye;

VB.NET: Clear DataGridView

The mistake that you are making is that you seem to be using a dataset object for storing your data. Each time you use the following code to put data into your dataset you add data to the data already in your dataset.

myDataAdapter.Fill(myDataSet)

If you assign the table in your dataset to a DataGridView object in your program by the following code you will get duplicate results because you have not cleared data which is already residing in your dataset and in your dataset table.

myDataGridView.DataSource = myDataSet.Tables(0)

To avoid replicating the data you have to call clear method on your dataset object.

myDataSet.clear()

An then assign the table in your dataset to your DataGridView object. The code is like this.

myDataSet.clear()
myDataAdapter.Fill(myDataSet)
myDataGridView.DataSource = myDataSet.Tables(0)

You can try this code:

' clear previous data
DataGridView2.DataSource = Nothing
DataGridView2.DataMember = Nothing
DataGridView2.Refresh()
Try
    connection.Open()
    adapter1 = New SqlDataAdapter(sql, connection)
    ' clear data already in the dataset
    ds1.Clear()
    adapter1.Fill(ds1)
    DataGridView2.DataSource = ds1.Tables(0)
    connection.Close()
Catch ex As Exception
    MsgBox(ex.ToString)
End Try

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

Added MSSQLSERVER full access to the folder, diskadmin and bulkadmin server roles.

In my c# application, when preparing for the bulk insert command,

string strsql = "BULK INSERT PWCR_Contractor_vw_TEST FROM '" + strFileName + "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\\n')";

And I get this error - Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 8 (STATUS).

I looked at my logfile and found that the terminator becomes ' ' instead of '\n'. The OLE DB provider "BULK" for linked server "(null)" reported an error. The provider did not give any information about the error:

Cannot fetch a row from OLE DB provider "BULK" for linked server "(null)". Query :BULK INSERT PWCR_Contractor_vw_TEST FROM 'G:\NEWSTAGEWWW\CalAtlasToPWCR\Results\parsedRegistration.csv' WITH (FIELDTERMINATOR = ',', **ROWTERMINATOR = ''**)

So I added extra escape to the rowterminator - string strsql = "BULK INSERT PWCR_Contractor_vw_TEST FROM '" + strFileName + "' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\\n')";

And now it inserts successfully.

Bulk Insert SQL -   --->  BULK INSERT PWCR_Contractor_vw_TEST FROM 'G:\\NEWSTAGEWWW\\CalAtlasToPWCR\\Results\\parsedRegistration.csv' WITH (FIELDTERMINATOR = ',', ROWTERMINATOR = '\n')
Bulk Insert to PWCR_Contractor_vw_TEST successful...  --->  clsDatase.PerformBulkInsert

How to read user input into a variable in Bash?

Try this

#/bin/bash

read -p "Enter a word: " word
echo "You entered $word"

Memory errors and list limits?

There is no memory limit imposed by Python. However, you will get a MemoryError if you run out of RAM. You say you have 20301 elements in the list. This seems too small to cause a memory error for simple data types (e.g. int), but if each element itself is an object that takes up a lot of memory, you may well be running out of memory.

The IndexError however is probably caused because your ListTemp has got only 19767 elements (indexed 0 to 19766), and you are trying to access past the last element.

It is hard to say what you can do to avoid hitting the limit without knowing exactly what it is that you are trying to do. Using numpy might help. It looks like you are storing a huge amount of data. It may be that you don't need to store all of it at every stage. But it is impossible to say without knowing.

Double precision - decimal places

Decimal representation of floating point numbers is kind of strange. If you have a number with 15 decimal places and convert that to a double, then print it out with exactly 15 decimal places, you should get the same number. On the other hand, if you print out an arbitrary double with 15 decimal places and the convert it back to a double, you won't necessarily get the same value back—you need 17 decimal places for that. And neither 15 nor 17 decimal places are enough to accurately display the exact decimal equivalent of an arbitrary double. In general, you need over 100 decimal places to do that precisely.

See the Wikipedia page for double-precision and this article on floating-point precision.

How to set a maximum execution time for a mysql query?

pt_kill has an option for such. But it is on-demand, not continually monitoring. It does what @Rafa suggested. However see --sentinel for a hint of how to come close with cron.

Pass a String from one Activity to another Activity in Android

In ActivityOne,

Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
intent.putExtra("data", somedata);
startActivity(intent);

In ActivityTwo,

Intent intent = getIntent();
String data = intent.getStringExtra("data");

How can I align the columns of tables in Bash?

function printTable()
{
    local -r delimiter="${1}"
    local -r data="$(removeEmptyLines "${2}")"

    if [[ "${delimiter}" != '' && "$(isEmptyString "${data}")" = 'false' ]]
    then
        local -r numberOfLines="$(wc -l <<< "${data}")"

        if [[ "${numberOfLines}" -gt '0' ]]
        then
            local table=''
            local i=1

            for ((i = 1; i <= "${numberOfLines}"; i = i + 1))
            do
                local line=''
                line="$(sed "${i}q;d" <<< "${data}")"

                local numberOfColumns='0'
                numberOfColumns="$(awk -F "${delimiter}" '{print NF}' <<< "${line}")"

                # Add Line Delimiter

                if [[ "${i}" -eq '1' ]]
                then
                    table="${table}$(printf '%s#+' "$(repeatString '#+' "${numberOfColumns}")")"
                fi

                # Add Header Or Body

                table="${table}\n"

                local j=1

                for ((j = 1; j <= "${numberOfColumns}"; j = j + 1))
                do
                    table="${table}$(printf '#| %s' "$(cut -d "${delimiter}" -f "${j}" <<< "${line}")")"
                done

                table="${table}#|\n"

                # Add Line Delimiter

                if [[ "${i}" -eq '1' ]] || [[ "${numberOfLines}" -gt '1' && "${i}" -eq "${numberOfLines}" ]]
                then
                    table="${table}$(printf '%s#+' "$(repeatString '#+' "${numberOfColumns}")")"
                fi
            done

            if [[ "$(isEmptyString "${table}")" = 'false' ]]
            then
                echo -e "${table}" | column -s '#' -t | awk '/^\+/{gsub(" ", "-", $0)}1'
            fi
        fi
    fi
}

function removeEmptyLines()
{
    local -r content="${1}"

    echo -e "${content}" | sed '/^\s*$/d'
}

function repeatString()
{
    local -r string="${1}"
    local -r numberToRepeat="${2}"

    if [[ "${string}" != '' && "${numberToRepeat}" =~ ^[1-9][0-9]*$ ]]
    then
        local -r result="$(printf "%${numberToRepeat}s")"
        echo -e "${result// /${string}}"
    fi
}

function isEmptyString()
{
    local -r string="${1}"

    if [[ "$(trimString "${string}")" = '' ]]
    then
        echo 'true' && return 0
    fi

    echo 'false' && return 1
}

function trimString()
{
    local -r string="${1}"

    sed 's,^[[:blank:]]*,,' <<< "${string}" | sed 's,[[:blank:]]*$,,'
}

SAMPLE RUNS

$ cat data-1.txt
HEADER 1,HEADER 2,HEADER 3

$ printTable ',' "$(cat data-1.txt)"
+-----------+-----------+-----------+
| HEADER 1  | HEADER 2  | HEADER 3  |
+-----------+-----------+-----------+

$ cat data-2.txt
HEADER 1,HEADER 2,HEADER 3
data 1,data 2,data 3

$ printTable ',' "$(cat data-2.txt)"
+-----------+-----------+-----------+
| HEADER 1  | HEADER 2  | HEADER 3  |
+-----------+-----------+-----------+
| data 1    | data 2    | data 3    |
+-----------+-----------+-----------+

$ cat data-3.txt
HEADER 1,HEADER 2,HEADER 3
data 1,data 2,data 3
data 4,data 5,data 6

$ printTable ',' "$(cat data-3.txt)"
+-----------+-----------+-----------+
| HEADER 1  | HEADER 2  | HEADER 3  |
+-----------+-----------+-----------+
| data 1    | data 2    | data 3    |
| data 4    | data 5    | data 6    |
+-----------+-----------+-----------+

$ cat data-4.txt
HEADER
data

$ printTable ',' "$(cat data-4.txt)"
+---------+
| HEADER  |
+---------+
| data    |
+---------+

$ cat data-5.txt
HEADER

data 1

data 2

$ printTable ',' "$(cat data-5.txt)"
+---------+
| HEADER  |
+---------+
| data 1  |
| data 2  |
+---------+

REF LIB at: https://github.com/gdbtek/linux-cookbooks/blob/master/libraries/util.bash

How to get POSTed JSON in Flask?

First of all, the .json attribute is a property that delegates to the request.get_json() method, which documents why you see None here.

You need to set the request content type to application/json for the .json property and .get_json() method (with no arguments) to work as either will produce None otherwise. See the Flask Request documentation:

This will contain the parsed JSON data if the mimetype indicates JSON (application/json, see is_json()), otherwise it will be None.

You can tell request.get_json() to skip the content type requirement by passing it the force=True keyword argument.

Note that if an exception is raised at this point (possibly resulting in a 400 Bad Request response), your JSON data is invalid. It is in some way malformed; you may want to check it with a JSON validator.

Returning pointer from a function

To my knowledge the use of the keyword new, does relatively the same thing as malloc(sizeof identifier). The code below demonstrates how to use the keyword new.

    void main(void){
        int* test;
        test = tester();
        printf("%d",*test);
        system("pause");
    return;
}
    int* tester(void){
        int *retMe;
        retMe = new int;//<----Here retMe is getting malloc for integer type
        *retMe = 12;<---- Initializes retMe... Note * dereferences retMe 
    return retMe;
}

Label points in geom_point

Instead of using the ifelse as in the above example, one can also prefilter the data prior to labeling based on some threshold values, this saves a lot of work for the plotting device:

xlimit <- 36
ylimit <- 24
ggplot(myData)+geom_point(aes(myX,myY))+
    geom_label(data=myData[myData$myX > xlimit & myData$myY> ylimit,], aes(myX,myY,myLabel))

Open another application from your own (intent)

Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setComponent(new ComponentName("package_name","package_name.class_name"));
        intent.putExtra("grace", "Hi");
        startActivity(intent);

Stored procedure return into DataSet in C# .Net

Try this

    DataSet ds = new DataSet("TimeRanges");
    using(SqlConnection conn = new SqlConnection("ConnectionString"))
    {               
            SqlCommand sqlComm = new SqlCommand("Procedure1", conn);               
            sqlComm.Parameters.AddWithValue("@Start", StartTime);
            sqlComm.Parameters.AddWithValue("@Finish", FinishTime);
            sqlComm.Parameters.AddWithValue("@TimeRange", TimeRange);

            sqlComm.CommandType = CommandType.StoredProcedure;

            SqlDataAdapter da = new SqlDataAdapter();
            da.SelectCommand = sqlComm;

            da.Fill(ds);
     }

Eclipse and Windows newlines

There is a handy bash utility - dos2unix - which is a DOS/MAC to UNIX text file format converter, that if not already installed on your distro, should be able to be easily installed via a package manager. dos2unix man page

Android Lint contentDescription warning

If you want to suppress this warning in elegant way (because you are sure that accessibility is not needed for this particular ImageView), you can use special attribute:

android:importantForAccessibility="no"

Why can't I use switch statement on a String?

In Java 11+ it's possible with variables too. The only condition is it must be a constant.

For Example:

final String LEFT = "left";
final String RIGHT = "right";
final String UP = "up";
final String DOWN = "down";

String var = ...;

switch (var) {
    case LEFT:
    case RIGHT:
    case DOWN:
    default:
        return 0;
}

PS. I've not tried this with earlier jdks. So please update the answer if it's supported there too.

Is it possible to "decompile" a Windows .exe? Or at least view the Assembly?

You may get some information viewing it in assembly, but I think the easiest thing to do is fire up a virtual machine and see what it does. Make sure you have no open shares or anything like that that it can jump through though ;)

How to change the remote a branch is tracking?

After trying the above and searching, searching, etc. I realized none of my changes were on the server that were on my local branch and Visual Studio in Team Explorer did not indicate this branch tracked a remote branch. The remote branch was there, so it should have worked. I ended up deleting the remote branch on github and 're' Push my local branch that had my changes that were not being tracked for an unknown reason.

By deleting the remote branch and 're' Push my local branch that was not being tracked, the local branch was re-created on git hub. I tried to this at the command prompt (using Windows) I could not get my local branch to track the remote branch until I did this. Everything is back to normal.

Declare variable in SQLite and use it

Herman's solution worked for me, but the ... had me mixed up for a bit. I'm including the demo I worked up based on his answer. The additional features in my answer include foreign key support, auto incrementing keys, and use of the last_insert_rowid() function to get the last auto generated key in a transaction.

My need for this information came up when I hit a transaction that required three foreign keys but I could only get the last one with last_insert_rowid().

PRAGMA foreign_keys = ON;   -- sqlite foreign key support is off by default
PRAGMA temp_store = 2;      -- store temp table in memory, not on disk

CREATE TABLE Foo(
    Thing1 INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
);

CREATE TABLE Bar(
    Thing2 INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    FOREIGN KEY(Thing2) REFERENCES Foo(Thing1)
);

BEGIN TRANSACTION;

CREATE TEMP TABLE _Variables(Key TEXT, Value INTEGER);

INSERT INTO Foo(Thing1)
VALUES(2);

INSERT INTO _Variables(Key, Value)
VALUES('FooThing', last_insert_rowid());

INSERT INTO Bar(Thing2)
VALUES((SELECT Value FROM _Variables WHERE Key = 'FooThing'));

DROP TABLE _Variables;

END TRANSACTION;

$(this).val() not working to get text from span using jquery

I think you want .text():

var monthname = $(this).text();

How to add title to subplots in Matplotlib?

In case you have multiple images and you want to loop though them and show them 1 by 1 along with titles - this is what you can do. No need to explicitly define ax1, ax2, etc.

  1. The catch is you can define dynamic axes(ax) as in Line 1 of code and you can set its title inside a loop.
  2. The rows of 2D array is length (len) of axis(ax)
  3. Each row has 2 items i.e. It is list within a list (Point No.2)
  4. set_title can be used to set title, once the proper axes(ax) or subplot is selected.
import matplotlib.pyplot as plt    
fig, ax = plt.subplots(2, 2, figsize=(6, 8))  
for i in range(len(ax)): 
    for j in range(len(ax[i])):
        ## ax[i,j].imshow(test_images_gr[0].reshape(28,28))
        ax[i,j].set_title('Title-' + str(i) + str(j))

sql query to find the duplicate records

You can't do it as a simple single query, but this would do:

select title
from kmovies
where title in (
    select title
    from kmovies
    group by title
    order by cnt desc
    having count(title) > 1
)

Get all child elements

Here is a code to get the child elements (In java):

String childTag = childElement.getTagName();
if(childTag.equals("html")) 
{
    return "/html[1]"+current;
}
WebElement parentElement = childElement.findElement(By.xpath("..")); 
List<WebElement> childrenElements = parentElement.findElements(By.xpath("*"));
int count = 0;
for(int i=0;i<childrenElements.size(); i++) 
{
    WebElement childrenElement = childrenElements.get(i);
    String childrenElementTag = childrenElement.getTagName();
    if(childTag.equals(childrenElementTag)) 
    {
        count++;
    }
 }

Is it possible to use JavaScript to change the meta-tags of the page?

You can use more simpler and lighter solution:

document.head.querySelector('meta[name="description"]').content = _desc

Path.Combine absolute with relative path strings

Be careful with Backslashes, don't forget them (neither use twice:)

string relativePath = "..\\bling.txt";
string baseDirectory = "C:\\blah\\";
//OR:
//string relativePath = "\\..\\bling.txt";
//string baseDirectory = "C:\\blah";
//THEN
string absolutePath = Path.GetFullPath(baseDirectory + relativePath);

Python list directory, subdirectory, and files

Since every example here is just using walk (with join), i'd like to show a nice example and comparison with listdir:

import os, time

def listFiles1(root): # listdir
    allFiles = []; walk = [root]
    while walk:
        folder = walk.pop(0)+"/"; items = os.listdir(folder) # items = folders + files
        for i in items: i=folder+i; (walk if os.path.isdir(i) else allFiles).append(i)
    return allFiles

def listFiles2(root): # listdir/join (takes ~1.4x as long) (and uses '\\' instead)
    allFiles = []; walk = [root]
    while walk:
        folder = walk.pop(0); items = os.listdir(folder) # items = folders + files
        for i in items: i=os.path.join(folder,i); (walk if os.path.isdir(i) else allFiles).append(i)
    return allFiles

def listFiles3(root): # walk (takes ~1.5x as long)
    allFiles = []
    for folder, folders, files in os.walk(root):
        for file in files: allFiles+=[folder.replace("\\","/")+"/"+file] # folder+"\\"+file still ~1.5x
    return allFiles

def listFiles4(root): # walk/join (takes ~1.6x as long) (and uses '\\' instead)
    allFiles = []
    for folder, folders, files in os.walk(root):
        for file in files: allFiles+=[os.path.join(folder,file)]
    return allFiles


for i in range(100): files = listFiles1("src") # warm up

start = time.time()
for i in range(100): files = listFiles1("src") # listdir
print("Time taken: %.2fs"%(time.time()-start)) # 0.28s

start = time.time()
for i in range(100): files = listFiles2("src") # listdir and join
print("Time taken: %.2fs"%(time.time()-start)) # 0.38s

start = time.time()
for i in range(100): files = listFiles3("src") # walk
print("Time taken: %.2fs"%(time.time()-start)) # 0.42s

start = time.time()
for i in range(100): files = listFiles4("src") # walk and join
print("Time taken: %.2fs"%(time.time()-start)) # 0.47s

So as you can see for yourself, the listdir version is much more efficient. (and that join is slow)

Can Selenium WebDriver open browser windows silently in the background?

Here is a .NET solution that worked for me:

Download PhantomJS at http://phantomjs.org/download.html.

Copy the .exe file from the bin folder in the download folder and paste it to the bin debug/release folder of your Visual Studio project.

Add this using

using OpenQA.Selenium.PhantomJS;

In your code, open the driver like this:

PhantomJSDriver driver = new PhantomJSDriver();
using (driver)
{
   driver.Navigate().GoToUrl("http://testing-ground.scraping.pro/login");
   // Your code here
}

How to choose an AWS profile when using boto3 to connect to CloudFront

I think the docs aren't wonderful at exposing how to do this. It has been a supported feature for some time, however, and there are some details in this pull request.

So there are three different ways to do this:

Option A) Create a new session with the profile

    dev = boto3.session.Session(profile_name='dev')

Option B) Change the profile of the default session in code

    boto3.setup_default_session(profile_name='dev')

Option C) Change the profile of the default session with an environment variable

    $ AWS_PROFILE=dev ipython
    >>> import boto3
    >>> s3dev = boto3.resource('s3')

Base64 encoding and decoding in oracle

I've implemented this to send Cyrillic e-mails through my MS Exchange server.

function to_base64(t in varchar2) return varchar2 is
 begin
    return utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw(t)));
end to_base64;

Try it.

upd: after a minor adjustment I came up with this, so it works both ways now:

function from_base64(t in varchar2) return varchar2 is
begin
  return utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw(t)));
end from_base64;

You can check it:

SQL> set serveroutput on
SQL> 
SQL> declare
  2    function to_base64(t in varchar2) return varchar2 is
  3    begin
  4      return utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw(t)));
  5    end to_base64;
  6  
  7    function from_base64(t in varchar2) return varchar2 is
  8    begin
  9      return utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw    (t)));
 10    end from_base64;
 11  
 12  begin
 13    dbms_output.put_line(from_base64(to_base64('asdf')));
 14  end;
 15  /

asdf

PL/SQL procedure successfully completed

upd2: Ok, here's a sample conversion that works for CLOB I just came up with. Try to work it out for your blobs. :)

declare

  clobOriginal     clob;
  clobInBase64     clob;
  substring        varchar2(2000);
  n                pls_integer := 0;
  substring_length pls_integer := 2000;

  function to_base64(t in varchar2) return varchar2 is
  begin
    return utl_raw.cast_to_varchar2(utl_encode.base64_encode(utl_raw.cast_to_raw(t)));
  end to_base64;

  function from_base64(t in varchar2) return varchar2 is
  begin
    return utl_raw.cast_to_varchar2(utl_encode.base64_decode(utl_raw.cast_to_raw(t)));
  end from_base64;

begin

  select clobField into clobOriginal from clobTable where id = 1;

  while true loop

    /*we substract pieces of substring_length*/
    substring := dbms_lob.substr(clobOriginal,
                                 least(substring_length, substring_length * n + 1 - length(clobOriginal)),
                                 substring_length * n + 1);  
    /*if no substring is found  - then we've reached the end of blob*/

    if substring is null then
      exit;
    end if;  

    /*convert them to base64 encoding and stack it in new clob vadriable*/
    clobInBase64 := clobInBase64 || to_base64(substring);          
    n := n + 1;  

  end loop;

  n := 0;
  clobOriginal := null;

  /*then we do the very same thing backwards - decode base64*/
  while true loop 

    substring := dbms_lob.substr(clobInBase64,
                                 least(substring_length, substring_length * n + 1 - length(clobInBase64)),
                                 substring_length * n + 1);  
    if substring is null then
      exit;
    end if;  
    clobOriginal := clobOriginal || from_base64(substring);  
    n := n + 1;  
  end loop; 

      /*and insert the data in our sample table - to ensure it's the same*/
  insert into clobTable (id, anotherClobField) values (1, clobOriginal);

end;

How can I sharpen an image in OpenCV?

Any Image is a collection of signals of various frequencies. The higher frequencies control the edges and the lower frequencies control the image content. Edges are formed when there is a sharp transition from one pixel value to the other pixel value like 0 and 255 in adjacent cell. Obviously there is a sharp change and hence the edge and high frequency. For sharpening an image these transitions can be enhanced further.

One way is to convolve a self made filter kernel with the image.

    import cv2
    import numpy as np

    image = cv2.imread('images/input.jpg')
    kernel = np.array([[-1,-1,-1], 
                       [-1, 9,-1],
                       [-1,-1,-1]])
    sharpened = cv2.filter2D(image, -1, kernel) # applying the sharpening kernel to the input image & displaying it.
    cv2.imshow('Image Sharpening', sharpened)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

There is another method of subtracting a blurred version of image from bright version of it. This helps sharpening the image. But should be done with caution as we are just increasing the pixel values. Imagine a grayscale pixel value 190, which if multiplied by a weight of 2 makes if 380, but is trimmed of at 255 due to the maximum allowable pixel range. This is information loss and leads to washed out image.

    addWeighted(frame, 1.5, image, -0.5, 0, image);

WooCommerce: Finding the products in database

I would recommend using WordPress custom fields to store eligible postcodes for each product. add_post_meta() and update_post_meta are what you're looking for. It's not recommended to alter the default WordPress table structure. All postmetas are inserted in wp_postmeta table. You can find the corresponding products within wp_posts table.

" netsh wlan start hostednetwork " command not working no matter what I try

netsh wlan set hostednetwork mode=allow ssid=dhiraj key=7870049877

Simple way to query connected USB devices info in Python?

For a system with legacy usb coming back and libusb-1.0, this approach will work to retrieve the various actual strings. I show the vendor and product as examples. It can cause some I/O, because it actually reads the info from the device (at least the first time, anyway.) Some devices don't provide this information, so the presumption that they do will throw an exception in that case; that's ok, so we pass.

import usb.core
import usb.backend.libusb1

busses = usb.busses()
for bus in busses:
    devices = bus.devices
    for dev in devices:
        if dev != None:
            try:
                xdev = usb.core.find(idVendor=dev.idVendor, idProduct=dev.idProduct)
                if xdev._manufacturer is None:
                    xdev._manufacturer = usb.util.get_string(xdev, xdev.iManufacturer)
                if xdev._product is None:
                    xdev._product = usb.util.get_string(xdev, xdev.iProduct)
                stx = '%6d %6d: '+str(xdev._manufacturer).strip()+' = '+str(xdev._product).strip()
                print stx % (dev.idVendor,dev.idProduct)
            except:
                pass

C++ trying to swap values in a vector

I think what you are looking for is iter_swap which you can find also in <algorithm>.
all you need to do is just pass two iterators each pointing at one of the elements you want to exchange.
since you have the position of the two elements, you can do something like this:

// assuming your vector is called v
iter_swap(v.begin() + position, v.begin() + next_position);
// position, next_position are the indices of the elements you want to swap

How to center canvas in html5

To center the canvas element horizontally, you must specify it as a block level and leave its left and right margin properties to the browser:

canvas{
    margin-right: auto;
    margin-left: auto;
    display: block;
}

If you wanted to center it vertically, the canvas element needs to be absolutely positioned:

canvas{
    position: absolute;
    top: 50%;
    transform: translate(0, -50%);              
}

If you wanted to center it horizontally and vertically, do:

canvas{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);               
}

For more info visit: https://www.w3.org/Style/Examples/007/center.en.html

How do the post increment (i++) and pre increment (++i) operators work in Java?

In the above example

int a = 5,i;

i=++a + ++a + a++;        //Ans: i = 6 + 7 + 7 = 20 then a = 8 

i=a++ + ++a + ++a;        //Ans: i = 8 + 10 + 11 = 29 then a = 11

a=++a + ++a + a++;        //Ans: a = 12 + 13 + 13 = 38

System.out.println(a);    //Ans: a = 38

System.out.println(i);    //Ans: i = 29

Java - get index of key in HashMap?

Not sure if this is any "cleaner", but:

List keys = new ArrayList(map.keySet());
for (int i = 0; i < keys.size(); i++) {
    Object obj = keys.get(i);
    // do stuff here
}

Trying to read cell 1,1 in spreadsheet using Google Script API

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();  // Not necessary 

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet 
var range = sheet.getRange(1,1); 
var data = range.getValue();

}

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

How can I check the extension of a file?

one easy way could be:

import os

if os.path.splitext(file)[1] == ".mp3":
    # do something

os.path.splitext(file) will return a tuple with two values (the filename without extension + just the extension). The second index ([1]) will therefor give you just the extension. The cool thing is, that this way you can also access the filename pretty easily, if needed!

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

If the shell scripts start with #!/bin/bash, they will always run with bash from /bin. If they however start with #!/usr/bin/env bash, they will search for bash in $PATH and then start with the first one they can find.

Why would this be useful? Assume you want to run bash scripts, that require bash 4.x or newer, yet your system only has bash 3.x installed and currently your distribution doesn't offer a newer version or you are no administrator and cannot change what is installed on that system.

Of course, you can download bash source code and build your own bash from scratch, placing it to ~/bin for example. And you can also modify your $PATH variable in your .bash_profile file to include ~/bin as the first entry (PATH=$HOME/bin:$PATH as ~ will not expand in $PATH). If you now call bash, the shell will first look for it in $PATH in order, so it starts with ~/bin, where it will find your bash. Same thing happens if scripts search for bash using #!/usr/bin/env bash, so these scripts would now be working on your system using your custom bash build.

One downside is, that this can lead to unexpected behavior, e.g. same script on the same machine may run with different interpreters for different environments or users with different search paths, causing all kind of headaches.

The biggest downside with env is that some systems will only allow one argument, so you cannot do this #!/usr/bin/env <interpreter> <arg>, as the systems will see <interpreter> <arg> as one argument (they will treat it as if the expression was quoted) and thus env will search for an interpreter named <interpreter> <arg>. Note that this is not a problem of the env command itself, which always allowed multiple parameters to be passed through but with the shebang parser of the system that parses this line before even calling env. Meanwhile this has been fixed on most systems but if your script wants to be ultra portable, you cannot rely that this has been fixed on the system you will be running.

It can even have security implications, e.g. if sudo was not configured to clean environment or $PATH was excluded from clean up. Let me demonstrate this:

Usually /bin is a well protected place, only root is able to change anything there. Your home directory is not, though, any program you run is able to make changes to it. That means malicious code could place a fake bash into some hidden directory, modify your .bash_profile to include that directory in your $PATH, so all scripts using #!/usr/bin/env bash will end up running with that fake bash. If sudo keeps $PATH, you are in big trouble.

E.g. consider a tool creates a file ~/.evil/bash with the following content:

#!/bin/bash

if [ $EUID -eq 0 ]; then
  echo "All your base are belong to us..."
  # We are root - do whatever you want to do
fi

/bin/bash "$@"

Let's make a simple script sample.sh:

#!/usr/bin/env bash

echo "Hello World"

Proof of concept (on a system where sudo keeps $PATH):

$ ./sample.sh
Hello World

$ sudo ./sample.sh
Hello World

$ export PATH="$HOME/.evil:$PATH"

$ ./sample.sh
Hello World

$ sudo ./sample.sh
All your base are belong to us...
Hello World

Usually the classic shells should all be located in /bin and if you don't want to place them there for whatever reason, it's really not an issue to place a symlink in /bin that points to their real locations (or maybe /bin itself is a symlink), so I would always go with #!/bin/sh and #!/bin/bash. There's just too much that would break if these wouldn't work anymore. It's not that POSIX would require these position (POSIX does not standardize path names and thus it doesn't even standardize the shebang feature at all) but they are so common, that even if a system would not offer a /bin/sh, it would probably still understand #!/bin/sh and know what to do with it and may it only be for compatibility with existing code.

But for more modern, non standard, optional interpreters like Perl, PHP, Python, or Ruby, it's not really specified anywhere where they should be located. They may be in /usr/bin but they may as well be in /usr/local/bin or in a completely different hierarchy branch (/opt/..., /Applications/..., etc.). That's why these often use the #!/usr/bin/env xxx shebang syntax.

How to Sort a List<T> by a property in the object

Suppose you have the following code, in this code, we have a Passenger class with a couple of properties that we want to sort based on.

public class Passenger
{
    public string Name { get; }
    public string LastName { get; }
    public string PassportNo { get; }
    public string Nationality { get; }

    public Passenger(string name, string lastName, string passportNo, string nationality)
    {
        this.Name = name;
        this.LastName = lastName;
        this.PassportNo = passportNo;
        this.Nationality = nationality;
    }

    public static int CompareByName(Passenger passenger1, Passenger passenger2)
    {
        return String.Compare(passenger1.Name, passenger2.Name);
    }

    public static int CompareByLastName(Passenger passenger1, Passenger passenger2)
    {
        return String.Compare(passenger1.LastName, passenger2.LastName);
    }

    public static int CompareNationality(Passenger passenger1, Passenger passenger2)
    {
        return String.Compare(passenger1.Nationality, passenger2.Nationality);
    }
}

public class TestPassengerSort
{
    Passenger p1 = new Passenger("Johon", "Floid", "A123456789", "USA");
    Passenger p2 = new Passenger("Jo", "Sina", "A987463215", "UAE");
    Passenger p3 = new Passenger("Ped", "Zoola", "A987855215", "Italy");

    public void SortThem()
    {
        Passenger[] passengers = new Passenger[] { p1, p2, p3 };
        List<Passenger> passengerList = new List<Passenger> { p1, p2, p3 };

        Array.Sort(passengers, Passenger.CompareByName);
        Array.Sort(passengers, Passenger.CompareByLastName);
        Array.Sort(passengers, Passenger.CompareNationality);

        passengerList.Sort(Passenger.CompareByName);
        passengerList.Sort(Passenger.CompareByLastName);
        passengerList.Sort(Passenger.CompareNationality);

    }
}

So you can implement your sort structure by using Composition delegate.

Position an element relative to its container

You have to explicitly set the position of the parent container along with the position of the child container. The typical way to do that is something like this:

div.parent{
    position: relative;
    left: 0px;  /* stick it wherever it was positioned by default */
    top: 0px;
}

div.child{
    position: absolute;
    left: 10px;
    top: 10px;
}

SQL Server Jobs with SSIS packages - Failed to decrypt protected XML node "DTS:Password" with error 0x8009000B

Change both Project and Package Properties ProtectionLevel to "DontSaveSensitive"

Is there a "goto" statement in bash?

It indeed may be useful for some debug or demonstration needs.

I found that Bob Copeland solution http://bobcopeland.com/blog/2012/10/goto-in-bash/ elegant:

#!/bin/bash
# include this boilerplate
function jumpto
{
    label=$1
    cmd=$(sed -n "/$label:/{:a;n;p;ba};" $0 | grep -v ':$')
    eval "$cmd"
    exit
}

start=${1:-"start"}

jumpto $start

start:
# your script goes here...
x=100
jumpto foo

mid:
x=101
echo "This is not printed!"

foo:
x=${x:-10}
echo x is $x

results in:

$ ./test.sh
x is 100
$ ./test.sh foo
x is 10
$ ./test.sh mid
This is not printed!
x is 101

Javascript logical "!==" operator?

!==

This is the strict not equal operator and only returns a value of true if both the operands are not equal and/or not of the same type. The following examples return a Boolean true:

a !== b
a !== "2"
4 !== '4' 

Entity Framework select distinct name

Try this:

var results = (from ta in context.TestAddresses
               select ta.Name).Distinct();

This will give you an IEnumerable<string> - you can call .ToList() on it to get a List<string>.

ReactJS: Warning: setState(...): Cannot update during an existing state transition

This same warning will be emitted on any state changes done in a render() call.

An example of a tricky to find case: When rendering a multi-select GUI component based on state data, if state has nothing to display, a call to resetOptions() is considered state change for that component.

The obvious fix is to do resetOptions() in componentDidUpdate() instead of render().

MS Access: how to compact current database in VBA

Try adding this module, pretty simple, just launches Access, opens the database, sets the "Compact on Close" option to "True", then quits.

Syntax to auto-compact:

acCompactRepair "C:\Folder\Database.accdb", True

To return to default*:

acCompactRepair "C:\Folder\Database.accdb", False

*not necessary, but if your back end database is >1GB this can be rather annoying when you go into it directly and it takes 2 minutes to quit!

EDIT: added option to recurse through all folders, I run this nightly to keep databases down to a minimum.

'accCompactRepair
'v2.02 2013-11-28 17:25

'===========================================================================
' HELP CONTACT
'===========================================================================
' Code is provided without warranty and can be stolen and amended as required.
'   Tom Parish
'   [email protected]
'   http://baldywrittencod.blogspot.com/2013/10/vba-modules-access-compact-repair.html
'   DGF Help Contact: see BPMHelpContact module
'=========================================================================

'includes code from
'http://www.ammara.com/access_image_faq/recursive_folder_search.html
'tweaked slightly for improved error handling

'   v2.02   bugfix preventing Compact when bAutoCompact set to False
'           bugfix with "OLE waiting for another application" msgbox
'           added "MB" to start & end sizes of message box at end
'   v2.01   added size reduction to message box
'   v2.00   added recurse
'   v1.00   original version

Option Explicit

Function accSweepForDatabases(ByVal strFolder As String, Optional ByVal bIncludeSubfolders As Boolean = True _
    , Optional bAutoCompact As Boolean = False) As String
'v2.02 2013-11-28 17:25
'sweeps path for .accdb and .mdb files, compacts and repairs all that it finds
'NB: leaves AutoCompact on Close as False unless specified, then leaves as True

'syntax:
'   accSweepForDatabases "path", [False], [True]

'code for ActiveX CommandButton on sheet module named "admin" with two named ranges "vPath" and "vRecurse":
'   accSweepForDatabases admin.Range("vPath"), admin.Range("vRecurse") [, admin.Range("vLeaveAutoCompact")]

Application.DisplayAlerts = False

Dim colFiles As New Collection, vFile As Variant, i As Integer, j As Integer, sFails As String, t As Single
Dim SizeBefore As Long, SizeAfter As Long
t = Timer
RecursiveDir colFiles, strFolder, "*.accdb", True  'comment this out if you only have Access 2003 installed
RecursiveDir colFiles, strFolder, "*.mdb", True

    For Each vFile In colFiles
        'Debug.Print vFile
        SizeBefore = SizeBefore + (FileLen(vFile) / 1048576)
On Error GoTo CompactFailed
    If InStr(vFile, "Geographical Configuration.accdb") > 0 Then MsgBox "yes"
        acCompactRepair vFile, bAutoCompact
        i = i + 1  'counts successes
        GoTo NextCompact
CompactFailed:
On Error GoTo 0
        j = j + 1   'counts failures
        sFails = sFails & vFile & vbLf  'records failure
NextCompact:
On Error GoTo 0
        SizeAfter = SizeAfter + (FileLen(vFile) / 1048576)

    Next vFile

Application.DisplayAlerts = True

'display message box, mark end of process
    accSweepForDatabases = i & " databases compacted successfully, taking " & CInt(Timer - t) & " seconds, and reducing storage overheads by " & Int(SizeBefore - SizeAfter) & "MB" & vbLf & vbLf & "Size Before: " & Int(SizeBefore) & "MB" & vbLf & "Size After: " & Int(SizeAfter) & "MB"
    If j > 0 Then accSweepForDatabases = accSweepForDatabases & vbLf & j & " failures:" & vbLf & vbLf & sFails
    MsgBox accSweepForDatabases, vbInformation, "accSweepForDatabases"

End Function

Function acCompactRepair(ByVal pthfn As String, Optional doEnable As Boolean = True) As Boolean
'v2.02 2013-11-28 16:22
'if doEnable = True will compact and repair pthfn
'if doEnable = False will then disable auto compact on pthfn

On Error GoTo CompactFailed

Dim A As Object
Set A = CreateObject("Access.Application")
With A
    .OpenCurrentDatabase pthfn
    .SetOption "Auto compact", True
    .CloseCurrentDatabase
    If doEnable = False Then
        .OpenCurrentDatabase pthfn
        .SetOption "Auto compact", doEnable
    End If
    .Quit
End With
Set A = Nothing
acCompactRepair = True
Exit Function
CompactFailed:
End Function


'source: http://www.ammara.com/access_image_faq/recursive_folder_search.html
'tweaked slightly for error handling

Private Function RecursiveDir(colFiles As Collection, _
                             strFolder As String, _
                             strFileSpec As String, _
                             bIncludeSubfolders As Boolean)

    Dim strTemp As String
    Dim colFolders As New Collection
    Dim vFolderName As Variant

    'Add files in strFolder matching strFileSpec to colFiles
    strFolder = TrailingSlash(strFolder)
On Error Resume Next
    strTemp = ""
    strTemp = Dir(strFolder & strFileSpec)
On Error GoTo 0
    Do While strTemp <> vbNullString
        colFiles.Add strFolder & strTemp
        strTemp = Dir
    Loop

    If bIncludeSubfolders Then
        'Fill colFolders with list of subdirectories of strFolder
On Error Resume Next
        strTemp = ""
        strTemp = Dir(strFolder, vbDirectory)
On Error GoTo 0
        Do While strTemp <> vbNullString
            If (strTemp <> ".") And (strTemp <> "..") Then
                If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0 Then
                    colFolders.Add strTemp
                End If
            End If
            strTemp = Dir
        Loop

        'Call RecursiveDir for each subfolder in colFolders
        For Each vFolderName In colFolders
            Call RecursiveDir(colFiles, strFolder & vFolderName, strFileSpec, True)
        Next vFolderName
    End If

End Function

Private Function TrailingSlash(strFolder As String) As String
    If Len(strFolder) > 0 Then
        If Right(strFolder, 1) = "\" Then
            TrailingSlash = strFolder
        Else
            TrailingSlash = strFolder & "\"
        End If
    End If
End Function

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

In my case I found that simply clearing the animation on the view before setting the visibility to GONE works.

dp2.clearAnimation();
dp2.setVisibility(View.GONE);

I had a similar issue where I toggle between two views, one of which must always start off as GONE - But when I displayed the views again, it was displaying over the first view even if setVisibility(GONE) was called. Clearing the animation before setting the view to GONE worked.

What causes javac to issue the "uses unchecked or unsafe operations" warning

This warning also could be raised due to

new HashMap() or new ArrayList() that is generic type has to be specific otherwise the compiler will generate warning.

Please make sure that if you code contains the following you have to change accordingly

new HashMap() => Map map = new HashMap() new HashMap() => Map map = new HashMap<>()

new ArrayList() => List map = new ArrayList() new ArrayList() => List map = new ArrayList<>()

How to get selected path and name of the file opened with file dialog?

After searching different websites looking for a solution as to how to separate the full path from the file name once the full one-piece information has been obtained from the Open File Dialog, and seeing how "complex" the solutions given were for an Excel newcomer like me, I wondered if there could be a simpler solution. So I started to work on it on my own and I came to this possibility. (I have no idea if somebody got the same idea before. Being so simple, if somebody has, I excuse myself.)

Dim fPath As String
Dim fName As String
Dim fdString As String

fdString = (the OpenFileDialog.FileName)

'Get just the path by finding the last "\" in the string from the end of it
 fPath = Left(fdString, InStrRev(fdString, "\"))

'Get just the file name by finding the last "\" in the string from the end of it
 fName = Mid(fdString, InStrRev(fdString, "\") + 1)

'Just to check the result
 Msgbox "File path: " & vbLF & fPath & vbLF & vblF & "File name: " & vbLF & fName

AND THAT'S IT!!! Just give it a try, and let me know how it goes...

Compare two date formats in javascript/jquery

Try it the other way:

var start_date  = $("#fit_start_time").val(); //05-09-2013
var end_date    = $("#fit_end_time").val(); //10-09-2013
var format='dd-MM-y';
    var result= compareDates(start_date,format,end_date,format);
    if(result==1)/// end date is less than start date
    {
            alert('End date should be greater than Start date');
    }



OR:
if(new Date(start_date) >= new Date(end_date))
{
    alert('End date should be greater than Start date');
}

PHP header redirect 301 - what are the implications?

The effect of the 301 would be that the search engines will index /option-a instead of /option-x. Which is probably a good thing since /option-x is not reachable for the search index and thus could have a positive effect on the index. Only if you use this wisely ;-)

After the redirect put exit(); to stop the rest of the script to execute

header("HTTP/1.1 301 Moved Permanently"); 
header("Location: /option-a"); 
exit();

Nginx location "not equal to" regex

i was looking for the same. and found this solution.

Use negative regex assertion:

location ~ ^/(?!(favicon\.ico|resources|robots\.txt)) { 
.... # your stuff 
} 

Source Negated Regular Expressions in location

Explanation of Regex :

If URL does not match any of the following path

example.com/favicon.ico
example.com/resources
example.com/robots.txt

Then it will go inside that location block and will process it.

Is there a way to set background-image as a base64 encoded image?

Try this, I have got success response ..it's working

$("#divId").css("background-image", "url('data:image/png;base64," + base64String + "')");

Convert stdClass object to array in PHP

Lets assume $post_id is array of $item

$post_id = array_map(function($item){

       return $item->{'post_id'};

       },$post_id);

strong text

Any way to replace characters on Swift String?

I am using this extension:

extension String {

    func replaceCharacters(characters: String, toSeparator: String) -> String {
        let characterSet = NSCharacterSet(charactersInString: characters)
        let components = self.componentsSeparatedByCharactersInSet(characterSet)
        let result = components.joinWithSeparator("")
        return result
    }

    func wipeCharacters(characters: String) -> String {
        return self.replaceCharacters(characters, toSeparator: "")
    }
}

Usage:

let token = "<34353 43434>"
token.replaceCharacters("< >", toString:"+")

Gson: Is there an easier way to serialize a map

In Gson 2.7.2 it's as easy as

Gson gson = new Gson();
String serialized = gson.toJson(map);

Using AES encryption in C#

If you just want to use the built-in crypto provider RijndaelManaged, check out the following help article (it also has a simple code sample):

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx

And just in case you need the sample in a hurry, here it is in all its plagiarized glory:

using System;
using System.IO;
using System.Security.Cryptography;

namespace RijndaelManaged_Example
{
    class RijndaelExample
    {
        public static void Main()
        {
            try
            {

                string original = "Here is some data to encrypt!";

                // Create a new instance of the RijndaelManaged 
                // class.  This generates a new key and initialization  
                // vector (IV). 
                using (RijndaelManaged myRijndael = new RijndaelManaged())
                {

                    myRijndael.GenerateKey();
                    myRijndael.GenerateIV();
                    // Encrypt the string to an array of bytes. 
                    byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);

                    // Decrypt the bytes to a string. 
                    string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);

                    //Display the original data and the decrypted data.
                    Console.WriteLine("Original:   {0}", original);
                    Console.WriteLine("Round Trip: {0}", roundtrip);
                }

            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
            }
        }
        static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
        {
            // Check arguments. 
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");
            byte[] encrypted;
            // Create an RijndaelManaged object 
            // with the specified key and IV. 
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;

                // Create a decryptor to perform the stream transform.
                ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for encryption. 
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {

                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }


            // Return the encrypted bytes from the memory stream. 
            return encrypted;

        }

        static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments. 
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");

            // Declare the string used to hold 
            // the decrypted text. 
            string plaintext = null;

            // Create an RijndaelManaged object 
            // with the specified key and IV. 
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for decryption. 
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {

                            // Read the decrypted bytes from the decrypting stream 
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }

            }

            return plaintext;

        }
    }
}

jQuery’s .bind() vs. .on()

From the jQuery documentation:

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

http://api.jquery.com/bind/

What is the default Jenkins password?

Similar to the Ubuntu answer above, the Windows admin default password is stored in {jenkins install dir}\secrets\initialAdminPassword file (default install location would it in C:\Program Files (x86)\Jenkins\secrets\initialAdminPassword )

Sort a list by multiple attributes?

I'm not sure if this is the most pythonic method ... I had a list of tuples that needed sorting 1st by descending integer values and 2nd alphabetically. This required reversing the integer sort but not the alphabetical sort. Here was my solution: (on the fly in an exam btw, I was not even aware you could 'nest' sorted functions)

a = [('Al', 2),('Bill', 1),('Carol', 2), ('Abel', 3), ('Zeke', 2), ('Chris', 1)]  
b = sorted(sorted(a, key = lambda x : x[0]), key = lambda x : x[1], reverse = True)  
print(b)  
[('Abel', 3), ('Al', 2), ('Carol', 2), ('Zeke', 2), ('Bill', 1), ('Chris', 1)]

Compare two List<T> objects for equality, ignoring order

Thinking this should do what you want:

list1.All(item => list2.Contains(item)) &&
list2.All(item => list1.Contains(item));

if you want it to be distinct, you could change it to:

list1.All(item => list2.Contains(item)) &&
list1.Distinct().Count() == list1.Count &&
list1.Count == list2.Count

jQuery: Get the cursor position of text in input without browser specific code?

Using the syntax text_element.selectionStart we can get the starting position of the selection of a text in terms of the index of the first character of the selected text in the text_element.value and in case we want to get the same of the last character in the selection we have to use text_element.selectionEnd.

Use it as follows:

<input type=text id=t1 value=abcd>
<button onclick="alert(document.getElementById('t1').selectionStart)">check position</button>

I'm giving you the fiddle_demo

How do I serialize a C# anonymous type to a JSON string?

Try the JavaScriptSerializer instead of the DataContractJsonSerializer

JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(your_anon_object);

How to add multiple files to Git at the same time

To add all the changes you've made:

git add .

To commit them:

git commit -m "MY MESSAGE HERE" #-m is the message flag

You can put those steps together like this:

git commit -a -m "MY MESSAGE HERE"

To push your committed changes from your local repository to your remote repository:

git push origin master

You might have to type in your username/password for github after this. Here's a good primer on using git. A bit old, but it covers what's going on really well.

How to get the next auto-increment id in mysql

Use LAST_INSERT_ID() from your SQL query.

Or

You can also use mysql_insert_id() to get it using PHP.

How to rearrange Pandas column sequence?

Feel free to disregard this solution as subtracting a list from an Index does not preserve the order of the original Index, if that's important.

In [61]: df.reindex(columns=pd.Index(['x', 'y']).append(df.columns - ['x', 'y']))
Out[61]: 
    x  y  a  b
0   3 -1  1  2
1   6 -2  2  4
2   9 -3  3  6
3  12 -4  4  8

How do I get a platform-dependent new line character?

StringBuilder newLine=new StringBuilder();
newLine.append("abc");
newline.append(System.getProperty("line.separator"));
newline.append("def");
String output=newline.toString();

The above snippet will have two strings separated by a new line irrespective of platforms.

Javascript Equivalent to C# LINQ Select

Had to merge this nice answers. It revealed something like that;

Extension;

 Array.prototype.where = function (filter) {

                                var collection = this;

                                switch (typeof filter) {

                                    case 'function':
                                        return $.grep(collection, filter);

                                    case 'object':
                                        for (var property in filter) {
                                            if (!filter.hasOwnProperty(property))
                                                continue; // ignore inherited properties

                                            collection = $.grep(collection, function (item) {
                                                return item[property] === filter[property];
                                            });
                                        }
                                        return collection.slice(0); // copy the array 
                                    // (in case of empty object filter)

                                    default:
                                        throw new TypeError('func must be either a' +
                                            'function or an object of properties and values to filter by');
                                }
                            };

Usage;



masterTableView.get_dataItems().where(function (t) {
if (t.findElement("_invoiceGridCheckbox").checked) {
    invoiceIds.push(t.getDataKeyValue("Id"));
  }
});

Warning about `$HTTP_RAW_POST_DATA` being deprecated

; always_populate_raw_post_data = -1 in php.init remove comment of this line .. always_populate_raw_post_data = -1

How can I give eclipse more memory than 512M?

Configuring this worked for me: -vmargs -Xms1536m -Xmx2048m -XX:MaxPermSize=1024m on Eclipse Java Photon June 2018

Running Windows 10, 8 GB ram and 64 bit. You can extend -Xmx2048 -XX:MaxpermSize= 1024m to 4096m too, if your computer has good ram.Mine worked well.

How to determine whether a year is a leap year?

Use calendar.isleap:

import calendar
print(calendar.isleap(1900))

window.open with headers

If you are in control of server side, it might be possible to set header value in query string and send it like that? That way you could parse it from query string if it's not found in the headers.

Just an idea... And you asked for a cunning hack :)

Get value from text area

use the val() method:

$(document).ready(function () {
    var j = $("textarea");
    if (j.val().length > 0) {
        alert(j.val());
    }
});

Onclick event to remove default value in a text input field

<input name="Name" value="Enter Your Name" onfocus="freez(this)" onblur="freez(this)">


function freez(obj)
{
 if(obj.value=='')
 {
   obj.value='Enter Your Name';
 }else if(obj.value=='Enter Your Name')
 {
   obj.value='';
 }
} 

String replace method is not replacing characters

Strings are immutable, meaning their contents cannot change. When you call replace(this,that) you end up with a totally new String. If you want to keep this new copy, you need to assign it to a variable. You can overwrite the old reference (a la sentence = sentence.replace(this,that) or a new reference as seen below:

public class Test{

    public static void main(String[] args) {

        String sentence = "Define, Measure, Analyze, Design and Verify";

        String replaced = sentence.replace("and", "");
        System.out.println(replaced);

    }
}

As an aside, note that I've removed the contains() check, as it is an unnecessary call here. If it didn't contain it, the replace will just fail to make any replacements. You'd only want that contains method if what you're replacing was different than the actual condition you're checking.

Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?

The link posted by Jose has been updated and pylab now has a tight_layout() function that does this automatically (in matplotlib version 1.1.0).

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout

http://matplotlib.org/users/tight_layout_guide.html#plotting-guide-tight-layout

Oracle "Partition By" Keyword

EMPNO     DEPTNO DEPT_COUNT

 7839         10          4
 5555         10          4
 7934         10          4
 7782         10          4 --- 4 records in table for dept 10
 7902         20          4
 7566         20          4
 7876         20          4
 7369         20          4 --- 4 records in table for dept 20
 7900         30          6
 7844         30          6
 7654         30          6
 7521         30          6
 7499         30          6
 7698         30          6 --- 6 records in table for dept 30

Here we are getting count for respective deptno. As for deptno 10 we have 4 records in table emp similar results for deptno 20 and 30 also.

RadioGroup: How to check programmatically

In your layout you can add android:checked="true" to CheckBox you want to be selected.

Or programmatically, you can use the setChecked method defined in the checkable interface:

RadioButton b = (RadioButton) findViewById(R.id.option1); b.setChecked(true);

Converting int to bytes in Python 3

Although the prior answer by brunsgaard is an efficient encoding, it works only for unsigned integers. This one builds upon it to work for both signed and unsigned integers.

def int_to_bytes(i: int, *, signed: bool = False) -> bytes:
    length = ((i + ((i * signed) < 0)).bit_length() + 7 + signed) // 8
    return i.to_bytes(length, byteorder='big', signed=signed)

def bytes_to_int(b: bytes, *, signed: bool = False) -> int:
    return int.from_bytes(b, byteorder='big', signed=signed)

# Test unsigned:
for i in range(1025):
    assert i == bytes_to_int(int_to_bytes(i))

# Test signed:
for i in range(-1024, 1025):
    assert i == bytes_to_int(int_to_bytes(i, signed=True), signed=True)

For the encoder, (i + ((i * signed) < 0)).bit_length() is used instead of just i.bit_length() because the latter leads to an inefficient encoding of -128, -32768, etc.


Credit: CervEd for fixing a minor inefficiency.

Detect click outside element

I am using this package : https://www.npmjs.com/package/vue-click-outside

It works fine for me

HTML :

<div class="__card-content" v-click-outside="hide" v-if="cardContentVisible">
    <div class="card-header">
        <input class="subject-input" placeholder="Subject" name=""/>
    </div>
    <div class="card-body">
        <textarea class="conversation-textarea" placeholder="Start a conversation"></textarea>
    </div>
</div>

My script codes :

import ClickOutside from 'vue-click-outside'
export default
{
    data(){
        return {
            cardContentVisible:false
        }
    },
    created()
    {
    },
    methods:
        {
            openCardContent()
            {
                this.cardContentVisible = true;
            }, hide () {
            this.cardContentVisible = false
                }
        },
    directives: {
            ClickOutside
    }
}

Set NOW() as Default Value for datetime datatype?

I use a trigger as a workaround to set a datetime field to NOW() for new inserts:

CREATE TRIGGER `triggername` BEFORE INSERT ON  `tablename` 
FOR EACH ROW 
SET NEW.datetimefield = NOW()

it should work for updates too

Answers by Johan & Leonardo involve converting to a timestamp field. Although this is probably ok for the use case presented in the question (storing RegisterDate and LastVisitDate), it is not a universal solution. See datetime vs timestamp question.

not:first-child selector

As I used ul:not(:first-child) is a perfect solution.

div ul:not(:first-child) {
    background-color: #900;
}

Why is this a perfect because by using ul:not(:first-child), we can apply CSS on inner elements. Like li, img, span, a tags etc.

But when used others solutions:

div ul + ul {
  background-color: #900;
}

and

div li~li {
    color: red;
}

and

ul:not(:first-of-type) {}

and

div ul:nth-child(n+2) {
    background-color: #900;
}

These restrict only ul level CSS. Suppose we cannot apply CSS on li as `div ul + ul li'.

For inner level elements the first Solution works perfectly.

div ul:not(:first-child) li{
        background-color: #900;
    }

and so on ...

Why does the C preprocessor interpret the word "linux" as the constant "1"?

In the Old Days (pre-ANSI), predefining symbols such as unix and vax was a way to allow code to detect at compile time what system it was being compiled for. There was no official language standard back then (beyond the reference material at the back of the first edition of K&R), and C code of any complexity was typically a complex maze of #ifdefs to allow for differences between systems. These macro definitions were generally set by the compiler itself, not defined in a library header file. Since there were no real rules about which identifiers could be used by the implementation and which were reserved for programmers, compiler writers felt free to use simple names like unix and assumed that programmers would simply avoid using those names for their own purposes.

The 1989 ANSI C standard introduced rules restricting what symbols an implementation could legally predefine. A macro predefined by the compiler could only have a name starting with two underscores, or with an underscore followed by an uppercase letter, leaving programmers free to use identifiers not matching that pattern and not used in the standard library.

As a result, any compiler that predefines unix or linux is non-conforming, since it will fail to compile perfectly legal code that uses something like int linux = 5;.

As it happens, gcc is non-conforming by default -- but it can be made to conform (reasonably well) with the right command-line options:

gcc -std=c90 -pedantic ... # or -std=c89 or -ansi
gcc -std=c99 -pedantic
gcc -std=c11 -pedantic

See the gcc manual for more details.

gcc will be phasing out these definitions in future releases, so you shouldn't write code that depends on them. If your program needs to know whether it's being compiled for a Linux target or not it can check whether __linux__ is defined (assuming you're using gcc or a compiler that's compatible with it). See the GNU C preprocessor manual for more information.

A largely irrelevant aside: the "Best One Liner" winner of the 1987 International Obfuscated C Code Contest, by David Korn (yes, the author of the Korn Shell) took advantage of the predefined unix macro:

main() { printf(&unix["\021%six\012\0"],(unix)["have"]+"fun"-0x60);}

It prints "unix", but for reasons that have absolutely nothing to do with the spelling of the macro name.

What's the best way to store a group of constants that my program uses?

Another vote for using web.config or app.config. The config files are a good place for constants like connection strings, etc. I prefer not to have to look at the source to view or modify these types of things. A static class which reads these constants from a .config file might be a good compromise, as it will let your application access these resources as though they were defined in code, but still give you the flexibility of having them in an easily viewable/editable space.

How to write new line character to a file in Java

bufferedWriter.write(text + "\n"); This method can work, but the new line character can be different between platforms, so alternatively, you can use this method:

bufferedWriter.write(text);
bufferedWriter.newline();

What is the syntax of the enhanced for loop in Java?

  1. Enhanced For Loop (Java)
for (Object obj : list);
  1. Enhanced For Each in arraylist (Java)
ArrayList<Integer> list = new ArrayList<Integer>(); 
list.forEach((n) -> System.out.println(n)); 

What is the difference between DAO and Repository patterns?

Frankly, this looks like a semantic distinction, not a technical distinction. The phrase Data Access Object doesn't refer to a "database" at all. And, although you could design it to be database-centric, I think most people would consider doing so a design flaw.

The purpose of the DAO is to hide the implementation details of the data access mechanism. How is the Repository pattern different? As far as I can tell, it isn't. Saying a Repository is different to a DAO because you're dealing with/return a collection of objects can't be right; DAOs can also return collections of objects.

Everything I've read about the repository pattern seems rely on this distinction: bad DAO design vs good DAO design (aka repository design pattern).