Programs & Examples On #Debug symbols

A debug symbol is information that expresses which programming-language constructs generated a specific piece of machine code in a given executable module.

Release generating .pdb files, why?

Because without the PDB files, it would be impossible to debug a "Release" build by anything other than address-level debugging. Optimizations really do a number on your code, making it very difficult to find the culprit if something goes wrong (say, an exception is thrown). Even setting breakpoints is extremely difficult, because lines of source code cannot be matched up one-to-one with (or even in the same order as) the generated assembly code. PDB files help you and the debugger out, making post-mortem debugging significantly easier.

You make the point that if your software is ready for release, you should have done all your debugging by then. While that's certainly true, there are a couple of important points to keep in mind:

  1. You should also test and debug your application (before you release it) using the "Release" build. That's because turning optimizations on (they are disabled by default under the "Debug" configuration) can sometimes cause subtle bugs to appear that you wouldn't otherwise catch. When you're doing this debugging, you'll want the PDB symbols.

  2. Customers frequently report edge cases and bugs that only crop up under "ideal" conditions. These are things that are almost impossible to reproduce in the lab because they rely on some whacky configuration of that user's machine. If they're particularly helpful customers, they'll report the exception that was thrown and provide you with a stack trace. Or they'll even let you borrow their machine to debug your software remotely. In either of those cases, you'll want the PDB files to assist you.

  3. Profiling should always be done on "Release" builds with optimizations enabled. And once again, the PDB files come in handy, because they allow the assembly instructions being profiled to be mapped back to the source code that you actually wrote.

You can't go back and generate the PDB files after the compile.* If you don't create them during the build, you've lost your opportunity. It doesn't hurt anything to create them. If you don't want to distribute them, you can simply omit them from your binaries. But if you later decide you want them, you're out of luck. Better to always generate them and archive a copy, just in case you ever need them.

If you really want to turn them off, that's always an option. In your project's Properties window, set the "Debug Info" option to "none" for any configuration you want to change.

Do note, however, that the "Debug" and "Release" configurations do by default use different settings for emitting debug information. You will want to keep this setting. The "Debug Info" option is set to "full" for a Debug build, which means that in addition to a PDB file, debugging symbol information is embedded into the assembly. You also get symbols that support cool features like edit-and-continue. In Release mode, the "pdb-only" option is selected, which, like it sounds, includes only the PDB file, without affecting the content of the assembly. So it's not quite as simple as the mere presence or absence of PDB files in your /bin directory. But assuming you use the "pdb-only" option, the PDB file's presence will in no way affect the run-time performance of your code.

* As Marc Sherman points out in a comment, as long as your source code has not changed (or you can retrieve the original code from a version-control system), you can rebuild it and generate a matching PDB file. At least, usually. This works well most of the time, but the compiler is not guaranteed to generate identical binaries each time you compile the same code, so there may be subtle differences. Worse, if you have made any upgrades to your toolchain in the meantime (like applying a service pack for Visual Studio), the PDBs are even less likely to match. To guarantee the reliable generation of ex postfacto PDB files, you would need to archive not only the source code in your version-control system, but also the binaries for your entire build toolchain to ensure that you could precisely recreate the configuration of your build environment. It goes without saying that it is much easier to simply create and archive the PDB files.

Visual Studio loading symbols

Just had this problem.

I fixed it by navigating to:

Tools -> Options -> Debugging -> Symbols

Then unchecking all non-local sources for Symbol file (.pdb) locations

e.g. Microsoft Symbol Servers and msdl.microsoft.com/download/symbols

#if DEBUG vs. Conditional("DEBUG")

Well, it's worth noting that they don't mean the same thing at all.

If the DEBUG symbol isn't defined, then in the first case the SetPrivateValue itself won't be called... whereas in the second case it will exist, but any callers who are compiled without the DEBUG symbol will have those calls omitted.

If the code and all its callers are in the same assembly this difference is less important - but it means that in the first case you also need to have #if DEBUG around the calling code as well.

Personally I'd recommend the second approach - but you do need to keep the difference between them clear in your head.

How can I rollback a git repository to a specific commit?

git reset --hard <old-commit-id>
git push -f <remote-name> <branch-name>

Note: As written in comments below, Using this is dangerous in a collaborative environment: you're rewriting history

trigger click event from angularjs directive

This is how I was able to trigger a button click when the page loads.

<li ng-repeat="a in array">
  <a class="button" id="btn" ng-click="function(a)" index="$index" on-load-clicker>
    {{a.name}}
  </a>
</li>

A simple directive that takes the index from the ng-repeat and uses a condition to call the first button in the index and click it when the page loads.

angular
    .module("myApp")
        .directive('onLoadClicker', function ($timeout) {
            return {
                restrict: 'A',
                scope: {
                    index: '=index'
                },
                link: function($scope, iElm) {
                    if ($scope.index == 0) {
                        $timeout(function() {

                            iElm.triggerHandler('click');

                        }, 0);
                    }
                }
            };
        });

This was the only way I was able to even trigger an auto click programmatically in the first place. angular.element(document.querySelector('#btn')).click(); Did not work from the controller so making this simple directive seems most effective if you are trying to run a click on page load and you can specify which button to click by passing in the index. I got help through this stack-overflow answer from another post reference: https://stackoverflow.com/a/26495541/4684183 onLoadClicker Directive.

Adding 1 hour to time variable

$time = '10:09';
$timestamp = strtotime($time);
$timestamp_one_hour_later = $timestamp + 3600; // 3600 sec. = 1 hour

// Formats the timestamp to HH:MM => outputs 11:09.
echo strftime('%H:%M', $timestamp_one_hour_later);
// As crolpa suggested, you can also do
// echo date('H:i', $timestamp_one_hour_later);

Check PHP manual for strtotime(), strftime() and date() for details.

BTW, in your initial code, you need to add some quotes otherwise you will get PHP syntax errors:

$time = 10:09; // wrong syntax
$time = '10:09'; // syntax OK

$time = date(H:i, strtotime('+1 hour')); // wrong syntax
$time = date('H:i', strtotime('+1 hour')); // syntax OK

load Js file in HTML

If this is your detail.html I don't see where do you load detail.js? Maybe this

<script src="js/index.js"></script>

should be this

<script src="js/detail.js"></script>

?

Counting the number of files in a directory using Java

Since you don't really need the total number, and in fact want to perform an action after a certain number (in your case 5000), you can use java.nio.file.Files.newDirectoryStream. The benefit is that you can exit early instead having to go through the entire directory just to get a count.

public boolean isOverMax(){
    Path dir = Paths.get("C:/foo/bar");
    int i = 1;

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path p : stream) {
            //larger than max files, exit
            if (++i > MAX_FILES) {
                return true;
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return false;
}

The interface doc for DirectoryStream also has some good examples.

How do you Sort a DataTable given column and direction?

In case you want to sort in more than one direction

  public static void sortOutputTable(ref DataTable output)
        {
            DataView dv = output.DefaultView;
            dv.Sort = "specialCode ASC, otherCode DESC";
            DataTable sortedDT = dv.ToTable();
            output = sortedDT;
        }

How to create PDFs in an Android app?

If you are developing for devices with API level 19 or higher you can use the built in PrintedPdfDocument: http://developer.android.com/reference/android/print/pdf/PrintedPdfDocument.html

// open a new document
PrintedPdfDocument document = new PrintedPdfDocument(context,
     printAttributes);

// start a page
Page page = document.startPage(0);

// draw something on the page
View content = getContentView();
content.draw(page.getCanvas());

// finish the page
document.finishPage(page);
. . .
// add more pages
. . .
// write the document content
document.writeTo(getOutputStream());

//close the document
document.close();

How to remove a key from Hash and get the remaining hash in Ruby/Rails?

Hash#except (Ruby 3.0+)

Starting from Ruby 3.0, Hash#except is a build-in method.

As a result, there is no more need to depend on ActiveSupport or write monkey-patches in order to use it.

h = { a: 1, b: 2, c: 3 }
p h.except(:a) #=> {:b=>2, :c=>3}

Sources:

Disable spell-checking on HTML textfields

An IFrame WILL "trigger" the spell checker (if it has content-editable set to true) just as a textfield, at least in Chrome.

jQuery: go to URL with target="_blank"

If you want to create the popup window through jQuery then you'll need to use a plugin. This one seems like it will do what you want:

http://rip747.github.com/popupwindow/

Alternately, you can always use JavaScript's window.open function.

Note that with either approach, the new window must be opened in response to user input/action (so for instance, a click on a link or button). Otherwise the browser's popup blocker will just block the popup.

how to check for special characters php

preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

Your use of it isn't a hack, though like many things in C++, mutable can be hack for a lazy programmer who doesn't want to go all the way back and mark something that shouldn't be const as non-const.

How to check if an object implements an interface?

For an instance

Character.Gorgon gor = new Character.Gorgon();

Then do

gor instanceof Monster

For a Class instance do

Class<?> clazz = Character.Gorgon.class;
Monster.class.isAssignableFrom(clazz);

Android get Current UTC time

System.currentTimeMillis() does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date instance to a string before using it. You can use DateFormats to convert Dates to Strings in any timezone:

DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());

Also see this related question.

MongoDB: Is it possible to make a case-insensitive query?

db.company_profile.find({ "companyName" : { "$regex" : "Nilesh" , "$options" : "i"}});

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

Checking for Undefined In React

In case you also need to check if nextProps.blog is not undefined ; you can do that in a single if statement, like this:

if (typeof nextProps.blog !== "undefined" && typeof nextProps.blog.content !== "undefined") {
    //
}

And, when an undefined , empty or null value is not expected; you can make it more concise:

if (nextProps.blog && nextProps.blog.content) {
    //
}

How to export/import PuTTy sessions list?

For those of you who need to import Putty from offline registry file e.g. when you are recovering from crashed system or simply moving to a new machine and grabbing data off that old drive there is one more solution worth mentioning:

http://www.nirsoft.net/utils/registry_file_offline_export.html

This great and free console application will export the entire registry or only a specific registry key. In my case i simply copied the registry file from an old drive to the same directory as the exporter tool and then i used following command and syntax in CMD window run as administrator:

RegFileExport.exe NTUSER.DAT putty.reg "HKEY_CURRENT_USER\Software\SimonTatham"

After importing the .reg file and starting Putty everything was there. Simple and efficient.

How can I dynamically add a directive in AngularJS?

function addAttr(scope, el, attrName, attrValue) {
  el.replaceWith($compile(el.clone().attr(attrName, attrValue))(scope));
}

AngularJS: Can't I set a variable value on ng-click?

While @tymeJV gave a correct answer, the way to do this to be inline with angular would be:

ng-click="hidePrefs()"

and then in your controller:

$scope.hidePrefs = function() {  
  $scope.prefs = false;
}

When creating a service with sc.exe how to pass in context parameters?

I use to just create it without parameters, and then edit the registry HKLM\System\CurrentControlSet\Services\[YourService].

How to remove rows with any zero value

I would probably go with Joran's suggestion of replacing 0's with NAs and then using the built in functions you mentioned. If you can't/don't want to do that, one approach is to use any() to find rows that contain 0's and subset those out:

set.seed(42)
#Fake data
x <- data.frame(a = sample(0:2, 5, TRUE), b = sample(0:2, 5, TRUE))
> x
  a b
1 2 1
2 2 2
3 0 0
4 2 1
5 1 2
#Subset out any rows with a 0 in them
#Note the negation with ! around the apply function
x[!(apply(x, 1, function(y) any(y == 0))),]
  a b
1 2 1
2 2 2
4 2 1
5 1 2

To implement Joran's method, something like this should get you started:

x[x==0] <- NA

How do I position an image at the bottom of div?

< img style="vertical-align: bottom" src="blah.png" >

Works for me. Inside a parallax div as well.

What do 1.#INF00, -1.#IND00 and -1.#IND mean?

From IEEE floating-point exceptions in C++ :

This page will answer the following questions.

  • My program just printed out 1.#IND or 1.#INF (on Windows) or nan or inf (on Linux). What happened?
  • How can I tell if a number is really a number and not a NaN or an infinity?
  • How can I find out more details at runtime about kinds of NaNs and infinities?
  • Do you have any sample code to show how this works?
  • Where can I learn more?

These questions have to do with floating point exceptions. If you get some strange non-numeric output where you're expecting a number, you've either exceeded the finite limits of floating point arithmetic or you've asked for some result that is undefined. To keep things simple, I'll stick to working with the double floating point type. Similar remarks hold for float types.

Debugging 1.#IND, 1.#INF, nan, and inf

If your operation would generate a larger positive number than could be stored in a double, the operation will return 1.#INF on Windows or inf on Linux. Similarly your code will return -1.#INF or -inf if the result would be a negative number too large to store in a double. Dividing a positive number by zero produces a positive infinity and dividing a negative number by zero produces a negative infinity. Example code at the end of this page will demonstrate some operations that produce infinities.

Some operations don't make mathematical sense, such as taking the square root of a negative number. (Yes, this operation makes sense in the context of complex numbers, but a double represents a real number and so there is no double to represent the result.) The same is true for logarithms of negative numbers. Both sqrt(-1.0) and log(-1.0) would return a NaN, the generic term for a "number" that is "not a number". Windows displays a NaN as -1.#IND ("IND" for "indeterminate") while Linux displays nan. Other operations that would return a NaN include 0/0, 0*8, and 8/8. See the sample code below for examples.

In short, if you get 1.#INF or inf, look for overflow or division by zero. If you get 1.#IND or nan, look for illegal operations. Maybe you simply have a bug. If it's more subtle and you have something that is difficult to compute, see Avoiding Overflow, Underflow, and Loss of Precision. That article gives tricks for computing results that have intermediate steps overflow if computed directly.

How do I remove carriage returns with Ruby?

I think your regex is almost complete - here's what I would do:

lines2 = lines.gsub(/[\r\n]+/m, "\n")

In the above, I've put \r and \n into a class (that way it doesn't matter in which order they might appear) and added the "+" qualifier (so that "\r\n\r\n\r\n" would also match once, and the whole thing replaced with "\n")

Get 2 Digit Number For The Month

SELECT REPLACE(CONVERT(varchar, MONTH(GetDate()) * 0.01), '0.', '')

Key Presses in Python

PyAutoGui also lets you press a button multiple times:

pyautogui.press('tab', presses=5)   # press TAB five times in a row

pyautogui.press('A', presses=1000)   # press A a thousand times in a row

How to split a string in two and store it in a field

I would suggest the following:

String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

Get Client Machine Name in PHP

gethostname() using the IP from $_SERVER['REMOTE_ADDR'] while accessing the script remotely will return the IP of your internet connection, not your computer.

Does calling clone() on an array also clone its contents?

clone() creates a shallow copy. Which means the elements will not be cloned. (What if they didn't implement Cloneable?)

You may want to use Arrays.copyOf(..) for copying arrays instead of clone() (though cloning is fine for arrays, unlike for anything else)

If you want deep cloning, check this answer


A little example to illustrate the shallowness of clone() even if the elements are Cloneable:

ArrayList[] array = new ArrayList[] {new ArrayList(), new ArrayList()};
ArrayList[] clone = array.clone();
for (int i = 0; i < clone.length; i ++) {
    System.out.println(System.identityHashCode(array[i]));
    System.out.println(System.identityHashCode(clone[i]));
    System.out.println(System.identityHashCode(array[i].clone()));
    System.out.println("-----");
}

Prints:

4384790  
4384790
9634993  
-----  
1641745  
1641745  
11077203  
-----  

m2e error in MavenArchiver.getManifest()

I found my answer! I looked into the pom for any plugins that have a dependency on the maven-archiver and found the maven-jar-plugin does. It was using the latest 3.0.0 version. When I downgraded to 2.6 it seems to fix the issue :-)

Converting List<Integer> to List<String>

Instead of using String.valueOf I'd use .toString(); it avoids some of the auto boxing described by @johnathan.holland

The javadoc says that valueOf returns the same thing as Integer.toString().

List<Integer> oldList = ...
List<String> newList = new ArrayList<String>(oldList.size());

for (Integer myInt : oldList) { 
  newList.add(myInt.toString()); 
}

RecyclerView vs. ListView

I think the main and biggest difference they have is that ListView looks for the position of the item while creating or putting it, on the other hand RecyclerView looks for the type of the item. if there is another item created with the same type RecyclerView does not create it again. It asks first adapter and then asks to recycledpool, if recycled pool says "yeah I've created a type similar to it", then RecyclerView doesn't try to create same type. ListView doesn't have a this kind of pooling mechanism.

How do I create and access the global variables in Groovy?

Like all OO languages, Groovy has no concept of "global" by itself (unlike, say, BASIC, Python or Perl).

If you have several methods that need to share the same variable, use a field:

class Foo {
    def a;

    def foo() {
        a = 1;
    }
    def bar() {
        print a;
    }
}

How to check the gradle version in Android Studio?

I'm not sure if this is what you ask, but you can check gradle version of your project here in android studio:

(left pane must be in project view, not android for this path) app->gradle->wrapper->gradle-wrapper.properties

it has a line like this, indicating the gradle version:

distributionUrl=http\://services.gradle.org/distributions/gradle-1.8-all.zip

There is also a table at the end of this page that shows gradle and gradle plug-in versions supported by each android studio version. (you can check your android studio by checking help->about as you may already know)

JQuery addclass to selected div, remove class if another div is selected

It's all about the selector. You can change your code to be something like this:

<div class="formbuilder">
    <div class="active">Heading</div>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
</div>

Then use this javascript:

$(document).ready(function () {
    $('.formbuilder div').on('click', function () {
        $('.formbuilder div').removeClass('active');
        $(this).addClass('active');
    });
});

The example in a working jsfiddle

See this api about the selector I used: http://api.jquery.com/descendant-selector/

How much should a function trust another function

My 2 cents.

This is a loaded question imho. A rule of thumb I use to is see how this function will be called. If the caller is something I have control over then , its ok to assume that it will be called with the right parameters and with proper initialization.

On the other hand if its some client I don't control then it is a good idea to do thorough error checking.

Format numbers in JavaScript similar to C#

You can do it in the following way: So you will not only format the number but you can also pass as a parameter how many decimal digits to display, you set a custom decimal and mile separator.

function format(number, decimals = 2, decimalSeparator = '.', thousandsSeparator = ',') {
    const roundedNumber = number.toFixed(decimals);
    let integerPart = '', fractionalPart = '';
    if (decimals == 0) {
        integerPart = roundedNumber;
        decimalSeparator = '';
    } else {
        let numberParts = roundedNumber.split('.');
        integerPart = numberParts[0];
        fractionalPart = numberParts[1];
    }
    integerPart = integerPart.replace(/(\d)(?=(\d{3})+(?!\d))/g, `$1${thousandsSeparator}`);
    return `${integerPart}${decimalSeparator}${fractionalPart}`;
}

Use:

let min = 1556454.0001;
let max = 15556982.9999;
console.time('number format');
for (let i = 0; i < 15000; i++) {
    let randomNumber = Math.random() * (max - min) + min;

    let formated = format(randomNumber, 4, ',', '.'); // formated number

    console.debug('number: ', randomNumber, 'formated: ', formated);
}
console.timeEnd('number format');

How to run multiple .BAT files within a .BAT file

If we have two batch scripts, aaa.bat and bbb.bat, and call like below

call aaa.bat
call bbb.bat

When executing the script, it will call aaa.bat first, wait for the thread of aaa.bat terminate, and call bbb.bat.

But if you don't want to wait for aaa.bat to terminate to call bbb.bat, try to use the START command:

START ["title"] [/D path] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]
  [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]
  [/AFFINITY <hex affinity>] [/WAIT] [/B] [command/program]
  [parameters]

Exam:

start /b aaa.bat
start /b bbb.bat

How to make Bitmap compress without change the bitmap size?

i think you use this method to compress the bitmap

BitmapFactory.Option imageOpts = new BitmapFactory.Options ();
imageOpts.inSampleSize = 2;   // for 1/2 the image to be loaded
Bitmap thumb = Bitmap.createScaledBitmap (BitmapFactory.decodeFile(photoPath, imageOpts), 96, 96, false);

How to switch databases in psql?

You can connect using

\c dbname

If you would like to see all possible commands for POSTGRESQL or SQL follow this steps :

  1. rails dbconsole (You will redericted to your current ENV database)

  2. \? (For POSTGRESQL commands)

or

  1. \h (For SQL commands)

  2. Press Q to Exit

how to add values to an array of objects dynamically in javascript?

In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently

data = [...data, {"label": 2, "value": 13}]

Examples

_x000D_
_x000D_
var data = [_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
    ];_x000D_
    _x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

For your case (i know it was in 2011), we can do it with map() & forEach() like below

_x000D_
_x000D_
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
   data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
 ({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
_x000D_
_x000D_

Cycles in an Undirected Graph

I started studying graphs recently. I wrote a piece of code in java that could determine if a graph has cycles. I used DFT to find cycles in the graph. Instead of recurssion I used a stack to traverse the graph.

At a high level DFT using a stack is done in the following steps

  1. Visit a Node
  2. If the node is not in the visited list add it to the list and push it to the top of the stack
  3. Mark the node at the top of the stack as the current node.
  4. Repeat the above for each adjacent node of the current node
  5. If all the nodes have been visited pop the current node off the stack

I performed a DFT from each node of the Graph and during the traversal if I encountered a vertex that I visited earlier, I checked if the vertex had a stack depth greater than one. I also checked if a node had an edge to itself and if there were multiple edges between nodes. The stack version that I originally wrote was not very elegant. I read the pseudo code of how it could be done using recursion and it was neat. Here is a java implementation. The LinkedList array represents a graph. with each node and it's adjacent vertices denoted by the index of the array and each item respectively

class GFG {
Boolean isCyclic(int V, LinkedList<Integer>[] alist) {
    List<Integer> visited = new ArrayList<Integer>();
    for (int i = 0; i < V; i++) {
        if (!visited.contains(i)) {
            if (isCyclic(i, alist, visited, -1))
                return true;
        }
    }
    return false;
}

Boolean isCyclic(int vertex, LinkedList<Integer>[] alist, List<Integer> visited, int parent) {
    visited.add(vertex);
    for (Iterator<Integer> iterator = alist[vertex].iterator(); iterator.hasNext();) {
        int element = iterator.next();
        if (!visited.contains(element)) {
            if (isCyclic(element, alist, visited, vertex))
                return true;
        } else if (element != parent)
            return true;
    }
    return false;
}

}

HTTP POST Returns Error: 417 "Expectation Failed."

System.Net.HttpWebRequest adds the header 'HTTP header "Expect: 100-Continue"' to every request unless you explicitly ask it not to by setting this static property to false:

System.Net.ServicePointManager.Expect100Continue = false;

Some servers choke on that header and send back the 417 error you're seeing.

Give that a shot.

how get yesterday and tomorrow datetime in c#

Today :

DateTime.Today

Tomorrow :

DateTime.Today.AddDays(1)

Yesterday :

DateTime.Today.AddDays(-1)

Skipping error in for-loop

Here's a simple way

for (i in 1:10) {
  
  skip_to_next <- FALSE
  
  # Note that print(b) fails since b doesn't exist
  
  tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
  
  if(skip_to_next) { next }     
}

Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b) with any code you want. You can also wrap many lines of code in { and } if you have more than one line of code inside the tryCatch

Could not find or load main class

Simple way to compile and execute java file.(HelloWorld.java doesn't includes any package)

set path="C:\Program Files (x86)\Java\jdk1.7.0_45\bin"
javac "HelloWorld.java"
java -cp . HelloWorld
pause

Count number of files within a directory in Linux?

this is one:

ls -l . | egrep -c '^-'

Note:

ls -1 | wc -l

Which means: ls: list files in dir

-1: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too

|: pipe output onto...

wc: "wordcount"

-l: count lines.

How to remove multiple deleted files in Git repository

git status | sed 's/^#\s*deleted:\s*//' | sed 's/^#.*//' | xargs git rm -rf

How to get the path of a running JAR file?

You can also use:

CodeSource codeSource = YourMainClass.class.getProtectionDomain().getCodeSource();
File jarFile = new File(codeSource.getLocation().toURI().getPath());
String jarDir = jarFile.getParentFile().getPath();

Python RuntimeWarning: overflow encountered in long scalars

An easy way to overcome this problem is to use 64 bit type

list = numpy.array(list, dtype=numpy.float64)

How do I find all of the symlinks in a directory tree?

What I do is create a script in my bin directory that is like an alias. For example I have a script named lsd ls -l | grep ^d

you could make one lsl ls -lR | grep ^l

Just chmod them +x and you are good to go.

Margin between items in recycler view Android

Instead of using XML to add margin between items in RecyclerView, it's better way to use RecyclerView.ItemDecoration that provide by android framework.

So, I create a library to solve this issue.

https://github.com/TheKhaeng/recycler-view-margin-decoration

enter image description here

How to add local jar files to a Maven project?

Not an answer to the original question, however it might be useful for someone

There is no proper way to add multiple jar libraries from the folder using Maven. If there are only few dependencies, it is probably easier to configure maven-install-plugin as mentioned in the answers above.

However for my particular case, I had a lib folder with more than 100 proprietary jar files which I had to add somehow. And for me it was much easier for me to convert my Maven project to Gradle.

plugins {
    id 'org.springframework.boot' version '2.2.2.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
    flatDir {
       dirs 'libs' // local libs folder
   }
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    
    implementation 'io.grpc:grpc-netty-shaded:1.29.0'
    implementation 'io.grpc:grpc-protobuf:1.29.0'
    implementation 'io.grpc:grpc-stub:1.29.0' // dependecies from maven central

    implementation name: 'akka-actor_2.12-2.6.1' // dependecies from lib folder
    implementation name: 'akka-protobuf-v3_2.12-2.6.1'
    implementation name: 'akka-stream_2.12-2.6.1'

 }

Bootstrap 3: Scroll bars

You need to use overflow option like below:

.nav{
    max-height: 300px;
    overflow-y: scroll; 
}

Change the height according to amount of items you need to show

How to properly set Column Width upon creating Excel file? (Column properties)

See this snippet: (C#)

    private Microsoft.Office.Interop.Excel.Application xla;
    Workbook wb;
    Worksheet ws;
    Range rg;
    ..........

        xla = new Microsoft.Office.Interop.Excel.Application();
        wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
        ws = (Worksheet)xla.ActiveSheet;
        rg = (Range)ws.Cells[1, 2];
        rg.ColumnWidth = 10;
        rg.Value2 = "Frequency";
        rg = (Range)ws.Cells[1, 3];
        rg.ColumnWidth = 15;
        rg.Value2 = "Impudence";
        rg = (Range)ws.Cells[1, 4];
        rg.ColumnWidth = 8;
        rg.Value2 = "Phase";

How do I get Bin Path?

This is what I used to accomplish to this:

System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, System.AppDomain.CurrentDomain.RelativeSearchPath ?? "");

How can I create an utility class?

Making a class abstract sends a message to the readers of your code that you want users of your abstract class to subclass it. However, this is not what you want then to do: a utility class should not be subclassed.

Therefore, adding a private constructor is a better choice here. You should also make the class final to disallow subclassing of your utility class.

jQuery get textarea text

Normally, it's the value property

testArea.value

Or is there something I'm missing in what you need?

Get class list for element with jQuery

A bit late, but using the extend() function lets you call "hasClass()" on any element, e.g.:
var hasClass = $('#divId').hasClass('someClass');

(function($) {
$.extend({
    hasClass: new function(className) {
        var classAttr = $J(this).attr('class');
        if (classAttr != null && classAttr != undefined) {
            var classList = classAttr.split(/\s+/);
            for(var ix = 0, len = classList.length;ix < len;ix++) {
                if (className === classList[ix]) {
                    return true;
                }
            }
        }
        return false;
    }
}); })(jQuery);

PHP Regex to get youtube video ID?

Based on bokor's comment on Anthony's answer:

preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:m\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $url, $matches);

$matches[1] contains the vidid

Matches:

Does not match:

  • www.facebook.com?wtv=youtube.com/v/vidid

Visual Studio 2017: Display method references

In previous posts I have read that this feature IS available on VS 2015 community if you FIRST install SQL Server express (free) and THEN install VS. I have tried it and it worked. I just had to reinstall Windows and am going thru the same procedure now and it did not work... so will try again :). I know it worked 6 months ago when I tried.

-Ed

How can I switch views programmatically in a view controller? (Xcode, iPhone)

If you're in a Navigation Controller:

ViewController *viewController = [[ViewController alloc] init];
[self.navigationController pushViewController:viewController animated:YES];

or if you just want to present a new view:

ViewController *viewController = [[ViewController alloc] init];    
[self presentViewController:viewController animated:YES completion:nil];

Java's L number (long) specification

It seems like these would be good to have because (I assume) if you could specify the number you're typing in is a short then java wouldn't have to cast it

Since the parsing of literals happens at compile time, this is absolutely irrelevant in regard to performance. The only reason having short and byte suffixes would be nice is that it lead to more compact code.

Efficiently finding the last line in a text file

Could you load the file into a mmap, then use mmap.rfind(string[, start[, end]]) to find the second last EOL character in the file? A seek to that point in the file should point you to the last line I would think.

java.net.SocketException: Connection reset by peer: socket write error When serving a file

This problem is usually caused by writing to a connection that had already been closed by the peer. In this case it could indicate that the user cancelled the download for example.

Finding element in XDocument?

The problem is that Elements only takes the direct child elements of whatever you call it on. If you want all descendants, use the Descendants method:

var query = from c in xmlFile.Descendants("Band")

How to check if a process is in hang state (Linux)

you could check the files

/proc/[pid]/task/[thread ids]/status

good postgresql client for windows?

I like Postgresql Maestro. I also use their version for MySql. I'm pretty statisfied with their product. Or you can use the free tool PgAdmin.

PostgreSQL delete with inner join

This worked for me:

DELETE from m_productprice
WHERE  m_pricelist_version_id='1000020'
       AND m_product_id IN (SELECT m_product_id
                            FROM   m_product
                            WHERE  upc = '7094'); 

Copy/Paste from Excel to a web page

You don't lose the delimiters, the cells are separated by tabs (\t) and rows by newlines (\n) which might not be visible in the form. Try it yourself: copy content from Excel to Notepad, and you'll see your cells nicely lined up. It's easy then to split the fields by tabs and replace them with something else, this way you can build even a table from them. Here's a example using jQuery:

var data = $('input[name=excel_data]').val();
var rows = data.split("\n");

var table = $('<table />');

for(var y in rows) {
    var cells = rows[y].split("\t");
    var row = $('<tr />');
    for(var x in cells) {
        row.append('<td>'+cells[x]+'</td>');
    }
    table.append(row);
}

// Insert into DOM
$('#excel_table').html(table);

So in essence, this script creates an HTML table from pasted Excel data.

MySQL export into outfile : CSV escaping chars

Probably won't help but you could try creating a CSV table with that content:

DROP TABLE IF EXISTS foo_export;
CREATE TABLE foo_export LIKE foo;
ALTER TABLE foo_export ENGINE=CSV;
INSERT INTO foo_export SELECT id, 
   client,
   project,
   task,
   REPLACE(REPLACE(ifnull(ts.description,''),'\n',' '),'\r',' ') AS description, 
   time,
   date
  FROM ....

How to perform a sum of an int[] array

When you declare a variable, you need to declare its type - in this case: int. Also you've put a random comma in the while loop. It probably worth looking up the syntax for Java and consider using a IDE that picks up on these kind of mistakes. You probably want something like this:

int [] numbers = { 1, 2, 3, 4, 5 ,6, 7, 8, 9 , 10 };
int sum = 0;
for(int i = 0; i < numbers.length; i++){
    sum += numbers[i];
}
System.out.println("The sum is: " + sum);

"java.lang.OutOfMemoryError : unable to create new native Thread"

It's likely that your OS does not allow the number of threads you're trying to create, or you're hitting some limit in the JVM. Especially if it's such a round number as 32k, a limit of one kind or another is a very likely culprit.

Are you sure you truly need 32k threads? Most modern languages have some kind of support for pools of reusable threads - I'm sure Java has something in place too (like ExecutorService, as user Jesper mentioned). Perhaps you could request threads from such a pool, instead of manually creating new ones.

In an array of objects, fastest way to find the index of an object whose attributes match a search

Maybe you would like to use higher-order functions such as "map". Assuming you want search by 'field' attribute:

var elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor);
var objectFound = array[elementPos];

Viewing root access files/folders of android on windows

Obviously, you'll need a rooted android device. Then set up an FTP server and transfer the files.

Describe table structure

For Sybase aka SQL Anywhere the following command outputs the structure of a table:

DESCRIBE 'TABLE_NAME';

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

Exactly for this purpose I wrote a bash function called :for.

Note: :for not only preserves and returns the exit code of the failing function, but also terminates all parallel running instance. Which might not be needed in this case.

#!/usr/bin/env bash

# Wait for pids to terminate. If one pid exits with
# a non zero exit code, send the TERM signal to all
# processes and retain that exit code
#
# usage:
# :wait 123 32
function :wait(){
    local pids=("$@")
    [ ${#pids} -eq 0 ] && return $?

    trap 'kill -INT "${pids[@]}" &>/dev/null || true; trap - INT' INT
    trap 'kill -TERM "${pids[@]}" &>/dev/null || true; trap - RETURN TERM' RETURN TERM

    for pid in "${pids[@]}"; do
        wait "${pid}" || return $?
    done

    trap - INT RETURN TERM
}

# Run a function in parallel for each argument.
# Stop all instances if one exits with a non zero
# exit code
#
# usage:
# :for func 1 2 3
#
# env:
# FOR_PARALLEL: Max functions running in parallel
function :for(){
    local f="${1}" && shift

    local i=0
    local pids=()
    for arg in "$@"; do
        ( ${f} "${arg}" ) &
        pids+=("$!")
        if [ ! -z ${FOR_PARALLEL+x} ]; then
            (( i=(i+1)%${FOR_PARALLEL} ))
            if (( i==0 )) ;then
                :wait "${pids[@]}" || return $?
                pids=()
            fi
        fi
    done && [ ${#pids} -eq 0 ] || :wait "${pids[@]}" || return $?
}

usage

for.sh:

#!/usr/bin/env bash
set -e

# import :for from gist: https://gist.github.com/Enteee/c8c11d46a95568be4d331ba58a702b62#file-for
# if you don't like curl imports, source the actual file here.
source <(curl -Ls https://gist.githubusercontent.com/Enteee/c8c11d46a95568be4d331ba58a702b62/raw/)

msg="You should see this three times"

:(){
  i="${1}" && shift

  echo "${msg}"

  sleep 1
  if   [ "$i" == "1" ]; then sleep 1
  elif [ "$i" == "2" ]; then false
  elif [ "$i" == "3" ]; then
    sleep 3
    echo "You should never see this"
  fi
} && :for : 1 2 3 || exit $?

echo "You should never see this"
$ ./for.sh; echo $?
You should see this three times
You should see this three times
You should see this three times
1

References

how to merge 200 csv files in Python

fout=open("out.csv","a")
for num in range(1,201):
    for line in open("sh"+str(num)+".csv"):
         fout.write(line)    
fout.close()

How to write a comment in a Razor view?

This comment syntax should work for you:

@* enter comments here *@

Is there any way to do HTTP PUT in python

If you want to stay within the standard library, you can subclass urllib2.Request:

import urllib2

class RequestWithMethod(urllib2.Request):
    def __init__(self, *args, **kwargs):
        self._method = kwargs.pop('method', None)
        urllib2.Request.__init__(self, *args, **kwargs)

    def get_method(self):
        return self._method if self._method else super(RequestWithMethod, self).get_method()


def put_request(url, data):
    opener = urllib2.build_opener(urllib2.HTTPHandler)
    request = RequestWithMethod(url, method='PUT', data=data)
    return opener.open(request)

Adding days to a date in Python

using timedeltas you can do:

import datetime
today=datetime.date.today()


time=datetime.time()
print("today :",today)

# One day different .
five_day=datetime.timedelta(days=5)
print("one day :",five_day)
#output - 1 day , 00:00:00


# five day extend .
fitfthday=today+five_day
print("fitfthday",fitfthday)


# five day extend .
fitfthday=today+five_day
print("fitfthday",fitfthday)
#output - 
today : 2019-05-29
one day : 5 days, 0:00:00
fitfthday 2019-06-03

pip issue installing almost any library

macOS Sierra 10.12.6. Wasn't able to install anything through pip (python installed through homebrew). All the answers above didn't work.

Eventually, upgrade from python 3.5 to 3.6 worked.

brew update
brew doctor #(in case you see such suggestion by brew)

then follow any additional suggestions by brew, i.e. overwrite link to python.

What is the maximum possible length of a .NET string?

200 megs... at which point your app grinds to a virtual halt, has about a gig working set memory, and the o/s starts to act like you'll need to reboot.

static void Main(string[] args)
{
    string s = "hello world";
    for(;;)
    {
        s = s + s.Substring(0, s.Length/10);
        Console.WriteLine(s.Length);
    }
}

12
13
14
15
16
17
18
...
158905664
174796230
192275853
211503438

Setting the JVM via the command line on Windows

Yes - just explicitly provide the path to java.exe. For instance:

c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_03\bin\java.exe" -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)

c:\Users\Jon\Test>"c:\Program Files\java\jdk1.6.0_12\bin\java.exe" -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)

The easiest way to do this for a running command shell is something like:

set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%

For example, here's a complete session showing my default JVM, then the change to the path, then the new one:

c:\Users\Jon\Test>java -version
java version "1.6.0_12"
Java(TM) SE Runtime Environment (build 1.6.0_12-b04)
Java HotSpot(TM) Client VM (build 11.2-b01, mixed mode, sharing)

c:\Users\Jon\Test>set PATH=c:\Program Files\Java\jdk1.6.0_03\bin;%PATH%

c:\Users\Jon\Test>java -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)

This won't change programs which explicitly use JAVA_HOME though.

Note that if you get the wrong directory in the path - including one that doesn't exist - you won't get any errors, it will effectively just be ignored.

curl_init() function not working

On Ubuntu 18.04 these two commands solve my this problem.

sudo apt-get install php5.6-curl //install curl for php 5.6
sudo service apache2 restart //restart apache

Online SQL syntax checker conforming to multiple databases

Only know about this. Not sure how well does it against MySQL http://developer.mimer.se/validator/

HQL Hibernate INNER JOIN

Joins can only be used when there is an association between entities. Your Employee entity should not have a field named id_team, of type int, mapped to a column. It should have a ManyToOne association with the Team entity, mapped as a JoinColumn:

@ManyToOne
@JoinColumn(name="ID_TEAM")
private Team team;

Then, the following query will work flawlessly:

select e from Employee e inner join e.team

Which will load all the employees, except those that aren't associated to any team.

The same goes for all the other fields which are a foreign key to some other table mapped as an entity, of course (id_boss, id_profession).

It's time for you to read the Hibernate documentation, because you missed an extremely important part of what it is and how it works.

How to set a selected option of a dropdown list control using angular JS

Try the following:

JS file

this.options = { 
        languages: [{language: 'English', lg:'en'}, {language:'German', lg:'de'}]
};
console.log(signinDetails.language);

HTML file

<div class="form-group col-sm-6">
    <label>Preferred language</label>
    <select class="form-control" name="right" ng-model="signinDetails.language" ng-init="signinDetails.language = options.languages[0]" ng-options="l as l.language for l in options.languages"><option></option>
    </select>
</div>

Create auto-numbering on images/figures in MS Word

I assume you are using the caption feature of Word, that is, captions were not typed in as normal text, but were inserted using Insert > Caption (Word versions before 2007), or References > Insert Caption (in the ribbon of Word 2007 and up). If done correctly, the captions are really 'fields'. You'll know if it is a field if the caption's background turns grey when you put your cursor on them (or is permanently displayed grey).

Captions are fields - Unfortunately fields (like caption fields) are only updated on specific actions, like opening of the document, printing, switching from print view to normal view, etc. The easiest way to force updating of all (caption) fields when you want it is by doing the following:

  1. Select all text in your document (easiest way is to press ctrl-a)
  2. Press F9, this command tells Word to update all fields in the selection.

Captions are normal text - If the caption number is not a field, I am afraid you'll have to edit the text manually.

How to pass a datetime parameter?

Since I have encoding ISO-8859-1 operating system the date format "dd.MM.yyyy HH:mm:sss" was not recognised what did work was to use InvariantCulture string.

string url = "GetData?DagsPr=" + DagsProfs.ToString(CultureInfo.InvariantCulture)

How to create dispatch queue in Swift 3

DispatchQueue.main.async(execute: {
   // code
})

How do I find out my MySQL URL, host, port and username?

If you want to know the port number of your local host on which Mysql is running you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'port';


mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+
1 row in set (0.00 sec)

It will give you the port number on which MySQL is running.


If you want to know the hostname of your Mysql you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'hostname';


mysql> SHOW VARIABLES WHERE Variable_name = 'hostname';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| hostname          | Dell  |
+-------------------+-------+
1 row in set (0.00 sec)

It will give you the hostname for mysql.


If you want to know the username of your Mysql you can use this query on MySQL Command line client --

select user();   


mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

It will give you the username for mysql.

How can I open a URL in Android's web browser from my application?

Webview can be used to load Url in your applicaion. URL can be provided from user in text view or you can hardcode it.

Also don't forget internet permissions in AndroidManifest.

String url="http://developer.android.com/index.html"

WebView wv=(WebView)findViewById(R.id.webView);
wv.setWebViewClient(new MyBrowser());
wv.getSettings().setLoadsImagesAutomatically(true);
wv.getSettings().setJavaScriptEnabled(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv.loadUrl(url);

private class MyBrowser extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

How to write both h1 and h2 in the same line?

<h1 style="text-align: left; float: left;">Text 1</h1>
<h2 style="text-align: right; float: right; display: inline;">Text 2</h2>
<hr style="clear: both;" />

Hope this helps!

Animate an element's width from 0 to 100%, with it and it's wrapper being only as wide as they need to be, without a pre-set width, in CSS3 or jQuery

Got it to work by transitioning the padding as well as the width.

JSFiddle: http://jsfiddle.net/tuybk748/1/

<div class='label gray'>+
</div><!-- must be connected to prevent gap --><div class='contents-wrapper'>
    <div class="gray contents">These are the contents of this div</div>
</div>
.gray {
    background: #ddd;
}
.contents-wrapper, .label, .contents {
    display: inline-block;
}
.label, .contents {
    overflow: hidden; /* must be on both divs to prevent dropdown behavior */
    height: 20px;
}
.label {
    padding: 10px 10px 15px;
}
.contents {
    padding: 10px 0px 15px; /* no left-right padding at beginning */
    white-space: nowrap; /* keeps text all on same line */
    width: 0%;
    -webkit-transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
    -moz-transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
    -o-transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
    transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
}
.label:hover + .contents-wrapper .contents {
    width: 100%;
    padding-left: 10px;
    padding-right: 10px;
}

How to select the nth row in a SQL database table?

Verify it on SQL Server:

Select top 10 * From emp 
EXCEPT
Select top 9 * From emp

This will give you 10th ROW of emp table!

git replacing LF with CRLF

  1. Open the file in the Notepad++.
  2. Go to Edit/EOL Conversion.
  3. Click to the Windows Format.
  4. Save the file.

docker: "build" requires 1 argument. See 'docker build --help'


You Need a DOT at the end...


So for example:

$ docker build -t <your username>/node-web-app .

It's a bit hidden, but if you pay attention to the . at the end...

ValueError: unsupported format character while forming strings

Well, why do you have %20 url-quoting escapes in a formatting string in first place? Ideally you'd do the interpolation formatting first:

formatting_template = 'Hello World%s'
text = '!'
full_string = formatting_template % text

Then you url quote it afterwards:

result = urllib.quote(full_string)

That is better because it would quote all url-quotable things in your string, including stuff that is in the text part.

How do I resize a Google Map with JavaScript after it has loaded?

for Google Maps v3, you need to trigger the resize event differently:

google.maps.event.trigger(map, "resize");

See the documentation for the resize event (you'll need to search for the word 'resize'): http://code.google.com/apis/maps/documentation/v3/reference.html#event


Update

This answer has been here a long time, so a little demo might be worthwhile & although it uses jQuery, there's no real need to do so.

_x000D_
_x000D_
$(function() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644)
  };
  var map = new google.maps.Map($("#map-canvas")[0], mapOptions);

  // listen for the window resize event & trigger Google Maps to update too
  $(window).resize(function() {
    // (the 'map' here is the result of the created 'var map = ...' above)
    google.maps.event.trigger(map, "resize");
  });
});
_x000D_
html,
body {
  height: 100%;
}
#map-canvas {
  min-width: 200px;
  width: 50%;
  min-height: 200px;
  height: 80%;
  border: 1px solid blue;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&dummy=.js"></script>
Google Maps resize demo
<div id="map-canvas"></div>
_x000D_
_x000D_
_x000D_

UPDATE 2018-05-22

With a new renderer release in version 3.32 of Maps JavaScript API the resize event is no longer a part of Map class.

The documentation states

When the map is resized, the map center is fixed

  • The full-screen control now preserves center.

  • There is no longer any need to trigger the resize event manually.

source: https://developers.google.com/maps/documentation/javascript/new-renderer

google.maps.event.trigger(map, "resize"); doesn't have any effect starting from version 3.32

Iterate over values of object

In the sense I think you intended, in ES5 or ES2015, no, not without some work on your part.

In ES2016, probably with object.values.

Mind you Arrays in JavaScript are effectively a map from an integer to a value, and the values in JavaScript arrays can be enumerated directly.

['foo', 'bar'].forEach(v => console.log(v)); // foo bar

Also, in ES2015, you can make an object iterable by placing a function on a property with the name of Symbol.iterator:

var obj = { 
    foo: '1', 
    bar: '2',
    bam: '3',
    bat: '4',
};

obj[Symbol.iterator] = iter.bind(null, obj);

function* iter(o) {
    var keys = Object.keys(o);
    for (var i=0; i<keys.length; i++) {
        yield o[keys[i]];
    }
}

for(var v of obj) { console.log(v); } // '1', '2', '3', '4'

Also, per other answers, there are other built-ins that provide the functionality you want, like Map (but not WeakMap because it is not iterable) and Set for example (but these are not present in all browsers yet).

How to get all options of a select using jQuery?

Here is a simple example in jquery to get all the values, texts, or value of the selected item, or text of the selected item

$('#nCS1 > option').each((index, obj) => {
   console.log($(obj).val());
})

_x000D_
_x000D_
printOptionValues = () => {_x000D_
_x000D_
  $('#nCS1 > option').each((index, obj) => {_x000D_
    console.log($(obj).val());_x000D_
  })_x000D_
_x000D_
}_x000D_
_x000D_
printOptionTexts = () => {_x000D_
  $('#nCS1 > option').each((index, obj) => {_x000D_
    console.log($(obj).text());_x000D_
  })_x000D_
}_x000D_
_x000D_
printSelectedItemText = () => {_x000D_
  console.log($('#nCS1 option:selected').text());_x000D_
}_x000D_
_x000D_
printSelectedItemValue = () => {_x000D_
  console.log($('#nCS1 option:selected').val());_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<select size="1" id="nCS1" name="nCS1" class="form-control" >_x000D_
     <option value="22">Australia</option>_x000D_
          <option value="23">Brunei</option>_x000D_
          <option value="33">Cambodia</option>_x000D_
          <option value="32">Canada</option>_x000D_
          <option value="27">Dubai</option>_x000D_
          <option value="28">Indonesia</option>_x000D_
          <option value="25">Malaysia</option>    _x000D_
</select>_x000D_
<br/>_x000D_
<input type='button' onclick='printOptionValues()' value='print option values' />_x000D_
<br/>_x000D_
<input type='button' onclick='printOptionTexts()' value='print option texts' />_x000D_
<br/>_x000D_
<input type='button' onclick='printSelectedItemText()' value='print selected option text'/>_x000D_
<br/>_x000D_
<input type='button' onclick='printSelectedItemValue()' value='print selected option value' />
_x000D_
_x000D_
_x000D_

Remove grid, background color, and top and right borders from ggplot2

Recent updates to ggplot (0.9.2+) have overhauled the syntax for themes. Most notably, opts() is now deprecated, having been replaced by theme(). Sandy's answer will still (as of Jan '12) generates a chart, but causes R to throw a bunch of warnings.

Here's updated code reflecting current ggplot syntax:

library(ggplot2)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))

#base ggplot object
p <- ggplot(df, aes(x = a, y = b))

p +
  #plots the points
  geom_point() +

  #theme with white background
  theme_bw() +

  #eliminates background, gridlines, and chart border
  theme(
    plot.background = element_blank(),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank(),
    panel.border = element_blank()
  ) +

  #draws x and y axis line
  theme(axis.line = element_line(color = 'black'))

generates:

plot output

How do I convert a datetime to date?

You use the datetime.datetime.date() method:

datetime.datetime.now().date()

Obviously, the expression above can (and should IMHO :) be written as:

datetime.date.today()

This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer

This issue arises due to updates, You can resolve this by downgrading the gradle used from com.android.tools.build:gradle:3.2.1 to a previous gradle like com.android.tools.build:gradle:3.0.0 or anything older than the current one

Laravel Unknown Column 'updated_at'

Setting timestamps to false means you are going to lose both created_at and updated_at whereas you could set both of the keys in your model.

Case 1:

You have created_at column but not update_at you could simply set updated_at to false in your model

class ABC extends Model {

const UPDATED_AT = null;

Case 2:

You have both created_at and updated_at columns but with different column names

You could simply do:

class ABC extends Model {

const CREATED_AT = 'name_of_created_at_column';
const UPDATED_AT = 'name_of_updated_at_column';

Finally ignoring timestamps completely:

class ABC extends Model {

public $timestamps = false;

How to filter JSON Data in JavaScript or jQuery?

This is how you should do it : ( for google find)

$([
  {"name":"Lenovo Thinkpad 41A4298","website":"google222"},
  {"name":"Lenovo Thinkpad 41A2222","website":"google"}
  ])
    .filter(function (i,n){
        return n.website==='google';
    });

Better solution : ( Salman's)

$.grep( [{"name":"Lenovo Thinkpad 41A4298","website":"google"},{"name":"Lenovo Thinkpad 41A2222","website":"google"}], function( n, i ) {
  return n.website==='google';
});

http://jsbin.com/yakubixi/4/edit

Cannot find pkg-config error

Try

iOS: Convert UTC NSDate to local Timezone

Convert the date from the UTC calendar to one with the appropriate local NSTimeZone.

Conditionally displaying JSF components

Yes, use the rendered attribute.

<h:form rendered="#{some boolean condition}">

You usually tie it to the model rather than letting the model grab the component and manipulate it.

E.g.

<h:form rendered="#{bean.booleanValue}" />
<h:form rendered="#{bean.intValue gt 10}" />
<h:form rendered="#{bean.objectValue eq null}" />
<h:form rendered="#{bean.stringValue ne 'someValue'}" />
<h:form rendered="#{not empty bean.collectionValue}" />
<h:form rendered="#{not bean.booleanValue and bean.intValue ne 0}" />
<h:form rendered="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

Note the importance of keyword based EL operators such as gt, ge, le and lt instead of >, >=, <= and < as angle brackets < and > are reserved characters in XML. See also this related Q&A: Error parsing XHTML: The content of elements must consist of well-formed character data or markup.

As to your specific use case, let's assume that the link is passing a parameter like below:

<a href="page.xhtml?form=1">link</a>

You can then show the form as below:

<h:form rendered="#{param.form eq '1'}">

(the #{param} is an implicit EL object referring to a Map representing the request parameters)

See also:

How to pass params with history.push/Link/Redirect in react-router v4?

React TypeScript with Hooks

From a Class

  this.history.push({
      pathname: "/unauthorized",
      state: { message: "Hello" },
    });

UnAuthorized Functional Component

interface IState {
  message?: string;
}

export default function UnAuthorized() {
  const location = useLocation();
  const message = (location.state as IState).message;

  return (
    <div className="jumbotron">
      <h6>{message}</h6>
    </div>
  );
}

std::enable_if to conditionally compile a member function

Here is my minimalist example, using a macro. Use double brackets enable_if((...)) when using more complex expressions.

template<bool b, std::enable_if_t<b, int> = 0>
using helper_enable_if = int;

#define enable_if(value) typename = helper_enable_if<value>

struct Test
{
     template<enable_if(false)>
     void run();
}

Get file size, image width and height before upload

Here is a pure JavaScript example of picking an image file, displaying it, looping through the image properties, and then re-sizing the image from the canvas into an IMG tag and explicitly setting the re-sized image type to jpeg.

If you right click the top image, in the canvas tag, and choose Save File As, it will default to a PNG format. If you right click, and Save File as the lower image, it will default to a JPEG format. Any file over 400px in width is reduced to 400px in width, and a height proportional to the original file.

HTML

<form class='frmUpload'>
  <input name="picOneUpload" type="file" accept="image/*" onchange="picUpload(this.files[0])" >
</form>

<canvas id="cnvsForFormat" width="400" height="266" style="border:1px solid #c3c3c3"></canvas>
<div id='allImgProperties' style="display:inline"></div>

<div id='imgTwoForJPG'></div>

SCRIPT

<script>

window.picUpload = function(frmData) {
  console.log("picUpload ran: " + frmData);

var allObjtProperties = '';
for (objProprty in frmData) {
    console.log(objProprty + " : " + frmData[objProprty]);
    allObjtProperties = allObjtProperties + "<span>" + objProprty + ": " + frmData[objProprty] + ", </span>";
};

document.getElementById('allImgProperties').innerHTML = allObjtProperties;

var cnvs=document.getElementById("cnvsForFormat");
console.log("cnvs: " + cnvs);
var ctx=cnvs.getContext("2d");

var img = new Image;
img.src = URL.createObjectURL(frmData);

console.log('img: ' + img);

img.onload = function() {
  var picWidth = this.width;
  var picHeight = this.height;

  var wdthHghtRatio = picHeight/picWidth;
  console.log('wdthHghtRatio: ' + wdthHghtRatio);

  if (Number(picWidth) > 400) {
    var newHeight = Math.round(Number(400) * wdthHghtRatio);
  } else {
    return false;
  };

    document.getElementById('cnvsForFormat').height = newHeight;
    console.log('width: 400  h: ' + newHeight);
    //You must change the width and height settings in order to decrease the image size, but
    //it needs to be proportional to the original dimensions.
    console.log('This is BEFORE the DRAW IMAGE');
    ctx.drawImage(img,0,0, 400, newHeight);

    console.log('THIS IS AFTER THE DRAW IMAGE!');

    //Even if original image is jpeg, getting data out of the canvas will default to png if not specified
    var canvasToDtaUrl = cnvs.toDataURL("image/jpeg");
    //The type and size of the image in this new IMG tag will be JPEG, and possibly much smaller in size
    document.getElementById('imgTwoForJPG').innerHTML = "<img src='" + canvasToDtaUrl + "'>";
};
};

</script>

Here is a jsFiddle:

jsFiddle Pick, display, get properties, and Re-size an image file

In jsFiddle, right clicking the top image, which is a canvas, won't give you the same save options as right clicking the bottom image in an IMG tag.

Fastest way to write huge data in text file Java

For those who want to improve the time for retrieval of records and dump into the file (i.e no processing on records), instead of putting them into an ArrayList, append those records into a StringBuffer. Apply toSring() function to get a single String and write it into the file at once.

For me, the retrieval time reduced from 22 seconds to 17 seconds.

Markdown and including multiple files

In fact you can use \input{filename} and \include{filename} which are latex commands, directly in Pandoc, because it supports nearly all html and latex syntax.

But beware, the included file will be treated as latex file. But you can compile your markdown to latex with Pandox easily.

Read from database and fill DataTable

Connection object is for illustration only. The DataAdapter is the key bit:

Dim strSql As String = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
  cnn.Open()
  Using dad As New SqlDataAdapter(strSql, cnn)
    dad.Fill(dtb)
  End Using
  cnn.Close()
End Using

How do I make background-size work in IE?

you can use this file (https://github.com/louisremi/background-size-polyfill “background-size polyfill”) for IE8 that is really simple to use:

.selector {
background-size: cover;
-ms-behavior: url(/backgroundsize.min.htc);
}

How to count total lines changed by a specific author in a Git repository?

After looking at Alex's and Gerty3000's answer, I have tried to shorten the one-liner:

Basically, using git log numstat and not keeping track of the number of files changed.

Git version 2.1.0 on Mac OSX:

git log --format='%aN' | sort -u | while read name; do echo -en "$name\t"; git log --author="$name" --pretty=tformat: --numstat | awk '{ add += $1; subs += $2; loc += $1 - $2 } END { printf "added lines: %s, removed lines: %s, total lines: %s\n", add, subs, loc }' -; done

Example:

Jared Burrows   added lines: 6826, removed lines: 2825, total lines: 4001

Count number of tables in Oracle

Use this query which will give you the actual no of counts in respect to the table owners

SELECT COUNT(*),tablespace_name  FROM USER_TABLES group by tablespace_name;

Version vs build in Xcode

Another way is to set the version number in appDelegate didFinishLaunchingWithOptions:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     NSString * ver = [self myVersion];
     NSLog(@"version: %@",ver);

     NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
     [userDefaults setObject:ver forKey:@"version"];
     return YES;
}

- (NSString *) myVersion {
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    return [NSString stringWithFormat:@"%@ build %@", version, build];
}

Didn't Java once have a Pair class?

A Pair class :

public class Pair<K, V> {

    private final K element0;
    private final V element1;

    public static <K, V> Pair<K, V> createPair(K element0, V element1) {
        return new Pair<K, V>(element0, element1);
    }

    public Pair(K element0, V element1) {
        this.element0 = element0;
        this.element1 = element1;
    }

    public K getElement0() {
        return element0;
    }

    public V getElement1() {
        return element1;
    }

}

usage :

Pair<Integer, String> pair = Pair.createPair(1, "test");
pair.getElement0();
pair.getElement1();

Immutable, only a pair !

How can I generate a random number in a certain range?

So you would want the following:

int random;
int max;
int min;

...somewhere in your code put the method to get the min and max from the user when they click submit and then use them in the following line of code:

random = Random.nextInt(max-min+1)+min;

This will set random to a random number between the user selected min and max. Then you will do:

TextView.setText(random.toString());

How to enable native resolution for apps on iPhone 6 and 6 Plus?

An error was encountered while running (Domain = LaunchServicesError, Code = 0)

Usually this indicates that installd returned an error during the install process (bad resources or similar).

Unfortunately, Xcode does not display the actual underlying error (feel free to file dupes of this known bug).

You should check ~/Library/Logs/CoreSimulator/CoreSimulator.log which will log the underlying error for you.

How to set dropdown arrow in spinner?

From the API level 16 and above, you can use following code to change the drop down icon in spinner. just goto onItemSelected in setonItemSelectedListener and change the drawable of textview selected like this.

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
  // give the color which ever you want to give to spinner item in this line of code               
//API Level 16 and above only. 
           ((TextView)parent.getChildAt(position)).setCompoundDrawablesRelativeWithIntrinsicBounds(null,null,ContextCompat.getDrawable(Activity.this,R.drawable.icon),null);
 //Basically itis changing the drawable of textview, we have change the textview left drawable.

}
        @Override
        public void onNothingSelected(AdapterView<?> parent) {

}
    });

hope it will help somebody.

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

I know that we are (n-1) * (n times), but why the division by 2?

It's only (n - 1) * n if you use a naive bubblesort. You can get a significant savings if you notice the following:

  • After each compare-and-swap, the largest element you've encountered will be in the last spot you were at.

  • After the first pass, the largest element will be in the last position; after the kth pass, the kth largest element will be in the kth last position.

Thus you don't have to sort the whole thing every time: you only need to sort n - 2 elements the second time through, n - 3 elements the third time, and so on. That means that the total number of compare/swaps you have to do is (n - 1) + (n - 2) + .... This is an arithmetic series, and the equation for the total number of times is (n - 1)*n / 2.

Example: if the size of the list is N = 5, then you do 4 + 3 + 2 + 1 = 10 swaps -- and notice that 10 is the same as 4 * 5 / 2.

Converting newline formatting from Mac to Windows

Just do tr delete:

tr -d "\r" <infile.txt >outfile.txt

Regarding Java switch statements - using return and omitting breaks in each case

Nope, what you have is fine. You could also do this as a formula (sliderVal < 5 ? (1.0 - 0.1 * sliderVal) : 1.0) or use a Map<Integer,Double>, but what you have is fine.

How to get CRON to call in the correct PATHs

Problem

Your script works when you run it from the console but fails in cron.

Cause

Your crontab doesn't have the right path variables (and possibly shell)

Solution

Add your current shell and path the crontab

Script to do it for you

#!/bin/bash
#
# Date: August 22, 2013
# Author: Steve Stonebraker
# File: add_current_shell_and_path_to_crontab.sh
# Description: Add current user's shell and path to crontab
# Source: http://brakertech.com/add-current-path-to-crontab
# Github: hhttps://github.com/ssstonebraker/braker-scripts/blob/master/working-scripts/add_current_shell_and_path_to_crontab.sh

# function that is called when the script exits (cleans up our tmp.cron file)
function finish { [ -e "tmp.cron" ] && rm tmp.cron; }

#whenver the script exits call the function "finish"
trap finish EXIT

########################################
# pretty printing functions
function print_status { echo -e "\x1B[01;34m[*]\x1B[0m $1"; }
function print_good { echo -e "\x1B[01;32m[*]\x1B[0m $1"; }
function print_error { echo -e "\x1B[01;31m[*]\x1B[0m $1"; }
function print_notification { echo -e "\x1B[01;33m[*]\x1B[0m $1"; }
function printline { 
  hr=-------------------------------------------------------------------------------------------------------------------------------
  printf '%s\n' "${hr:0:${COLUMNS:-$(tput cols)}}"
}
####################################
# print message and exit program
function die { print_error "$1"; exit 1; }

####################################
# user must have at least one job in their crontab
function require_gt1_user_crontab_job {
        crontab -l &> /dev/null
        [ $? -ne 0 ] && die "Script requires you have at least one user crontab job!"
}


####################################
# Add current shell and path to user's crontab
function add_shell_path_to_crontab {
    #print info about what's being added
    print_notification "Current SHELL: ${SHELL}"
    print_notification "Current PATH: ${PATH}"

    #Add current shell and path to crontab
    print_status "Adding current SHELL and PATH to crontab \nold crontab:"

    printline; crontab -l; printline

    #keep old comments but start new crontab file
    crontab -l | grep "^#" > tmp.cron

    #Add our current shell and path to the new crontab file
    echo -e "SHELL=${SHELL}\nPATH=${PATH}\n" >> tmp.cron 

    #Add old crontab entries but ignore comments or any shell or path statements
    crontab -l | grep -v "^#" | grep -v "SHELL" | grep -v "PATH" >> tmp.cron

    #load up the new crontab we just created
    crontab tmp.cron

    #Display new crontab
    print_good "New crontab:"
    printline; crontab -l; printline
}

require_gt1_user_crontab_job
add_shell_path_to_crontab

Source

https://github.com/ssstonebraker/braker-scripts/blob/master/working-scripts/add_current_shell_and_path_to_crontab.sh

Sample Output

add_curent_shell_and_path_to_crontab.sh example output

How do I set combobox read-only or user cannot write in a combo box only can select the given items?

Make the DropDownStyle to DropDownList

stateComboBox.DropDownStyle = ComboBoxStyle.DropDownList;

How to style HTML5 range input to have different color before and after slider?

It's now supported with pseudo elements in each of WebKit, Firefox and IE. But, of course, it's different in each one. : (

See this question's answers and/or search for a CodePen titled prettify <input type=range> #101 for some solutions.

How to get changes from another branch

  1. go to the master branch our-team

    • git checkout our-team
  2. pull all the new changes from our-team branch

    • git pull
  3. go to your branch featurex

    • git checkout featurex
  4. merge the changes of our-team branch into featurex branch

    • git merge our-team
    • or git cherry-pick {commit-hash} if you want to merge specific commits
  5. push your changes with the changes of our-team branch

    • git push

Note: probably you will have to fix conflicts after merging our-team branch into featurex branch before pushing

Unable to compile class for JSP: The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

There are a lot of correct/same answers, but for future references:

Same stands for Tomcat 7. Be aware that updating only your used frameworks' versions (as proposed in other similar questions) isn't enough.

You also have to update Tomcat plugin's version. What worked for me, using Java 7, was upgrading to version 2.2 of tomcat7-maven-plugin (= Tomcat 7.0.47).

In Javascript/jQuery what does (e) mean?

$(this).click(function(e) {
    // does something
});

In reference to the above code
$(this) is the element which as some variable.
click is the event that needs to be performed.
the parameter e is automatically passed from js to your function which holds the value of $(this) value and can be used further in your code to do some operation.

CSV parsing in Java - working example..?

At a minimum you are going to need to know the column delimiter.

Need to ZIP an entire directory using Node.js

Use Node's native child_process api to accomplish this.

No need for third party libs. Two lines of code.

const child_process = require("child_process");
child_process.execSync(`zip -r DESIRED_NAME_OF_ZIP_FILE_HERE *`, {
  cwd: PATH_TO_FOLDER_YOU_WANT_ZIPPED_HERE
});

I'm using the synchronous API. You can use child_process.exec(path, options, callback) if you need async. There are a lot more options than just specifying the CWD to further finetune your requests. See exec/execSync docs.


Please note: This example assumes you have the zip utility installed on your system (it comes with OSX, at least). Some operating systems may not have utility installed (i.e., AWS Lambda runtime doesn't). In that case, you can easily obtain the zip utility binary here and package it along with your application source code (for AWS Lambda you can package it in a Lambda Layer as well), or you'll have to either use a third party module (of which there are plenty on NPM). I prefer the former approach, as the ZIP utility is tried and tested for decades.

Can we execute a java program without a main() method?

Now - no


Prior to Java 7:

Yes, sequence is as follows:

  • jvm loads class
  • executes static blocks
  • looks for main method and invokes it

So, if there's code in a static block, it will be executed. But there's no point in doing that.

How to test that:

public final class Test {
    static {
        System.out.println("FOO");
    }
}

Then if you try to run the class (either form command line with java Test or with an IDE), the result is:

FOO
java.lang.NoSuchMethodError: main

What is the difference between Python's list methods append and extend?

extend(L) extends the list by appending all the items in the given list L.

>>> a
[1, 2, 3]
a.extend([4])  #is eqivalent of a[len(a):] = [4]
>>> a
[1, 2, 3, 4]
a = [1, 2, 3]
>>> a
[1, 2, 3]
>>> a[len(a):] = [4]
>>> a
[1, 2, 3, 4]

PHP Error: Function name must be a string

In PHP.js, $_COOKIE is a function ;-)

function $_COOKIE(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return decodeURIComponent(c.substring(nameEQ.length,c.length).replace(/\+/g, '%20'));
    }
    return null;
}

via http://phpjs.org/functions/setcookie:509

Java JTable getting the data of the selected row

Just simple like this:

    tbl.addMouseListener(new MouseListener() {
        @Override
        public void mouseReleased(MouseEvent e) {
        }
        @Override
        public void mousePressed(MouseEvent e) {
            String selectedCellValue = (String) tbl.getValueAt(tbl.getSelectedRow() , tbl.getSelectedColumn());
            System.out.println(selectedCellValue);
        }
        @Override
        public void mouseExited(MouseEvent e) {
        }
        @Override
        public void mouseEntered(MouseEvent e) {
        }
        @Override
        public void mouseClicked(MouseEvent e) {
        }
    });

how to refresh page in angular 2

Just in case someone else encounters this problem. You need to call

window.location.reload()

And you cannot call this from a expression. If you want to call this from a click event you need to put this on a function:

(click)="realodPage()"

And simply define the function:

reloadPage() {
   window.location.reload();
}

If you are changing the route, it might not work because the click event seems to happen before the route changes. A very dirty solution is just to add a small delay

reloadPage() {
    setTimeout(()=>{
      window.location.reload();
    }, 100);
}

Replace input type=file by an image

I would use SWFUpload or Uploadify. They need Flash but do everything you want without troubles.

Any <input type="file"> based workaround that tries to trigger the "open file" dialog by means other than clicking on the actual control could be removed from browsers for security reasons at any time. (I think in the current versions of FF and IE, it is not possible any more to trigger that event programmatically.)

Converting between java.time.LocalDateTime and java.util.Date

I'm not sure if this is the simplest or best way, or if there are any pitfalls, but it works:

static public LocalDateTime toLdt(Date date) {
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(date);
    ZonedDateTime zdt = cal.toZonedDateTime();
    return zdt.toLocalDateTime();
}

static public Date fromLdt(LocalDateTime ldt) {
    ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());
    GregorianCalendar cal = GregorianCalendar.from(zdt);
    return cal.getTime();
}

background:none vs background:transparent what is the difference?

As aditional information on @Quentin answer, and as he rightly says, background CSS property itself, is a shorthand for:

background-color
background-image
background-repeat
background-attachment
background-position

That's mean, you can group all styles in one, like:

background: red url(../img.jpg) 0 0 no-repeat fixed;

This would be (in this example):

background-color: red;
background-image: url(../img.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
background-position: 0 0;

So... when you set: background:none;
you are saying that all the background properties are set to none...
You are saying that background-image: none; and all the others to the initial state (as they are not being declared).
So, background:none; is:

background-color: initial;
background-image: none;
background-repeat: initial;
background-attachment: initial;
background-position: initial;

Now, when you define only the color (in your case transparent) then you are basically saying:

background-color: transparent;
background-image: initial;
background-repeat: initial;
background-attachment: initial;
background-position: initial;

I repeat, as @Quentin rightly says the default transparent and none values in this case are the same, so in your example and for your original question, No, there's no difference between them.

But!.. if you say background:none Vs background:red then yes... there's a big diference, as I say, the first would set all properties to none/default and the second one, will only change the color and remains the rest in his default state.

So in brief:

Short answer: No, there's no difference at all (in your example and orginal question)
Long answer: Yes, there's a big difference, but depends directly on the properties granted to attribute.


Upd1: Initial value (aka default)

Initial value the concatenation of the initial values of its longhand properties:

background-image: none
background-position: 0% 0%
background-size: auto auto
background-repeat: repeat
background-origin: padding-box
background-style: is itself a shorthand, its initial value is the concatenation of its own longhand properties
background-clip: border-box
background-color: transparent

See more background descriptions here


Upd2: Clarify better the background:none; specification.

How do the major C# DI/IoC frameworks compare?

See for a comparison of net-ioc-frameworks on google code including linfu and spring.net that are not on your list while i write this text.

I worked with spring.net: It has many features (aop, libraries , docu, ...) and there is a lot of experience with it in the dotnet and the java-world. The features are modularized so you donot have to take all features. The features are abstractions of common issues like databaseabstraction, loggingabstraction. however it is difficuilt to do and debug the IoC-configuration.

From what i have read so far: If i had to chooseh for a small or medium project i would use ninject since ioc-configuration is done and debuggable in c#. But i havent worked with it yet. for large modular system i would stay with spring.net because of abstraction-libraries.

Type of expression is ambiguous without more context Swift

Not an answer to this question, but as I came here looking for the error others might find this also useful:

For me, I got this Swift error when I tried to use the for (index, object) loop on an array without adding the .enumerated() part ...

How to filter by object property in angularJS

The documentation has the complete answer. Anyway this is how it is done:

<input type="text" ng-model="filterValue">
<li ng-repeat="i in data | filter:{age:filterValue}:true"> {{i | json }}</li>

will filter only age in data array and true is for exact match.

For deep filtering,

<li ng-repeat="i in data | filter:{$:filterValue}:true"> {{i}}</li>

The $ is a special property for deep filter and the true is for exact match like above.

Show div #id on click with jQuery

You can use jQuery toggle to show and hide the div. The script will be like this

  <script type="text/javascript">
    jQuery(function(){
      jQuery("#music").click(function () {
        jQuery("#musicinfo").toggle("slow");
      });
    });
</script>

Android: alternate layout xml for landscape mode

The layouts in /res/layout are applied to both portrait and landscape, unless you specify otherwise. Let’s assume we have /res/layout/home.xml for our homepage and we want it to look differently in the 2 layout types.

  1. create folder /res/layout-land (here you will keep your landscape adjusted layouts)
  2. copy home.xml there
  3. make necessary changes to it

Source

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

Open your mysql file any edit tool

find

/*!40101 SET NAMES utf8mb4 */;

change

/*!40101 SET NAMES utf8 */;

Save and upload ur mysql.

MySQL SELECT AS combine two columns into one

If both columns can contain NULL, but you still want to merge them to a single string, the easiest solution is to use CONCAT_WS():

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT_WS('', ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

This way you won't have to check for NULL-ness of each column separately.

Alternatively, if both columns are actually defined as NOT NULL, CONCAT() will be quite enough:

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

As for COALESCE, it's a bit different beast: given the list of arguments, it returns the first that's not NULL.

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

I think this sort of question is entirely appropriate to the forum, especially if an easy solution can be found, as would save others hours of pain.

Unfortunately I dont have the solution, but would suggest (if you haven't already)

  1. Run FileMon to see if the installer is looking for specific files which are no longer there - this may give some clues.

  2. Painful, but try uninstalling other apps based upon the VS shell (eg 2005) first.

Simple JavaScript problem: onClick confirm not preventing default action

I've had issue with IE7 and returning false before.

Check my answer here to another problem: Javascript not running on IE

How to get enum value by string or int

You could use following method to do that:

public static Output GetEnumItem<Output, Input>(Input input)
    {
        //Output type checking...
        if (typeof(Output).BaseType != typeof(Enum))
            throw new Exception("Exception message...");

        //Input type checking: string type
        if (typeof(Input) == typeof(string))
            return (Output)Enum.Parse(typeof(Output), (dynamic)input);

        //Input type checking: Integer type
        if (typeof(Input) == typeof(Int16) ||
            typeof(Input) == typeof(Int32) ||
            typeof(Input) == typeof(Int64))

            return (Output)(dynamic)input;

        throw new Exception("Exception message...");
    }

Note:this method only is a sample and you can improve it.

Java 8 Stream API to find Unique Object matching a property value

findAny & orElse

By using findAny() and orElse():

Person matchingObject = objects.stream().
filter(p -> p.email().equals("testemail")).
findAny().orElse(null);

Stops looking after finding an occurrence.

findAny

Optional<T> findAny()

Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)

How do I compare two strings in Perl?

In addtion to Sinan Ünür comprehensive listing of string comparison operators, Perl 5.10 adds the smart match operator.

The smart match operator compares two items based on their type. See the chart below for the 5.10 behavior (I believe this behavior is changing slightly in 5.10.1):

perldoc perlsyn "Smart matching in detail":

The behaviour of a smart match depends on what type of thing its arguments are. It is always commutative, i.e. $a ~~ $b behaves the same as $b ~~ $a . The behaviour is determined by the following table: the first row that applies, in either order, determines the match behaviour.

  $a      $b        Type of Match Implied    Matching Code
  ======  =====     =====================    =============
  (overloading trumps everything)

  Code[+] Code[+]   referential equality     $a == $b   
  Any     Code[+]   scalar sub truth         $b->($a)   

  Hash    Hash      hash keys identical      [sort keys %$a]~~[sort keys %$b]
  Hash    Array     hash slice existence     grep {exists $a->{$_}} @$b
  Hash    Regex     hash key grep            grep /$b/, keys %$a
  Hash    Any       hash entry existence     exists $a->{$b}

  Array   Array     arrays are identical[*]
  Array   Regex     array grep               grep /$b/, @$a
  Array   Num       array contains number    grep $_ == $b, @$a 
  Array   Any       array contains string    grep $_ eq $b, @$a 

  Any     undef     undefined                !defined $a
  Any     Regex     pattern match            $a =~ /$b/ 
  Code()  Code()    results are equal        $a->() eq $b->()
  Any     Code()    simple closure truth     $b->() # ignoring $a
  Num     numish[!] numeric equality         $a == $b   
  Any     Str       string equality          $a eq $b   
  Any     Num       numeric equality         $a == $b   

  Any     Any       string equality          $a eq $b   

+ - this must be a code reference whose prototype (if present) is not ""
(subs with a "" prototype are dealt with by the 'Code()' entry lower down) 
* - that is, each element matches the element of same index in the other
array. If a circular reference is found, we fall back to referential 
equality.   
! - either a real number, or a string that looks like a number

The "matching code" doesn't represent the real matching code, of course: it's just there to explain the intended meaning. Unlike grep, the smart match operator will short-circuit whenever it can.

Custom matching via overloading You can change the way that an object is matched by overloading the ~~ operator. This trumps the usual smart match semantics. See overload.

How to change Tkinter Button state from disabled to normal?

I think a quick way to change the options of a widget is using the configure method.

In your case, it would look like this:

self.x.configure(state=NORMAL)

How can I assign an ID to a view programmatically?

Android id overview

An Android id is an integer commonly used to identify views; this id can be assigned via XML (when possible) and via code (programmatically.) The id is most useful for getting references for XML-defined Views generated by an Inflater (such as by using setContentView.)

Assign id via XML

  • Add an attribute of android:id="@+id/somename" to your view.
  • When your application is built, the android:id will be assigned a unique int for use in code.
  • Reference your android:id's int value in code using "R.id.somename" (effectively a constant.)
  • this int can change from build to build so never copy an id from gen/package.name/R.java, just use "R.id.somename".
  • (Also, an id assigned to a Preference in XML is not used when the Preference generates its View.)

Assign id via code (programmatically)

  • Manually set ids using someView.setId(int);
  • The int must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.)
  • For example, if creating and numbering several views representing items, you could use their item number.

Uniqueness of ids

  • XML-assigned ids will be unique.
  • Code-assigned ids do not have to be unique
  • Code-assigned ids can (theoretically) conflict with XML-assigned ids.
  • These conflicting ids won't matter if queried correctly (keep reading).

When (and why) conflicting ids don't matter

  • findViewById(int) will iterate depth-first recursively through the view hierarchy from the View you specify and return the first View it finds with a matching id.
  • As long as there are no code-assigned ids assigned before an XML-defined id in the hierarchy, findViewById(R.id.somename) will always return the XML-defined View so id'd.

Dynamically Creating Views and Assigning IDs

  • In layout XML, define an empty ViewGroup with id.
  • Such as a LinearLayout with android:id="@+id/placeholder".
  • Use code to populate the placeholder ViewGroup with Views.
  • If you need or want, assign any ids that are convenient to each view.
  • Query these child views using placeholder.findViewById(convenientInt);

  • API 17 introduced View.generateViewId() which allows you to generate a unique ID.

If you choose to keep references to your views around, be sure to instantiate them with getApplicationContext() and be sure to set each reference to null in onDestroy. Apparently leaking the Activity (hanging onto it after is is destroyed) is wasteful.. :)

Reserve an XML android:id for use in code

API 17 introduced View.generateViewId() which generates a unique ID. (Thanks to take-chances-make-changes for pointing this out.)*

If your ViewGroup cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:

Here, values/ids.xml defines a custom id:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="reservedNamedId" type="id"/>
</resources>

Then once the ViewGroup or View has been created, you can attach the custom id

myViewGroup.setId(R.id.reservedNamedId);

Conflicting id example

For clarity by way of obfuscating example, lets examine what happens when there is an id conflict behind the scenes.

layout/mylayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <LinearLayout
        android:id="@+id/placeholder"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
</LinearLayout>

To simulate a conflict, lets say our latest build assigned R.id.placeholder(@+id/placeholder) an int value of 12..

Next, MyActivity.java defines some adds views programmatically (via code):

int placeholderId = R.id.placeholder; // placeholderId==12
// returns *placeholder* which has id==12:
ViewGroup placeholder = (ViewGroup)this.findViewById(placeholderId);
for (int i=0; i<20; i++){
    TextView tv = new TextView(this.getApplicationContext());
    // One new TextView will also be assigned an id==12:
    tv.setId(i);
    placeholder.addView(tv);
}

So placeholder and one of our new TextViews both have an id of 12! But this isn't really a problem if we query placeholder's child views:

// Will return a generated TextView:
 placeholder.findViewById(12);

// Whereas this will return the ViewGroup *placeholder*;
// as long as its R.id remains 12: 
Activity.this.findViewById(12);

*Not so bad

I do not want to inherit the child opacity from the parent in CSS

For other people trying to make a table (or something) look focused on one row using opacity. Like @Blowski said use color not opacity. Check out this fiddle: http://jsfiddle.net/2en6o43d/

.table:hover > .row:not(:hover)

git clone: Authentication failed for <URL>

  1. Go to Control Panel\All Control Panel Items\Credential Manager and select Generic Credentials.
  2. Remove all the credential with your company domain name.
  3. Git clone repository from git bash terminal once again and it will ask for password and username. Insert it again and you are all set!

Why write <script type="text/javascript"> when the mime type is set by the server?

It allows browsers to determine if they can handle the scripting/style language before making a request for the script or stylesheet (or, in the case of embedded script/style, identify which language is being used).

This would be much more important if there had been more competition among languages in browser space, but VBScript never made it beyond IE and PerlScript never made it beyond an IE specific plugin while JSSS was pretty rubbish to begin with.

The draft of HTML5 makes the attribute optional.

.Net picking wrong referenced assembly version

This error was somewhat misleading - I was loading some DLLs that required x64 architecture to be specified. In the .csproj file:

<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release-ABC|AnyCPU'">
    <OutputPath>bin\Release-ABC</OutputPath>
    <PlatformTarget>x64</PlatformTarget>
</PropertyGroup>

A missing PlatformTarget caused this error.

How to get distinct results in hibernate with joins and row-based limiting (paging)?

I will now explain a different solution, where you can use the normal query and pagination method without having the problem of possibly duplicates or suppressed items.

This Solution has the advance that it is:

  • faster than the PK id solution mentioned in this article
  • preserves the Ordering and don’t use the 'in clause' on a possibly large Dataset of PK’s

The complete Article can be found on my blog

Hibernate gives the possibility to define the association fetching method not only at design time but also at runtime by a query execution. So we use this aproach in conjunction with a simple relfection stuff and can also automate the process of changing the query property fetching algorithm only for collection properties.

First we create a method which resolves all collection properties from the Entity Class:

public static List<String> resolveCollectionProperties(Class<?> type) {
  List<String> ret = new ArrayList<String>();
  try {
   BeanInfo beanInfo = Introspector.getBeanInfo(type);
   for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
     if (Collection.class.isAssignableFrom(pd.getPropertyType()))
     ret.add(pd.getName());
   }
  } catch (IntrospectionException e) {
    e.printStackTrace();
  }
  return ret;
}

After doing that you can use this little helper method do advise your criteria object to change the FetchMode to SELECT on that query.

Criteria criteria = …

//    … add your expression here  …

// set fetchmode for every Collection Property to SELECT
for (String property : ReflectUtil.resolveCollectionProperties(YourEntity.class)) {
  criteria.setFetchMode(property, org.hibernate.FetchMode.SELECT);
}
criteria.setFirstResult(firstResult);
criteria.setMaxResults(maxResults);
criteria.list();

Doing that is different from define the FetchMode of your entities at design time. So you can use the normal join association fetching on paging algorithms in you UI, because this is most of the time not the critical part and it is more important to have your results as quick as possible.

How can I sort a dictionary by key?

Python dicts are un-ordered. Usually, this is not a problem since the most common use case is to do a lookup.

The simplest way to do what you want would be to create a collections.OrderedDict inserting the elements in sorted order.

ordered_dict = collections.OrderedDict([(k, d[k]) for k in sorted(d.keys())])

If you need to iterated, as others above have suggested, the simplest way would be to iterate over sorted keys. Examples-

Print values sorted by keys:

# create the dict
d = {k1:v1, k2:v2,...}
# iterate by keys in sorted order
for k in sorted(d.keys()):
    value = d[k]
    # do something with k, value like print
    print k, value

Get list of values sorted by keys:

values = [d[k] for k in sorted(d.keys())]

How do I concatenate const/literal strings in C?

As people pointed out string handling improved much. So you may want to learn how to use the C++ string library instead of C-style strings. However here is a solution in pure C

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

void appendToHello(const char *s) {
    const char *const hello = "hello ";

    const size_t sLength     = strlen(s);
    const size_t helloLength = strlen(hello);
    const size_t totalLength = sLength + helloLength;

    char *const strBuf = malloc(totalLength + 1);
    if (strBuf == NULL) {
        fprintf(stderr, "malloc failed\n");
        exit(EXIT_FAILURE);
    }

    strcpy(strBuf, hello);
    strcpy(strBuf + helloLength, s);

    puts(strBuf);

    free(strBuf);

}

int main (void) {
    appendToHello("blah blah");
    return 0;
}

I am not sure whether it is correct/safe but right now I could not find a better way to do this in ANSI C.

Ignore case in Python strings

For occasional or even repeated comparisons, a few extra string objects shouldn't matter as long as this won't happen in the innermost loop of your core code or you don't have enough data to actually notice the performance impact. See if you do: doing things in a "stupid" way is much less stupid if you also do it less.

If you seriously want to keep comparing lots and lots of text case-insensitively you could somehow keep the lowercase versions of the strings at hand to avoid finalization and re-creation, or normalize the whole data set into lowercase. This of course depends on the size of the data set. If there are a relatively few needles and a large haystack, replacing the needles with compiled regexp objects is one solution. If It's hard to say without seeing a concrete example.

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Your syntax is pretty screwy.

Change this:

input:not(disabled)not:[type="submit"]:focus{

to:

input:not(:disabled):not([type="submit"]):focus{

Seems that many people don't realize :enabled and :disabled are valid CSS selectors...

Full Page <iframe>

Put this in your CSS.

iframe {
  width: 100%;
  height: 100vh;
}

Login to remote site with PHP cURL

This is how I solved this in ImpressPages:

//initial request with login data

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');  //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp');  //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

//another request preserving the session

curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

How do you add an in-app purchase to an iOS application?

I know I am quite late to post this, but I share similar experience when I learned the ropes of IAP model.

In-app purchase is one of the most comprehensive workflow in iOS implemented by Storekit framework. The entire documentation is quite clear if you patience to read it, but is somewhat advanced in nature of technicality.

To summarize:

1 - Request the products - use SKProductRequest & SKProductRequestDelegate classes to issue request for Product IDs and receive them back from your own itunesconnect store.

These SKProducts should be used to populate your store UI which the user can use to buy a specific product.

2 - Issue payment request - use SKPayment & SKPaymentQueue to add payment to the transaction queue.

3 - Monitor transaction queue for status update - use SKPaymentTransactionObserver Protocol's updatedTransactions method to monitor status:

SKPaymentTransactionStatePurchasing - don't do anything
SKPaymentTransactionStatePurchased - unlock product, finish the transaction
SKPaymentTransactionStateFailed - show error, finish the transaction
SKPaymentTransactionStateRestored - unlock product, finish the transaction

4 - Restore button flow - use SKPaymentQueue's restoreCompletedTransactions to accomplish this - step 3 will take care of the rest, along with SKPaymentTransactionObserver's following methods:

paymentQueueRestoreCompletedTransactionsFinished
restoreCompletedTransactionsFailedWithError

Here is a step by step tutorial (authored by me as a result of my own attempts to understand it) that explains it. At the end it also provides code sample that you can directly use.

Here is another one I created to explain certain things that only text could describe in better manner.

Calling stored procedure from another stored procedure SQL Server

First of all, if table2's idProduct is an identity, you cannot insert it explicitly until you set IDENTITY_INSERT on that table

SET IDENTITY_INSERT table2 ON;

before the insert.

So one of two, you modify your second stored and call it with only the parameters productName and productDescription and then get the new ID

EXEC test2 'productName', 'productDescription'
SET @newID = SCOPE_IDENTIY()

or you already have the ID of the product and you don't need to call SCOPE_IDENTITY() and can make the insert on table1 with that ID

What is an uber jar?

According to uber-JAR Documentation Approaches: There are three common methods for constructing an uber-JAR:

Unshaded Unpack all JAR files, then repack them into a single JAR. Tools: Maven Assembly Plugin, Classworlds Uberjar

Shaded Same as unshaded, but rename (i.e., "shade") all packages of all dependencies. Tools: Maven Shade Plugin

JAR of JARs The final JAR file contains the other JAR files embedded within. Tools: Eclipse JAR File Exporter, One-JAR.

Text Progress Bar in the Console

Here's my Python 3 solution:

import time
for i in range(100):
    time.sleep(1)
    s = "{}% Complete".format(i)
    print(s,end=len(s) * '\b')

'\b' is a backslash, for each character in your string. This does not work within the Windows cmd window.

Ruby: How to convert a string to boolean

def true?(obj)
  obj.to_s.downcase == "true"
end

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

I haven't checked (although it wouldn't be hard to), but I think that Stack Exchange sites use the jquery.timeago plugin to create these time strings.


It's quite easy to use the plugin, and it's clean and updates automatically.

Here's a quick sample (from the plugin's home page):

First, load jQuery and the plugin:

<script src="jquery.min.js" type="text/javascript"></script> <script src="jquery.timeago.js" type="text/javascript"></script>

Now, let's attach it to your timestamps on DOM ready:

jQuery(document).ready(function() {
jQuery("abbr.timeago").timeago(); });

This will turn all abbr elements with a class of timeago and an ISO 8601 timestamp in the title: <abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr> into something like this: <abbr class="timeago" title="July 17, 2008">about a year ago</abbr> which yields: about a year ago. As time passes, the timestamps will automatically update.

Can someone explain how to implement the jQuery File Upload plugin?

I also struggled with this but got it working once I figured out how the paths work in UploadHandler.php: upload_dir and upload_url are about the only settings to look at to get it working. Also check your server error logs for debugging information.

How to get the list of all installed color schemes in Vim?

Type

:colorscheme then Space followed by TAB.

or as Peter said,

:colorscheme then Space followed by CTRLd

The short version of the command is :colo so you can use it in the two previous commands, instead of using the "long form".

If you want to find and preview more themes, there are various websites like Vim colors

Creating a segue programmatically

First of, suppose you have two different views in storyboard, and you want to navigate from one screen to another, so follow this steps:

1). Define all your views with class file and also storyboard id in identity inspector.

2). Make sure you add a navigation controller to the first view. Select it in the Storyboard and then Editor >Embed In > Navigation Controller

3). In your first class, import the "secondClass.h"

#import "ViewController.h
#import "secondController.h"

4). Add this command in the IBAction that has to perform the segue

secondController *next=[self.storyboard instantiateViewControllerWithIdentifier:@"second"];
[self.navigationController pushViewController:next animated:YES];

5). @"second" is secondview controller class, storyboard id.

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

Seeing how you draw your canvas with

$("canvas").drawImage();

it seems that you use jQuery Canvas (jCanvas) by Caleb Evans. I actually use that plugin and it has a simple way to retrieve canvas base64 image string with $('canvas').getCanvasImage();

Here's a working Fiddle for you: http://jsfiddle.net/e6nqzxpn/

ERROR: Cannot open source file " "

You need to check your project settings, under C++, check include directories and make sure it points to where GameEngine.h resides, the other issue could be that GameEngine.h is not in your source file folder or in any include directory and resides in a different folder relative to your project folder. For instance you have 2 projects ProjectA and ProjectB, if you are including GameEngine.h in some source/header file in ProjectA then to include it properly, assuming that ProjectB is in the same parent folder do this:

include "../ProjectB/GameEngine.h"

This is if you have a structure like this:

Root\ProjectA

Root\ProjectB <- GameEngine.h actually lives here

CSS change button style after click

It is possible to do with CSS only by selecting active and focus pseudo element of the button.

button:active{
    background:olive;
}

button:focus{
    background:olive;
}

See codepen: http://codepen.io/fennefoss/pen/Bpqdqx

You could also write a simple jQuery click function which changes the background color.

HTML:

<button class="js-click">Click me!</button>

CSS:

button {
  background: none;
}

JavaScript:

  $( ".js-click" ).click(function() {
    $( ".js-click" ).css('background', 'green');
  });

Check out this codepen: http://codepen.io/fennefoss/pen/pRxrVG

What's the difference between REST & RESTful

A service based on REST is called a "RESTful service".

Source I rely on posting that: Dr.Dobbs Archive

The server committed a protocol violation. Section=ResponseStatusLine ERROR

I just had the same issue. In my particular case git was removing CR in a http file on check-in, but disregarding the cause, you can follow these steps for debugging the issue: https://technical.fail/posts/2021-01-26-dotnet-framework-throwing-the-server-committed-a-protocol-violation-section-responsestatusline

SQL: Combine Select count(*) from multiple tables

SELECT 
(select count(*) from foo1 where ID = '00123244552000258')
+
(select count(*) from foo2 where ID = '00123244552000258')
+
(select count(*) from foo3 where ID = '00123244552000258')

This is an easy way.

Determining the last row in a single column

You can do this by going in the reverse way. Starting from the last row in spreadsheet and going up till you get some value. This will work in all the cases even if you have some empty rows in between. Code looks like below:

var iLastRowWithData = lastValue('A');
function lastValue(column) {
  var iLastRow = SpreadsheetApp.getActiveSheet().getMaxRows();
  var aValues = SpreadsheetApp.getActiveSheet().getRange(column + "2:" + column + lastRow).getValues();

  for (; aValues[iLastRow - 1] == "" && iLastRow > 0; iLastRow--) {}
  return iLastRow;
}

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

How is "mvn clean install" different from "mvn install"?

You can call more than one target goal with maven. mvn clean install calls clean first, then install. You have to clean manually, because clean is not a standard target goal and not executed automatically on every install.

clean removes the target folder - it deletes all class files, the java docs, the jars, reports and so on. If you don't clean, then maven will only "do what has to be done", like it won't compile classes when the corresponding source files haven't changed (in brief).

we call it target in ant and goal in maven

Insert multiple values using INSERT INTO (SQL Server 2005)

The syntax you are using is new to SQL Server 2008:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1000,N'test'),(1001,N'test2')

For SQL Server 2005, you will have to use multiple INSERT statements:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1000,N'test')

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1001,N'test2')

One other option is to use UNION ALL:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
SELECT 1000, N'test' UNION ALL
SELECT 1001, N'test2'

How can I convert a Unix timestamp to DateTime and vice versa?

var dt = DateTime.Now; 
var unixTime = ((DateTimeOffset)dt).ToUnixTimeSeconds();

// 1510396991

var dt = DateTimeOffset.FromUnixTimeSeconds(1510396991);

// [11.11.2017 10:43:11 +00:00]

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

The onload will always be trigger, i slove this problem use try catch block.It will throw an exception when you try to get the contentDocument.

iframe.onload = function(){
   var that = $(this)[0];
   try{
        that.contentDocument;
   }
   catch(err){
        //TODO 
   }
}

Where can I find jenkins restful api reference?

Additional Solution: use Restul api wrapper libraries written in Java / python / Ruby - An object oriented wrappers which aim to provide a more conventionally way of controlling a Jenkins server.

For documentation and links: Remote Access API

Form Submit Execute JavaScript Best Practice?

Attach an event handler to the submit event of the form. Make sure it cancels the default action.

Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.

Here is how you would do it in YUI 3:

<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
    YUI().use('event', function (Y) {
        Y.one('form').on('submit', function (e) {
            // Whatever else you want to do goes here
            e.preventDefault();
        });
    });
</script>

Make sure that the server will pick up the slack if the JavaScript fails for any reason.

Provide static IP to docker containers via docker-compose

I was facing some difficulties with an environment variable that is with custom name (not with container name /port convention for KAPACITOR_BASE_URL and KAPACITOR_ALERTS_ENDPOINT). If we give service name in this case it wouldn't resolve the ip as

KAPACITOR_BASE_URL:  http://kapacitor:9092

In above http://[**kapacitor**]:9092 would not resolve to http://172.20.0.2:9092

I resolved the static IPs issues using subnetting configurations.

version: "3.3"

networks:
  frontend:
    ipam:
      config:
        - subnet: 172.20.0.0/24
services:
    db:
        image: postgres:9.4.4
        networks:
            frontend:
                ipv4_address: 172.20.0.5
        ports:
            - "5432:5432"
        volumes:
            - postgres_data:/var/lib/postgresql/data

    redis:
        image: redis:latest
        networks:
            frontend:
                ipv4_address: 172.20.0.6
        ports:
            - "6379"

    influxdb:
        image: influxdb:latest
        ports:
            - "8086:8086"
            - "8083:8083"
        volumes:
            - ../influxdb/influxdb.conf:/etc/influxdb/influxdb.conf
            - ../influxdb/inxdb:/var/lib/influxdb
        networks:
            frontend:
                ipv4_address: 172.20.0.4
        environment:
          INFLUXDB_HTTP_AUTH_ENABLED: "false"
          INFLUXDB_ADMIN_ENABLED: "true"
          INFLUXDB_USERNAME: "db_username"
          INFLUXDB_PASSWORD: "12345678"
          INFLUXDB_DB: db_customers

    kapacitor:
        image: kapacitor:latest
        ports: 
            - "9092:9092"
        networks:
            frontend:
                ipv4_address: 172.20.0.2
        depends_on:
            - influxdb
        volumes:
            - ../kapacitor/kapacitor.conf:/etc/kapacitor/kapacitor.conf
            - ../kapacitor/kapdb:/var/lib/kapacitor
        environment:
          KAPACITOR_INFLUXDB_0_URLS_0: http://influxdb:8086

    web:
        build: .
        environment:
          RAILS_ENV: $RAILS_ENV
        command: bundle exec rails s -b 0.0.0.0
        ports:
            - "3000:3000"
        networks:
            frontend:
                ipv4_address: 172.20.0.3
        links:
            - db
            - kapacitor
        depends_on:
            - db
        volumes:
            - .:/var/app/current
        environment:
          DATABASE_URL: postgres://postgres@db
          DATABASE_USERNAME: postgres
          DATABASE_PASSWORD: postgres
          INFLUX_URL: http://influxdb:8086
          INFLUX_USER: db_username
          INFLUX_PWD: 12345678
          KAPACITOR_BASE_URL:  http://172.20.0.2:9092
          KAPACITOR_ALERTS_ENDPOINT: http://172.20.0.3:3000

volumes:
  postgres_data:

Multiple values in single-value context

How about this way?

package main

import (
    "fmt"
    "errors"
)

type Item struct {
    Value int
    Name string
}

var items []Item = []Item{{Value:0, Name:"zero"}, 
                        {Value:1, Name:"one"}, 
                        {Value:2, Name:"two"}}

func main() {
    var err error
    v := Get(3, &err).Value
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(v)

}

func Get(value int, err *error) Item {
    if value > (len(items) - 1) {
        *err = errors.New("error")
        return Item{}
    } else {
        return items[value]
    }
}

How to define optional methods in Swift protocol?

Put the @optional in front of methods or properties.

How to access component methods from “outside” in ReactJS?

If you want to call functions on components from outside React, you can call them on the return value of renderComponent:

var Child = React.createClass({…});
var myChild = React.renderComponent(Child);
myChild.someMethod();

The only way to get a handle to a React Component instance outside of React is by storing the return value of React.renderComponent. Source.

How to destroy Fragment?

Give a try to this

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    // TODO Auto-generated method stub

    FragmentManager manager = ((Fragment) object).getFragmentManager();
    FragmentTransaction trans = manager.beginTransaction();
    trans.remove((Fragment) object);
    trans.commit();

    super.destroyItem(container, position, object);
}

Reimport a module in python while interactive

Actually, in Python 3 the module imp is marked as DEPRECATED. Well, at least that's true for 3.4.

Instead the reload function from the importlib module should be used:

https://docs.python.org/3/library/importlib.html#importlib.reload

But be aware that this library had some API-changes with the last two minor versions.