Programs & Examples On #Watcom

An Open Source C/C++ and ForTran development environment for multiple 16- and 32-bit x86 targets.

PHP removing a character in a string

$str = preg_replace('/\?\//', '?', $str);

Edit: See CMS' answer. It's late, I should know better.

Checking length of dictionary object

var c = {'a':'A', 'b':'B', 'c':'C'};
var count = 0;
for (var i in c) {
   if (c.hasOwnProperty(i)) count++;
}

alert(count);

Attempted to read or write protected memory

The problem may be due to mixed build platforms DLLs in the project. i.e You build your project to Any CPU but have some DLLs in the project already built for x86 platform. These will cause random crashes because of different memory mapping of 32bit and 64bit architecture. If all the DLLs are built for one platform the problem can be solved. For safety try bulinding for 32bit x86 architecture because it is the most compatible.

Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?

Just for others (like me) who might have faced the above error. The solution in simple terms.

You might have missed to register your Interface and class (which implements that inteface) registration in your code.

e.g if the error is
"The current type, xyznamespace. Imyinterfacename, is an interface and cannot be constructed. Are you missing a type mapping?"

Then you must register the class which implements the Imyinterfacename in the UnityConfig class in the Register method. using code like below

 container.RegisterType<Imyinterfacename, myinterfaceimplclassname>();

best way to get folder and file list in Javascript

In my project I use this function for getting huge amount of files. It's pretty fast (put require("FS") out to make it even faster):

var _getAllFilesFromFolder = function(dir) {

    var filesystem = require("fs");
    var results = [];

    filesystem.readdirSync(dir).forEach(function(file) {

        file = dir+'/'+file;
        var stat = filesystem.statSync(file);

        if (stat && stat.isDirectory()) {
            results = results.concat(_getAllFilesFromFolder(file))
        } else results.push(file);

    });

    return results;

};

usage is clear:

_getAllFilesFromFolder(__dirname + "folder");

Custom toast on Android: a simple example

A toast is for showing messages for short intervals of time; So, as per my understanding, you would like to customize it with adding an image to it and changing size, color of the message text. If that is all, you want to do, then there is no need to make a separate layout and inflate it to the Toast instance.

The default Toast's view contains a TextView for showing messages on it. So, if we have the resource id reference of that TextView, we can play with it. So below is what can you do to achieve this:

Toast toast = Toast.makeText(this, "I am custom Toast!", Toast.LENGTH_LONG);
View toastView = toast.getView(); // This'll return the default View of the Toast.

/* And now you can get the TextView of the default View of the Toast. */
TextView toastMessage = (TextView) toastView.findViewById(android.R.id.message);
toastMessage.setTextSize(25);
toastMessage.setTextColor(Color.RED);
toastMessage.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_fly, 0, 0, 0);
toastMessage.setGravity(Gravity.CENTER);
toastMessage.setCompoundDrawablePadding(16);
toastView.setBackgroundColor(Color.CYAN);
toast.show();

In above code you can see, you can add image to TextView via setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom) whichever position relative to TextView you want to.

Update:

Have written a builder class to simplify the above purpose; Here is the link: https://gist.github.com/TheLittleNaruto/6fc8f6a2b0d0583a240bd78313ba83bc

Check the HowToUse.kt in above link.

Output:

Enter image description here

AppSettings get value from .config file

Some of the Answers seems a little bit off IMO Here is my take circa 2016

<add key="ClientsFilePath" value="filepath"/>

Make sure System.Configuration is referenced.

Question is asking for value of an appsettings key

Which most certainly SHOULD be

  string yourKeyValue = ConfigurationManager.AppSettings["ClientsFilePath"]

  //yourKeyValue should hold on the HEAP  "filepath"

Here is a twist in which you can group together values ( not for this question)

var emails = ConfigurationManager.AppSettings[ConfigurationManager.AppSettings["Environment"] + "_Emails"];

emails will be value of Environment Key + "_Emails"

example :   [email protected];[email protected];

'NoneType' object is not subscriptable?

The print() function returns None. You are trying to index None. You can not, because 'NoneType' object is not subscriptable.

Put the [0] inside the brackets. Now you're printing everything, and not just the first term.

Convert .cer certificate to .jks

Export a certificate from a keystore:

keytool -export -alias mydomain -file mydomain.crt -keystore keystore.jks

how to print float value upto 2 decimal place without rounding off

i'd suggest shorter and faster approach:

printf("%.2f", ((signed long)(fVal * 100) * 0.01f));

this way you won't overflow int, plus multiplication by 100 shouldn't influence the significand/mantissa itself, because the only thing that really is changing is exponent.

How to install requests module in Python 3.4, instead of 2.7

You can specify a Python version for pip to use:

pip3.4 install requests

Python 3.4 has pip support built-in, so you can also use:

python3.4 -m pip install

If you're running Ubuntu (or probably Debian as well), you'll need to install the system pip3 separately:

sudo apt-get install python3-pip

This will install the pip3 executable, so you can use it, as well as the earlier mentioned python3.4 -m pip:

pip3 install requests

Database Diagram Support Objects cannot be Installed ... no valid owner

This fixed it for me. It sets the owner found under the 'files' section of the database properties window, and is as scripted by management studio.

USE [your_db_name]
GO
EXEC dbo.sp_changedbowner @loginame = N'sa', @map = false
GO

According to the sp_changedbowner documentation this is deprecated now.

Based on Israel's answer. Aaron's answer is the non-deprecated variation of this.

Random color generator

I think the first response is the most succinct/useful, but I just wrote one that would probably be easier for a beginner to understand.

function randomHexColor(){
    var hexColor=[]; //new Array()
    hexColor[0] = "#"; //first value of array needs to be hash tag for hex color val, could also prepend this later

    for (i = 1; i < 7; i++)
    {
        var x = Math.floor((Math.random()*16)); //Tricky: Hex has 16 numbers, but 0 is one of them

        if (x >=10 && x <= 15) //hex:0123456789ABCDEF, this takes care of last 6 
        {
            switch(x)
            {
                case 10: x="a" 
                break;
                case 11: x="b" 
                break;
                case 12: x="c" 
                break;
                case 13: x="d" 
                break;
                case 14: x="e" 
                break;
                case 15: x="f" 
                break;  
            }
        }
        hexColor[i] = x;
    }
    var cString = hexColor.join(""); //this argument for join method ensures there will be no separation with a comma
    return cString;
}

How to search a Git repository by commit message?

first to list the commits use

git log --oneline

then find the SHA of the commit (Message), then I used

 git log --stat 8zad24d

(8zad24d) is the SHA assosiated with the commit you are intrested in (the first couples sha example (8zad24d) you can select 4 char or 6 or 8 or the entire sha) to find the right info

Create 3D array using Python

You should use a list comprehension:

>>> import pprint
>>> n = 3
>>> distance = [[[0 for k in xrange(n)] for j in xrange(n)] for i in xrange(n)]
>>> pprint.pprint(distance)
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
>>> distance[0][1]
[0, 0, 0]
>>> distance[0][1][2]
0

You could have produced a data structure with a statement that looked like the one you tried, but it would have had side effects since the inner lists are copy-by-reference:

>>> distance=[[[0]*n]*n]*n
>>> pprint.pprint(distance)
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
 [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
>>> distance[0][0][0] = 1
>>> pprint.pprint(distance)
[[[1, 0, 0], [1, 0, 0], [1, 0, 0]],
 [[1, 0, 0], [1, 0, 0], [1, 0, 0]],
 [[1, 0, 0], [1, 0, 0], [1, 0, 0]]]

How to send PUT, DELETE HTTP request in HttpURLConnection?

For doing a PUT in HTML correctly, you will have to surround it with try/catch:

try {
    url = new URL("http://www.example.com/resource");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);
    httpCon.setRequestMethod("PUT");
    OutputStreamWriter out = new OutputStreamWriter(
        httpCon.getOutputStream());
    out.write("Resource content");
    out.close();
    httpCon.getInputStream();
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (ProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

Change background colour for Visual Studio

File-> Preferences-> Settings.

Find workbench.colorCustomizations object, change its editor.background property and save (you will see the results immediately — no need to restart vs code). Or you just can copy my current config file vs code config gist.

How to empty a redis database?

You have two options:

  • FLUSHDB - clears currently active database
  • FLUSHALL - clears all the existing databases

How to validate an e-mail address in swift?

In Swift 4.2 and Xcode 10.1

//Email validation
func isValidEmail(email: String) -> Bool {
    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
    var valid = NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: email)
    if valid {
        valid = !email.contains("Invalid email id")
    }
    return valid
}

//Use like this....
let emailTrimmedString = emailTF.text?.trimmingCharacters(in: .whitespaces)
if isValidEmail(email: emailTrimmedString!) == false {
   SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter valid email")
}

If you want to use SharedClass.

//This is SharedClass
import UIKit
class SharedClass: NSObject {

static let sharedInstance = SharedClass()

//Email validation
func isValidEmail(email: String) -> Bool {
    let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
    var valid = NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: email)
    if valid {
        valid = !email.contains("Invalid email id")
    }
    return valid
}

private override init() {

}
}

And call function like this....

if SharedClass.sharedInstance. isValidEmail(email: emailTrimmedString!) == false {
   SharedClass.sharedInstance.alert(view: self, title: "", message: "Please enter correct email")
   //Your code here
} else {
   //Code here
}

How do I add the contents of an iterable to a set?

Just a quick update, timings using python 3:

#!/usr/local/bin python3
from timeit import Timer

a = set(range(1, 100000))
b = list(range(50000, 150000))

def one_by_one(s, l):
    for i in l:
        s.add(i)    

def cast_to_list_and_back(s, l):
    s = set(list(s) + l)

def update_set(s,l):
    s.update(l)

results are:

one_by_one 10.184448844986036
cast_to_list_and_back 7.969255169969983
update_set 2.212590195937082

Execute php file from another php

This came across while working on a project on linux platform.

exec('wget http://<url to the php script>)

This runs as if you run the script from browser.

Hope this helps!!

How can I remove item from querystring in asp.net using c#?

  1. Gather your query string by using HttpContext.Request.QueryString. It defaults as a NameValueCollection type.
  2. Cast it as a string and use System.Web.HttpUtility.ParseQueryString() to parse the query string (which returns a NameValueCollection again).
  3. You can then use the Remove() function to remove the specific parameter (using the key to reference that parameter to remove).
  4. Use case the query parameters back to a string and use string.Join() to format the query string as something readable by your URL as valid query parameters.

See below for a working example, where param_to_remove is the parameter you want to remove.

Let's say your query parameters are param1=1&param_to_remove=stuff&param2=2. Run the following lines:

var queryParams = System.Web.HttpUtility.ParseQueryString(HttpContext.Request.QueryString.ToString());
queryParams.Remove("param_to_remove");
string queryString = string.Join("&", queryParams.Cast<string>().Select(e => e + "=" + queryParams[e]));

Now your query string should be param1=1&param2=2.

Chrome, Javascript, window.open in new tab

It is sometimes useful to force the use of a tab, if the user likes that. As Prakash stated above, this is sometimes dictated by the use of a non-user-initiated event, but there are ways around that.

For example:

$("#theButton").button().click( function(event) {
   $.post( url, data )
   .always( function( response ) {
      window.open( newurl + response, '_blank' );
   } );
} );

will always open "newurl" in a new browser window since the "always" function is not considered user-initiated. However, if we do this:

$("#theButton").button().click( function(event) {
   var newtab = window.open( '', '_blank' );
   $.post( url, data )
   .always( function( response ) {
      newtab.location = newurl + response;
   } );
} );

we open the new browser window or create the new tab, as determined by the user preference in the button click which IS user-initiated. Then we just set the location to the desired URL after returning from the AJAX post. Voila, we force the use of a tab if the user likes that.

Conversion from List<T> to array T[]

Try using

MyClass[] myArray = list.ToArray();

Can I force a UITableView to hide the separator between empty cells?

I use the following:

UIView *view = [[UIView alloc] init];
myTableView.tableFooterView = view;
[view release];

Doing it in viewDidLoad. But you can set it anywhere.

How to get file_get_contents() to work with HTTPS?

This is probably due to your target server not having a valid SSL certificate.

Combine :after with :hover

Just append :after to your #alertlist li:hover selector the same way you do with your #alertlist li.selected selector:

#alertlist li.selected:after, #alertlist li:hover:after
{
    position:absolute;
    top: 0;
    right:-10px;
    bottom:0;

    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid #303030;
    content: "";
}

psql: FATAL: Ident authentication failed for user "postgres"

If you are using it on CentOS,you may need to reload postgres after making the above solutions:

systemctl restart postgresql-9.3.service

Refresh Page and Keep Scroll Position

document.location.reload() stores the position, see in the docs.

Add additional true parameter to force reload, but without restoring the position.

document.location.reload(true)

MDN docs:

The forcedReload flag changes how some browsers handle the user's scroll position. Usually reload() restores the scroll position afterward, but forced mode can scroll back to the top of the page, as if window.scrollY === 0.

How to get the list of properties of a class?

Here is improved @lucasjones answer. I included improvements mentioned in comment section after his answer. I hope someone will find this useful.

public static string[] GetTypePropertyNames(object classObject,  BindingFlags bindingFlags)
{
    if (classObject == null)
    {
        throw new ArgumentNullException(nameof(classObject));
    }

        var type = classObject.GetType();
        var propertyInfos = type.GetProperties(bindingFlags);

        return propertyInfos.Select(propertyInfo => propertyInfo.Name).ToArray();
 }

Merging dataframes on index with pandas

You can do this with merge:

df_merged = df1.merge(df2, how='outer', left_index=True, right_index=True)

The keyword argument how='outer' keeps all indices from both frames, filling in missing indices with NaN. The left_index and right_index keyword arguments have the merge be done on the indices. If you get all NaN in a column after doing a merge, another troubleshooting step is to verify that your indices have the same dtypes.

The merge code above produces the following output for me:

                V1    V2
A 2012-01-01  12.0  15.0
  2012-02-01  14.0   NaN
  2012-03-01   NaN  21.0
B 2012-01-01  15.0  24.0
  2012-02-01   8.0   9.0
C 2012-01-01  17.0   NaN
  2012-02-01   9.0   NaN
D 2012-01-01   NaN   7.0
  2012-02-01   NaN  16.0

Get value of multiselect box using jQuery or pure JS

According to the widget's page, it should be:

var myDropDownListValues = $("#myDropDownList").multiselect("getChecked").map(function()
{
    return this.value;    
}).get();

It works for me :)

Get the cartesian product of a series of lists?

with itertools.product:

import itertools
result = list(itertools.product(*somelists))

How to completely hide the navigation bar in iPhone / HTML5

Try the following:

  1. Add this meta tag in the head of your HTML file:

    <meta name="apple-mobile-web-app-capable" content="yes" />
    
  2. Open your site with Safari on iPhone, and use the bookmark feature to add your site to the home screen.

  3. Go back to home screen and open the bookmarked site. The URL and status bar will be gone.

As long as you only need to work with the iPhone, you should be fine with this solution.

In addition, your sample on the warnerbros.com site uses the Sencha touch framework. You can Google it for more information or check out their demos.

When restoring a backup, how do I disconnect all active connections?

I prefer to do like this,

alter database set offline with rollback immediate

and then restore your database. after that,

alter database set online with rollback immediate

How to iterate over the files of a certain directory, in Java?

Here is an example that lists all the files on my desktop. you should change the path variable to your path.

Instead of printing the file's name with System.out.println, you should place your own code to operate on the file.

public static void main(String[] args) {
    File path = new File("c:/documents and settings/Zachary/desktop");

    File [] files = path.listFiles();
    for (int i = 0; i < files.length; i++){
        if (files[i].isFile()){ //this line weeds out other directories/folders
            System.out.println(files[i]);
        }
    }
}

How to copy commits from one branch to another?

Suppose I have committed changes to master branch.I will get the commit id(xyz) of the commit now i have to go to branch for which i need to push my commits.

Single commit id xyx

git checkout branch-name
git cherry-pick xyz
git push origin branch-name

Multiple commit id's xyz abc qwe

git checkout branch-name
git cherry-pick xyz abc qwe
git push origin branch-name

How to access the request body when POSTing using Node.js and Express?

I'm absolutely new to JS and ES, but what seems to work for me is just this:

JSON.stringify(req.body)

Let me know if there's anything wrong with it!

How do I check whether input string contains any spaces?

if (str.indexOf(' ') >= 0)

would be (slightly) faster.

C-like structures in Python

You can use a tuple for a lot of things where you would use a struct in C (something like x,y coordinates or RGB colors for example).

For everything else you can use dictionary, or a utility class like this one:

>>> class Bunch:
...     def __init__(self, **kwds):
...         self.__dict__.update(kwds)
...
>>> mystruct = Bunch(field1=value1, field2=value2)

I think the "definitive" discussion is here, in the published version of the Python Cookbook.

How to check if a Ruby object is a Boolean

I find this to be concise and self-documenting:

[true, false].include? foo

If using Rails or ActiveSupport, you can even do a direct query using in?

foo.in? [true, false]

Checking against all possible values isn't something I'd recommend for floats, but feasible when there are only two possible values!

ADB.exe is obsolete and has serious performance problems

In my case what removed this message was (After updating everything) deleting the emulator and creating a new one. Manually updating the adb didn't solved this for. Nor updating via the Android studio Gui. In my case it seems that since the emulator was created with "old" components it keep showing the message. I had three emulators, just deleted them all and created a new one. For my surprise when it started the message was no more.

Cannot tell if performance is better or not. The message just didn't came up. Also I have everything updated to the latest (emulators and sdk).

How to add a custom HTTP header to every WCF call?

A bit late to the party but Juval Lowy addresses this exact scenario in his book and the associated ServiceModelEx library.

Basically he defines ClientBase and ChannelFactory specialisations that allow specifying type-safe header values. I suggesst downloading the source and looking at the HeaderClientBase and HeaderChannelFactory classes.

John

Use and meaning of "in" in an if statement?

Maybe these examples will help illustrate what in does. It basically translate to Is this item in this other item?

listOfNums = [ 1, 2, 3, 4, 5, 6, 45, 'j' ]

>>> 3 in listOfNums:
>>> True

>>> 'j' in listOfNums:
>>> True

>>> 66 in listOfNums:
>>> False

Connecting client to server using Socket.io

Have you tried loading the socket.io script not from a relative URL?

You're using:

<script src="socket.io/socket.io.js"></script>

And:

socket.connect('http://127.0.0.1:8080');

You should try:

<script src="http://localhost:8080/socket.io/socket.io.js"></script>

And:

socket.connect('http://localhost:8080');

Switch localhost:8080 with whatever fits your current setup.

Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).

How do you clear a stringstream variable?

You can clear the error state and empty the stringstream all in one line

std::stringstream().swap(m); // swap m with a default constructed stringstream

This effectively resets m to a default constructed state

How can I exclude one word with grep?

The right solution is to use grep -v "word" file, with its awk equivalent:

awk '!/word/' file

However, if you happen to have a more complex situation in which you want, say, XXX to appear and YYY not to appear, then awk comes handy instead of piping several greps:

awk '/XXX/ && !/YYY/' file
#    ^^^^^    ^^^^^^
# I want it      |
#            I don't want it

You can even say something more complex. For example: I want those lines containing either XXX or YYY, but not ZZZ:

awk '(/XXX/ || /YYY/) && !/ZZZ/' file

etc.

Pytorch tensor to numpy array

There are 4 dimensions of the tensor you want to convert.

[:, ::-1, :, :] 

: means that the first dimension should be copied as it is and converted, same goes for the third and fourth dimension.

::-1 means that for the second axes it reverses the the axes

Pandas create empty DataFrame with only column names

Creating colnames with iterating

df = pd.DataFrame(columns=['colname_' + str(i) for i in range(5)])
print(df)

# Empty DataFrame
# Columns: [colname_0, colname_1, colname_2, colname_3, colname_4]
# Index: []

to_html() operations

print(df.to_html())

# <table border="1" class="dataframe">
#   <thead>
#     <tr style="text-align: right;">
#       <th></th>
#       <th>colname_0</th>
#       <th>colname_1</th>
#       <th>colname_2</th>
#       <th>colname_3</th>
#       <th>colname_4</th>
#     </tr>
#   </thead>
#   <tbody>
#   </tbody>
# </table>

this seems working

print(type(df.to_html()))
# <class 'str'>

The problem is caused by

when you create df like this

df = pd.DataFrame(columns=COLUMN_NAMES)

it has 0 rows × n columns, you need to create at least one row index by

df = pd.DataFrame(columns=COLUMN_NAMES, index=[0])

now it has 1 rows × n columns. You are be able to add data. Otherwise its df that only consist colnames object(like a string list).

Java finished with non-zero exit value 2 - Android Gradle

Just in case if someone still struggling with this and have no clue why is this happening and how to fix. In fact this error

Error:Execution failed for task ':app:dexDebug'. > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdkx.x.x_xx\bin\java.exe'' finished with non-zero exit value 2

can have many reasons to happen but certainly not something related to your JDK version so don't wast your time in wrong direction. These are two main reasons for this to happen

  1. You have same library or jar file included several places and some of them conflicting with each other.
  2. You are about to or already exceeded 65k method limit

First case can be fixed as follows: Find out which dependencies you have included multiple times. In order to do this run following command in android studio terminal

gradlew -q dependencies yourProjectName_usually_app:dependencies --configuration compile

this will return all the dependencies but jar files that you include from lib folder try to get rid of duplication marked with asterisk (*), this is not always possible but in some cases you still can do it, after this try to exclude modules that are included many times, you can do it like this

compile ('com.facebook.android:facebook-android-sdk:4.0.1'){
    exclude module: 'support-v4'
}

For the second case when you exceeding method limit suggestion is to try to minimize it by removing included libraries (note sounds like first solution) if no way to do it add multiDexEnabled true to your defaultConfig

defaultConfig {
   ...
   ...
   multiDexEnabled true
}

this increases method limit but it is not the best thing to do because of possible performance issues IMPORTANT adding only multiDexEnabled true to defaultConfig is not enough in fact on all devices running android <5 Lollipop it will result in unexpected behavior and NoClassDefFoundError. how to solve it is described here

Clear variable in python

Do you want to delete a variable, don't you?

ok, I think I've got a best alternative idea to @bnaul's answer:

You can delete individual names with del:

del x

or you can remove them from the globals() object:

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.

Modules you've imported (like import os) are going to remain imported because they are referenced by sys.modules; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.

SSH configuration: override the default username

If you only want to ssh a few times, such as on a borrowed or shared computer, try:

ssh buck@hostname

or

ssh -l buck hostname

How to download an entire directory and subdirectories using wget?

You may use this in shell:

wget -r --no-parent http://abc.tamu.edu/projects/tzivi/repository/revisions/2/raw/tzivi/

The Parameters are:

-r     //recursive Download

and

--no-parent // Don´t download something from the parent directory

If you don't want to download the entire content, you may use:

-l1 just download the directory (tzivi in your case)

-l2 download the directory and all level 1 subfolders ('tzivi/something' but not 'tivizi/somthing/foo')  

And so on. If you insert no -l option, wget will use -l 5 automatically.

If you insert a -l 0 you´ll download the whole Internet, because wget will follow every link it finds.

How to get the row number from a datatable?

ArrayList check = new ArrayList();            

for (int i = 0; i < oDS.Tables[0].Rows.Count; i++)
{
    int iValue = Convert.ToInt32(oDS.Tables[0].Rows[i][3].ToString());
    check.Add(iValue);

}

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

//set CLASSPATH=%CLASSPATH%;activation.jar;mail.jar
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class Mail
{
    String  d_email = "[email protected]",
            d_password = "****",
            d_host = "smtp.gmail.com",
            d_port  = "465",
            m_to = "[email protected]",
            m_subject = "Testing",
            m_text = "Hey, this is the testing email using smtp.gmail.com.";
    public static void main(String[] args)
    {
        String[] to={"[email protected]"};
        String[] cc={"[email protected]"};
        String[] bcc={"[email protected]"};
        //This is for google
        Mail.sendMail("[email protected]", "password", "smtp.gmail.com", 
                      "465", "true", "true", 
                      true, "javax.net.ssl.SSLSocketFactory", "false", 
                      to, cc, bcc, 
                      "hi baba don't send virus mails..", 
                      "This is my style...of reply..If u send virus mails..");
    }

    public synchronized static boolean sendMail(
        String userName, String passWord, String host, 
        String port, String starttls, String auth, 
        boolean debug, String socketFactoryClass, String fallback, 
        String[] to, String[] cc, String[] bcc, 
        String subject, String text) 
    {
        Properties props = new Properties();
        //Properties props=System.getProperties();
        props.put("mail.smtp.user", userName);
        props.put("mail.smtp.host", host);
        if(!"".equals(port))
            props.put("mail.smtp.port", port);
        if(!"".equals(starttls))
            props.put("mail.smtp.starttls.enable",starttls);
        props.put("mail.smtp.auth", auth);
        if(debug) {
            props.put("mail.smtp.debug", "true");
        } else {
            props.put("mail.smtp.debug", "false");         
        }
        if(!"".equals(port))
            props.put("mail.smtp.socketFactory.port", port);
        if(!"".equals(socketFactoryClass))
            props.put("mail.smtp.socketFactory.class",socketFactoryClass);
        if(!"".equals(fallback))
            props.put("mail.smtp.socketFactory.fallback", fallback);

        try
        {
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);
            MimeMessage msg = new MimeMessage(session);
            msg.setText(text);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress("[email protected]"));
            for(int i=0;i<to.length;i++) {
                msg.addRecipient(Message.RecipientType.TO, 
                                 new InternetAddress(to[i]));
            }
            for(int i=0;i<cc.length;i++) {
                msg.addRecipient(Message.RecipientType.CC, 
                                 new InternetAddress(cc[i]));
            }
            for(int i=0;i<bcc.length;i++) {
                msg.addRecipient(Message.RecipientType.BCC, 
                                 new InternetAddress(bcc[i]));
            }
            msg.saveChanges();
            Transport transport = session.getTransport("smtp");
            transport.connect(host, userName, passWord);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
            return true;
        }
        catch (Exception mex)
        {
            mex.printStackTrace();
            return false;
        }
    }

}

Replacing characters in Ant property

Here is the solution without scripting and no external jars like ant-conrib:

The trick is to use ANT's resources:

  • There is one resource type called "propertyresource" which is like a source file, but provides an stream from the string value of this resource. So you can load it and use it in any task like "copy" that accepts files
  • There is also the task "loadresource" that can load any resource to a property (e.g., a file), but this one could also load our propertyresource. This task allows for filtering the input by applying some token transformations. Finally the following will do what you want:
<loadresource property="propB">
  <propertyresource name="propA"/>
  <filterchain>
    <tokenfilter>
      <filetokenizer/>
      <replacestring from=" " to="_"/>
    </tokenfilter>
  </filterchain>
</loadresource>

This one will replace all " " in propA by "_" and place the result in propB. "filetokenizer" treats the whole input stream (our property) as one token and appies the string replacement on it.

You can do other fancy transformations using other tokenfilters: http://ant.apache.org/manual/Types/filterchain.html

Get an image extension from an uploaded file in Laravel

Yet another way to do it:

//Where $file is an instance of Illuminate\Http\UploadFile
$extension = $file->getClientOriginalExtension();

Extract Number from String in Python

Your regex looks correct. Are you sure you haven't made a mistake with the variable names? In your code above you mixup total_hotel_reviews_string and str.

>>> import re
>>> s = "3158 reviews"
>>> 
>>> print(re.findall("\d+", s))
['3158']

SQL Server equivalent of MySQL's NOW()?

getdate() or getutcdate().

How do you use the "WITH" clause in MySQL?

'Common Table Expression' feature is not available in MySQL, so you have to go to make a view or temporary table to solve, here I have used a temporary table.

The stored procedure mentioned here will solve your need. If I want to get all my team members and their associated members, this stored procedure will help:

----------------------------------
user_id   |   team_id
----------------------------------
admin     |   NULL
ramu      |   admin
suresh    |   admin
kumar     |   ramu
mahesh    |   ramu
randiv    |   suresh
-----------------------------------

Code:

DROP PROCEDURE `user_hier`//
CREATE DEFINER=`root`@`localhost` PROCEDURE `user_hier`(in team_id varchar(50))
BEGIN
declare count int;
declare tmp_team_id varchar(50);
CREATE TEMPORARY TABLE res_hier(user_id varchar(50),team_id varchar(50))engine=memory;
CREATE TEMPORARY TABLE tmp_hier(user_id varchar(50),team_id varchar(50))engine=memory;
set tmp_team_id = team_id;
SELECT COUNT(*) INTO count FROM user_table WHERE user_table.team_id=tmp_team_id;
WHILE count>0 DO
insert into res_hier select user_table.user_id,user_table.team_id from user_table where user_table.team_id=tmp_team_id;
insert into tmp_hier select user_table.user_id,user_table.team_id from user_table where user_table.team_id=tmp_team_id;
select user_id into tmp_team_id from tmp_hier limit 0,1;
select count(*) into count from tmp_hier;
delete from tmp_hier where user_id=tmp_team_id;
end while;
select * from res_hier;
drop temporary table if exists res_hier;
drop temporary table if exists tmp_hier;
end

This can be called using:

mysql>call user_hier ('admin')//

os.walk without digging into directories below

The suggestion to use listdir is a good one. The direct answer to your question in Python 2 is root, dirs, files = os.walk(dir_name).next().

The equivalent Python 3 syntax is root, dirs, files = next(os.walk(dir_name))

Oracle listener not running and won't start

In my Windows case the listener would not start, and 'lsnrctl start' would hang forever. The solution was to kill all processes of extproc. I suspect it had something funny to do with my vpn

Objective-C for Windows

Expanding on the two previous answers, if you just want Objective-C but not any of the Cocoa frameworks, then gcc will work on any platform. You can use it through Cygwin or get MinGW. However, if you want the Cocoa frameworks, or at least a reasonable subset of them, then GNUStep and Cocotron are your best bets.

Cocotron implements a lot of stuff that GNUStep does not, such as CoreGraphics and CoreData, though I can't vouch for how complete their implementation is on a specific framework. Their aim is to keep Cocotron up to date with the latest version of OS X so that any viable OS X program can run on Windows. Because GNUStep typically uses the latest version of gcc, they also add in support for Objective-C++ and a lot of the Objective-C 2.0 features.

I haven't tested those features with GNUStep, but if you use a sufficiently new version of gcc, you might be able to use them. I was not able to use Objective-C++ with GNUStep a few years ago. However, GNUStep does compile from just about any platform. Cocotron is a very mac-centric project. Although it is probably possible to compile it on other platforms, it comes XCode project files, not makefiles, so you can only compile its frameworks out of the box on OS X. It also comes with instructions on compiling Windows apps on XCode, but not any other platform. Basically, it's probably possible to set up a Windows development environment for Cocotron, but it's not as easy as setting one up for GNUStep, and you'll be on your own, so GNUStep is definitely the way to go if you're developing on Windows as opposed to just for Windows.

For what it's worth, Cocotron is licensed under the MIT license, and GNUStep is licensed under the LGPL.

Java method to swap primitives

I think this is the closest you can get to a simple swap, but it does not have a straightforward usage pattern:

int swap(int a, int b) {  // usage: y = swap(x, x=y);
   return a;
}

y = swap(x, x=y);

It relies on the fact that x will pass into swap before y is assigned to x, then x is returned and assigned to y.

You can make it generic and swap any number of objects of the same type:

<T> T swap(T... args) {   // usage: z = swap(a, a=b, b=c, ... y=z);
    return args[0];
}

c = swap(a, a=b, b=c)

How can I generate random alphanumeric strings?

Just some performance comparisons of the various answers in this thread:

Methods & Setup

// what's available
public static string possibleChars = "abcdefghijklmnopqrstuvwxyz";
// optimized (?) what's available
public static char[] possibleCharsArray = possibleChars.ToCharArray();
// optimized (precalculated) count
public static int possibleCharsAvailable = possibleChars.Length;
// shared randomization thingy
public static Random random = new Random();


// http://stackoverflow.com/a/1344242/1037948
public string LinqIsTheNewBlack(int num) {
    return new string(
    Enumerable.Repeat(possibleCharsArray, num)
              .Select(s => s[random.Next(s.Length)])
              .ToArray());
}

// http://stackoverflow.com/a/1344258/1037948
public string ForLoop(int num) {
    var result = new char[num];
    while(num-- > 0) {
        result[num] = possibleCharsArray[random.Next(possibleCharsAvailable)];
    }
    return new string(result);
}

public string ForLoopNonOptimized(int num) {
    var result = new char[num];
    while(num-- > 0) {
        result[num] = possibleChars[random.Next(possibleChars.Length)];
    }
    return new string(result);
}

public string Repeat(int num) {
    return new string(new char[num].Select(o => possibleCharsArray[random.Next(possibleCharsAvailable)]).ToArray());
}

// http://stackoverflow.com/a/1518495/1037948
public string GenerateRandomString(int num) {
  var rBytes = new byte[num];
  random.NextBytes(rBytes);
  var rName = new char[num];
  while(num-- > 0)
    rName[num] = possibleCharsArray[rBytes[num] % possibleCharsAvailable];
  return new string(rName);
}

//SecureFastRandom - or SolidSwiftRandom
static string GenerateRandomString(int Length) //Configurable output string length
{
    byte[] rBytes = new byte[Length]; 
    char[] rName = new char[Length];
    SolidSwiftRandom.GetNextBytesWithMax(rBytes, biasZone);
    for (var i = 0; i < Length; i++)
    {
        rName[i] = charSet[rBytes[i] % charSet.Length];
    }
    return new string(rName);
}

Results

Tested in LinqPad. For string size of 10, generates:

  • from Linq = chdgmevhcy [10]
  • from Loop = gtnoaryhxr [10]
  • from Select = rsndbztyby [10]
  • from GenerateRandomString = owyefjjakj [10]
  • from SecureFastRandom = VzougLYHYP [10]
  • from SecureFastRandom-NoCache = oVQXNGmO1S [10]

And the performance numbers tend to vary slightly, very occasionally NonOptimized is actually faster, and sometimes ForLoop and GenerateRandomString switch who's in the lead.

  • LinqIsTheNewBlack (10000x) = 96762 ticks elapsed (9.6762 ms)
  • ForLoop (10000x) = 28970 ticks elapsed (2.897 ms)
  • ForLoopNonOptimized (10000x) = 33336 ticks elapsed (3.3336 ms)
  • Repeat (10000x) = 78547 ticks elapsed (7.8547 ms)
  • GenerateRandomString (10000x) = 27416 ticks elapsed (2.7416 ms)
  • SecureFastRandom (10000x) = 13176 ticks elapsed (5ms) lowest [Different machine]
  • SecureFastRandom-NoCache (10000x) = 39541 ticks elapsed (17ms) lowest [Different machine]

Set initially selected item in Select list in Angular2

Update to angular 4.X.X, there is a new way to mark an option selected:

<select [compareWith]="byId" [(ngModel)]="selectedItem">
  <option *ngFor="let item of items" [ngValue]="item">{{item.name}}
  </option>
</select>

byId(item1: ItemModel, item2: ItemModel) {
  return item1.id === item2.id;
}

Some tutorial here

How to change a string into uppercase

For questions on simple string manipulation the dir built-in function comes in handy. It gives you, among others, a list of methods of the argument, e.g., dir(s) returns a list containing upper.

how to copy only the columns in a DataTable to another DataTable?

If only the columns are required then DataTable.Clone() can be used. With Clone function only the schema will be copied. But DataTable.Copy() copies both the structure and data

E.g.

DataTable dt = new DataTable();
dt.Columns.Add("Column Name");
dt.Rows.Add("Column Data");
DataTable dt1 = dt.Clone();
DataTable dt2 = dt.Copy();

dt1 will have only the one column but dt2 will have one column with one row.

How to ignore a particular directory or file for tslint?

As an addition

To disable all rules for the next line // tslint:disable-next-line

To disable specific rules for the next line: // tslint:disable-next-line:rule1 rule2...

To disable all rules for the current line: someCode(); // tslint:disable-line

To disable specific rules for the current line: someCode(); // tslint:disable-line:rule1

How to get the parent dir location

I tried:

import os
os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), os.pardir))

Return datetime object of previous month

You can use the third party dateutil module (PyPI entry here).

import datetime
import dateutil.relativedelta

d = datetime.datetime.strptime("2013-03-31", "%Y-%m-%d")
d2 = d - dateutil.relativedelta.relativedelta(months=1)
print d2

output:

2013-02-28 00:00:00

How can I close a login form and show the main form without my application closing?

public void ShowMain()
  {
       if(auth()) // a method that returns true when the user exists.
       {        
         this.Hide();
         var main = new Main();
         main.Show();
       }
      else
       {
              MessageBox.Show("Invalid login details.");
        }         
   }

Default Activity not found in Android Studio

Following did the trick for me. From Run -> Edit Configuration.

enter image description here

Creating a new dictionary in Python

Call dict with no parameters

new_dict = dict()

or simply write

new_dict = {}

Force git stash to overwrite added files

TL;DR:

git checkout HEAD path/to/file
git stash apply

Long version:

You get this error because of the uncommited changes that you want to overwrite. Undo these changes with git checkout HEAD. You can undo changes to a specific file with git checkout HEAD path/to/file. After removing the cause of the conflict, you can apply as usual.

Redirect to an external URL from controller action in Spring MVC

Looking into the actual implementation of UrlBasedViewResolver and RedirectView the redirect will always be contextRelative if your redirect target starts with /. So also sending a //yahoo.com/path/to/resource wouldn't help to get a protocol relative redirect.

So to achieve what you are trying you could do something like:

@RequestMapping(method = RequestMethod.POST)
public String processForm(HttpServletRequest request, LoginForm loginForm, 
                          BindingResult result, ModelMap model) 
{
    String redirectUrl = request.getScheme() + "://www.yahoo.com";
    return "redirect:" + redirectUrl;
}

Using GSON to parse a JSON array

public static <T> List<T> toList(String json, Class<T> clazz) {
    if (null == json) {
        return null;
    }
    Gson gson = new Gson();
    return gson.fromJson(json, new TypeToken<T>(){}.getType());
}

sample call:

List<Specifications> objects = GsonUtils.toList(products, Specifications.class);

Pyinstaller setting icons don't change

The below command can set the icon on an executable file.

Remember the ".ico" file should present in the place of the path given in "Path_of_.ico_file".

pyinstaller.exe --onefile --windowed --icon="Path_of_.ico_file" app.py

For example:

If the app.py file is present in the current directory and app.ico is present inside the Images folder within the current directory.

Then the command should be as below. The final executable file will be generated inside the dist folder

pyinstaller.exe --onefile --windowed --icon=Images\app.ico app.py

Use "ENTER" key on softkeyboard instead of clicking button

Most updated way to achieve this is:

Add this to your EditText in XML:

android:imeOptions="actionSearch"

Then in your Activity/Fragment:

EditText.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
        // Do what you want here
        return@setOnEditorActionListener true
    }
    return@setOnEditorActionListener false
}

Import error No module named skimage

You can use pip install scikit-image.

Also see the recommended procedure.

Accessing an SQLite Database in Swift

I have written a SQLite3 wrapper library written in Swift.

This is actually a very high level wrapper with very simple API, but anyway, it has low-level C inter-op code, and I post here a (simplified) part of it to shows the C inter-op.

    struct C
    {
        static let  NULL        =   COpaquePointer.null()
    }

    func open(filename:String, flags:OpenFlag)
    {
        let name2   =   filename.cStringUsingEncoding(NSUTF8StringEncoding)!
        let r       =   sqlite3_open_v2(name2, &_rawptr, flags.value, UnsafePointer<Int8>.null())
        checkNoErrorWith(resultCode: r)
    }

    func close()
    {   
        let r   =   sqlite3_close(_rawptr)
        checkNoErrorWith(resultCode: r)
        _rawptr =   C.NULL
    }

    func prepare(SQL:String) -> (statements:[Core.Statement], tail:String)
    {
        func once(zSql:UnsafePointer<Int8>, len:Int32, inout zTail:UnsafePointer<Int8>) -> Core.Statement?
        {
            var pStmt   =   C.NULL
            let r       =   sqlite3_prepare_v2(_rawptr, zSql, len, &pStmt, &zTail)
            checkNoErrorWith(resultCode: r)

            if pStmt == C.NULL
            {
                return  nil
            }
            return  Core.Statement(database: self, pointerToRawCStatementObject: pStmt)
        }

        var stmts:[Core.Statement]  =   []
        let sql2    =   SQL as NSString
        var zSql    =   UnsafePointer<Int8>(sql2.UTF8String)
        var zTail   =   UnsafePointer<Int8>.null()
        var len1    =   sql2.lengthOfBytesUsingEncoding(NSUTF8StringEncoding);
        var maxlen2 =   Int32(len1)+1

        while let one = once(zSql, maxlen2, &zTail)
        {
            stmts.append(one)
            zSql    =   zTail
        }

        let rest1   =   String.fromCString(zTail)
        let rest2   =   rest1 == nil ? "" : rest1!

        return  (stmts, rest2)
    }

    func step() -> Bool
    {   
        let rc1 =   sqlite3_step(_rawptr)

        switch rc1
        {   
            case SQLITE_ROW:
                return  true

            case SQLITE_DONE:
                return  false

            default:
                database.checkNoErrorWith(resultCode: rc1)
        }
    }

    func columnText(at index:Int32) -> String
    {
        let bc  =   sqlite3_column_bytes(_rawptr, Int32(index))
        let cs  =   sqlite3_column_text(_rawptr, Int32(index))

        let s1  =   bc == 0 ? "" : String.fromCString(UnsafePointer<CChar>(cs))!
        return  s1
    }

    func finalize()
    {
        let r   =   sqlite3_finalize(_rawptr)
        database.checkNoErrorWith(resultCode: r)

        _rawptr =   C.NULL
    }

If you want a full source code of this low level wrapper, see these files.

Notepad++ incrementally replace

I was looking for the same feature today but couldn't do this in Notepad++. However, we have TextPad to our rescue. It worked for me.

In TextPad's replace dialog, turn on regex; then you could try replacing

<row id="1"/>

by

<row id="\i"/>

Have a look at this link for further amazing replace features of TextPad - http://sublimetext.userecho.com/topic/106519-generate-a-sequence-of-numbers-increment-replace/

How to implement Android Pull-to-Refresh

To implement android Pull-to-Refresh try this piece of code,

<android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/pullToRefresh"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

</android.support.v4.widget.SwipeRefreshLayout>

Activity class:

ListView lv = (ListView) findViewById(R.id.lv);
SwipeRefreshLayout pullToRefresh = (SwipeRefreshLayout) findViewById(R.id.pullToRefresh);


lv.setAdapter(mAdapter);

pullToRefresh.setOnRefreshListener(new OnRefreshListener() {

        @Override
        public void onRefresh() {
            // TODO Auto-generated method stub

            refreshContent();

        }
    });



private void refreshContent(){ 

     new Handler().postDelayed(new Runnable() {
            @Override public void run() {
                pullToRefresh.setRefreshing(false);
            }
        }, 5000);

 }

Include .so library in apk in android studio

I've tried the solution presented in the accepted answer and it did not work for me. I wanted to share what DID work for me as it might help someone else. I've found this solution here.

Basically what you need to do is put your .so files inside a a folder named lib (Note: it is not libs and this is not a mistake). It should be in the same structure it should be in the APK file.

In my case it was:
Project:
|--lib:
|--|--armeabi:
|--|--|--.so files.

So I've made a lib folder and inside it an armeabi folder where I've inserted all the needed .so files. I then zipped the folder into a .zip (the structure inside the zip file is now lib/armeabi/*.so) I renamed the .zip file into armeabi.jar and added the line compile fileTree(dir: 'libs', include: '*.jar') into dependencies {} in the gradle's build file.

This solved my problem in a rather clean way.

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

If none of these answers worked like in my case do this:

  1. Drop constraints
  2. Set all values to allow nulls
  3. Truncate table
  4. Add constraints that were dropped.

Good luck!

How can I disable all views inside the layout?

You can have whichever children that you want to have the same state as the parents include android:duplicateParentState="true".  Then if you disable the parent, whatever children you have that set on will follow suit.  

This will allow you to dynamically control all states at once from the parent view.

<LinearLayout
    android:id="@+id/some_parent_something"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
     <Button 
        android:id="@+id/backbutton"
        android:text="Back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:duplicateParentState="true"/>
    <LinearLayout
        android:id="@+id/my_layout"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:duplicateParentState="true">
        <TextView
            android:id="@+id/my_text_view"
            android:text="First Name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:duplicateParentState="true" />
        <EditText
            android:id="@+id/my_edit_view"
            android:width="100px"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:duplicateParentState="true" /> 
        <View .../>
        <View .../>
        ...
           <View .../>
    </LinearLayout>

</LinearLayout>

How to use awk sort by column 3

  1. Use awk to put the user ID in front.
  2. Sort
  3. Use sed to remove the duplicate user ID, assuming user IDs do not contain any spaces.

    awk -F, '{ print $3, $0 }' user.csv | sort | sed 's/^.* //'
    

Proxy with urllib2

You have to install a ProxyHandler

urllib2.install_opener(
    urllib2.build_opener(
        urllib2.ProxyHandler({'http': '127.0.0.1'})
    )
)
urllib2.urlopen('http://www.google.com')

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

Default passwords of Oracle 11g?

It is possible to connect to the database without specifying a password. Once you've done that you can then reset the passwords. I'm assuming that you've installed the database on your machine; if not you'll first need to connect to the machine the database is running on.

  1. Ensure your user account is a member of the dba group. How you do this depends on what OS you are running.

  2. Enter sqlplus / as sysdba in a Command Prompt/shell/Terminal window as appropriate. This should log you in to the database as SYS.

  3. Once you're logged in, you can then enter

    alter user SYS identified by "newpassword";
    

    to reset the SYS password, and similarly for SYSTEM.

(Note: I haven't tried any of this on Oracle 12c; I'm assuming they haven't changed things since Oracle 11g.)

How to unpack pkl file?

Handy one-liner

pkl() (
  python -c 'import pickle,sys;d=pickle.load(open(sys.argv[1],"rb"));print(d)' "$1"
)
pkl my.pkl

Will print __str__ for the pickled object.

The generic problem of visualizing an object is of course undefined, so if __str__ is not enough, you will need a custom script.

How do I get the path of the assembly the code is in?

This should work, unless the assembly is shadow copied:

string path = System.Reflection.Assembly.GetExecutingAssembly().Location

Handling back button in Android Navigation Component

just create an extension function to the fragment

fun Fragment.onBackPressedAction(action: () -> Boolean) {
    requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object :
        OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            this.isEnabled = action()
            if (!this.isEnabled) {
                requireActivity().onBackPressed()
            }
        }
    })
}

and after in the fragment put the code into onCreateView (the action must return false to call the activity onBackPressed)

onBackPressedAction { //do something }

jquery animate .css

Just use .animate() instead of .css() (with a duration if you want), like this:

$('#hfont1').hover(function() {
    $(this).animate({"color":"#efbe5c","font-size":"52pt"}, 1000);
}, function() {
    $(this).animate({"color":"#e8a010","font-size":"48pt"}, 1000);
});

You can test it here. Note though, you need either the jQuery color plugin, or jQuery UI included to animate the color. In the above, the duration is 1000ms, you can change it, or just leave it off for the default 400ms duration.

Replace string within file contents

#!/usr/bin/python

with open(FileName) as f:
    newText=f.read().replace('A', 'Orange')

with open(FileName, "w") as f:
    f.write(newText)

MAMP mysql server won't start. No mysql processes are running

Best way to find the real cause is to check the MAMP error log in MAMP > logs > mysql_error_log.err

I found the ERROR "Do you already have another mysql server running on port: 3306 ?" - which was actually the cause for my MAMP MYSQL not starting.

Port 3306 was already "busy", so I have changed it to 8306 and that solved my issue.

Where are the Properties.Settings.Default stored?

if you use Windows 10, this is the directory:

C:\Users<UserName>\AppData\Local\

+

<ProjectName.exe_Url_somedata>\1.0.0.0<filename.config>

Two dimensional array in python

a = [[] for index in range(1, n)]

Converting a Java Keystore into PEM Format

I kept getting errors from openssl when using StoBor's command:

MAC verified OK
Error outputting keys and certificates
139940235364168:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:evp_enc.c:535:
139940235364168:error:23077074:PKCS12 routines:PKCS12_pbe_crypt:pkcs12 cipherfinal error:p12_decr.c:97:
139940235364168:error:2306A075:PKCS12 routines:PKCS12_item_decrypt_d2i:pkcs12 pbe crypt error:p12_decr.c:123:

For some reason, only this style of command would work for my JKS file

keytool -importkeystore -srckeystore foo.jks \
   -destkeystore foo.p12 \
   -srcstoretype jks \
   -srcalias mykey \
   -deststoretype pkcs12 \
   -destkeypass DUMMY123

The key was setting destkeypass, the value of the argument did not matter.

Loop through files in a directory using PowerShell

If you need to loop inside a directory recursively for a particular kind of file, use the below command, which filters all the files of doc file type

$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc

If you need to do the filteration on multiple types, use the below command.

$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc,*.pdf

Now $fileNames variable act as an array from which you can loop and apply your business logic.

How do I mock a REST template exchange?

Let say you have an exchange call like below:

String url = "/zzz/{accountNumber}";

Optional<AccountResponse> accResponse = Optional.ofNullable(accountNumber)
        .map(account -> {


            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "bearer 121212");


            HttpEntity<Object> entity = new HttpEntity<>(headers);
            ResponseEntity<AccountResponse> response = template.exchange(
                    url,
                    GET,
                    entity,
                    AccountResponse.class,
                    accountNumber
            );

            return response.getBody();
        });

To mock this in your test case you can use mocitko as below:

when(restTemplate.exchange(
        ArgumentMatchers.anyString(),
        ArgumentMatchers.any(HttpMethod.class),
        ArgumentMatchers.any(),
        ArgumentMatchers.<Class<AccountResponse>>any(),
        ArgumentMatchers.<ParameterizedTypeReference<List<Object>>>any())
)

How to check for file existence

# file? will only return true for files
File.file?(filename)

and

# Will also return true for directories - watch out!
File.exist?(filename)

How do I display image in Alert/confirm box in Javascript?

Alert boxes in JavaScript can only display pure text. You could use a JavaScript library like jQuery to display a modal instead?

This might be useful: http://jqueryui.com/dialog/

You can do it like this:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Dialog - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  <script>
  body {
    font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
    font-size: 62.5%;
}

  </script>
  <script>
  $(function() {
    $( "#dialog" ).dialog();
  });
  </script>
</head>
<body>

<div id="dialog" title="Basic dialog">
  <p>Image:</p>
  <img src="http://placehold.it/50x50" alt="Placeholder Image" />

</div>


</body>
</html>

Python "\n" tag extra line

The print function in python adds itself \n

You could use

import sys
sys.stdout.write(a)

instead

how to parse json using groovy

That response is a Map, with a single element with key '212315952136472'. There's no 'data' key in the Map. If you want to loop through all entries, use something like this:

JSONObject userJson = JSON.parse(jsonResponse)
userJson.each { id, data -> println data.link }

If you know it's a single-element Map then you can directly access the link:

def data = userJson.values().iterator().next()
String link = data.link

And if you knew the id (e.g. if you used it to make the request) then you can access the value more concisely:

String id = '212315952136472'
...
String link = userJson[id].link

What is the purpose of the : (colon) GNU Bash builtin?

If you'd like to truncate a file to zero bytes, useful for clearing logs, try this:

:> file.log

How to replace NA values in a table for selected columns

This is now trivial in tidyr with replace_na(). The function appears to work for data.tables as well as data.frames:

tidyr::replace_na(x, list(a=0, b=0))

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

compilation error: identifier expected

only variable/object declaration statement are written outside of method

public class details{
    public static void main(String arg[]){
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

here is example try to learn java book and see the syntax then try to develop the program

How to write text on a image in windows using python opencv2

I know this is a really old question but i think i have a solution In the newer versions of openCV fonts are repesented by a number like this

    FONT_HERSHEY_SIMPLEX = 0,
    FONT_HERSHEY_PLAIN = 1,
    FONT_HERSHEY_DUPLEX = 2,
    FONT_HERSHEY_COMPLEX = 3,
    FONT_HERSHEY_TRIPLEX = 4,
    FONT_HERSHEY_COMPLEX_SMALL = 5,
    FONT_HERSHEY_SCRIPT_SIMPLEX = 6,
    FONT_HERSHEY_SCRIPT_COMPLEX = 7,
    FONT_ITALIC = 16

so all you have to do is replace the font name with the corresponding number

cv2.putText(image,"Hello World!!!", (x,y), 0, 2, 255)

again i know its an old question but it may help someone in the future

delete all from table

You can also use truncate.

truncate table table_name;

How to add element into ArrayList in HashMap

I know, this is an old question. But just for the sake of completeness, the lambda version.

Map<String, List<Item>> items = new HashMap<>();
items.computeIfAbsent(key, k -> new ArrayList<>()).add(item);

MySQL - ERROR 1045 - Access denied

  1. Go to mysql console
  2. Enter use mysql;
  3. UPDATE mysql.user SET Password= PASSWORD ('') WHERE User='root' FLUSH PRIVILEGES; exit PASSWORD ('') is must empty
  4. Then go to wamp/apps/phpmyadmin../config.inc.php
  5. Find $cfg ['Servers']['$I']['password']='root';
  6. Replace the ['password'] with ['your old password']
  7. Save the file
  8. Restart the all services and goto localhost/phpmyadmin

What is "origin" in Git?

The best answer here:

https://www.git-tower.com/learn/git/glossary/origin

In Git, "origin" is a shorthand name for the remote repository that a project was originally cloned from. More precisely, it is used instead of that original repository's URL - and thereby makes referencing much easier.

SELECT max(x) is returning null; how can I make it return 0?

Depends on what product you're using, but most support something like

SELECT IFNULL(MAX(X), 0, MAX(X)) AS MaxX FROM tbl WHERE XID = 1

or

SELECT CASE MAX(X) WHEN NULL THEN 0 ELSE MAX(X) FROM tbl WHERE XID = 1

What is the difference between Html.Hidden and Html.HiddenFor

The Html.Hidden creates a hidden input but you have to specify the name and all the attributes you want to give that field and value. The Html.HiddenFor creates a hidden input for the object that you pass to it, they look like this:

Html.Hidden("yourProperty",model.yourProperty);

Html.HiddenFor(m => m.yourProperty)

In this case the output is the same!

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

For relative paths, here's what I did. I am aware of the age of this question, I simply want to contribute a simpler answer that works in the majority of cases:

Say you have a path like this:

"path/to/file/folder"

For some reason, Linux-built executables made in eclipse work fine with this. However, windows gets very confused if given a path like this to work with!

As stated above there are several ways to get the current path to the executable, but the easiest way I find works a charm in the majority of cases is appending this to the FRONT of your path:

"./path/to/file/folder"

Just adding "./" should get you sorted! :) Then you can start loading from whatever directory you wish, so long as it is with the executable itself.

EDIT: This won't work if you try to launch the executable from code::blocks if that's the development environment being used, as for some reason, code::blocks doesn't load stuff right... :D

EDIT2: Some new things I have found is that if you specify a static path like this one in your code (Assuming Example.data is something you need to load):

"resources/Example.data"

If you then launch your app from the actual directory (or in Windows, you make a shortcut, and set the working dir to your app dir) then it will work like that. Keep this in mind when debugging issues related to missing resource/file paths. (Especially in IDEs that set the wrong working dir when launching a build exe from the IDE)

Bulk create model objects in django

Check out this blog post on the bulkops module.

On my django 1.3 app, I have experienced significant speedup.

How can one tell the version of React running at runtime in the browser?

In index.js file, simply replace App component with "React.version". E.g.

ReactDOM.render(React.version, document.getElementById('root'));

I have checked this with React v16.8.1

Installing Node.js (and npm) on Windows 10

go to http://nodejs.org/

and hit the button that says "Download For ..."

This'll download the .msi (or .pkg for mac) which will do all the installation and paths for you, unlike the selected answer.

What is the Oracle equivalent of SQL Server's IsNull() function?

You can use the condition if x is not null then.... It's not a function. There's also the NVL() function, a good example of usage here: NVL function ref.

Copy a variable's value into another

I found using JSON works but watch our for circular references

var newInstance = JSON.parse(JSON.stringify(firstInstance));

Convert System.Drawing.Color to RGB and Hex Value

For hexadecimal code try this

  1. Get ARGB (Alpha, Red, Green, Blue) representation for the color
  2. Filter out Alpha channel: & 0x00FFFFFF
  3. Format out the value (as hexadecimal "X6" for hex)

For RGB one

  1. Just format out Red, Green, Blue values

Implementation

private static string HexConverter(Color c) {
  return String.Format("#{0:X6}", c.ToArgb() & 0x00FFFFFF);
}

public static string RgbConverter(Color c) {
  return String.Format("RGB({0},{1},{2})", c.R, c.G, c.B);
}

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

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

According to what you found, this was what happened :

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

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


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

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

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

Setting width/height as percentage minus pixels

Try box-sizing. For the list:

height: 100%;
/* Presuming 10px header height */
padding-top: 10px;
/* Firefox */
-moz-box-sizing: border-box;
/* WebKit */
-webkit-box-sizing: border-box;
/* Standard */
box-sizing: border-box;

For the header:

position: absolute;
left: 0;
top: 0;
height: 10px;

Of course, the parent container should has something like:

position: relative;

Access parent DataContext from DataTemplate

I had problems with the relative source in Silverlight. After searching and reading I did not find a suitable solution without using some additional Binding library. But, here is another approach for gaining access to the parent DataContext by directly referencing an element of which you know the data context. It uses Binding ElementName and works quite well, as long as you respect your own naming and don't have heavy reuse of templates/styles across components:

<ItemsControl x:Name="level1Lister" ItemsSource={Binding MyLevel1List}>
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <Button Content={Binding MyLevel2Property}
              Command={Binding ElementName=level1Lister,
                       Path=DataContext.MyLevel1Command}
              CommandParameter={Binding MyLevel2Property}>
      </Button>
    <DataTemplate>
  <ItemsControl.ItemTemplate>
</ItemsControl>

This also works if you put the button into Style/Template:

<Border.Resources>
  <Style x:Key="buttonStyle" TargetType="Button">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="Button">
          <Button Command={Binding ElementName=level1Lister,
                                   Path=DataContext.MyLevel1Command}
                  CommandParameter={Binding MyLevel2Property}>
               <ContentPresenter/>
          </Button>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>
</Border.Resources>

<ItemsControl x:Name="level1Lister" ItemsSource={Binding MyLevel1List}>
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <Button Content="{Binding MyLevel2Property}" 
              Style="{StaticResource buttonStyle}"/>
    <DataTemplate>
  <ItemsControl.ItemTemplate>
</ItemsControl>

At first I thought that the x:Names of parent elements are not accessible from within a templated item, but since I found no better solution, I just tried, and it works fine.

Docker error response from daemon: "Conflict ... already in use by container"

It looks like a container with the name qgis-desktop-2-4 already exists in the system. You can check the output of the below command to confirm if it indeed exists:

$ docker ps -a

The last column in the above command's output is for names.

If the container exists, remove it using:

$ docker rm qgis-desktop-2-4

Or forcefully using,

$ docker rm -f qgis-desktop-2-4

And then try creating a new container.

How to implement the Softmax function in Python

Already answered in much detail in above answers. max is subtracted to avoid overflow. I am adding here one more implementation in python3.

import numpy as np
def softmax(x):
    mx = np.amax(x,axis=1,keepdims = True)
    x_exp = np.exp(x - mx)
    x_sum = np.sum(x_exp, axis = 1, keepdims = True)
    res = x_exp / x_sum
    return res

x = np.array([[3,2,4],[4,5,6]])
print(softmax(x))

What is the error "Every derived table must have its own alias" in MySQL?

I arrived here because I thought I should check in SO if there are adequate answers, after a syntax error that gave me this error, or if I could possibly post an answer myself.

OK, the answers here explain what this error is, so not much more to say, but nevertheless I will give my 2 cents using my words:

This error is caused by the fact that you basically generate a new table with your subquery for the FROM command.

That's what a derived table is, and as such, it needs to have an alias (actually a name reference to it).

So given the following hypothetical query:

SELECT id, key1
FROM (
    SELECT t1.ID id, t2.key1 key1, t2.key2 key2, t2.key3 key3
    FROM table1 t1 
    LEFT JOIN table2 t2 ON t1.id = t2.id
    WHERE t2.key3 = 'some-value'
) AS tt

So, at the end, the whole subquery inside the FROM command will produce the table that is aliased as tt and it will have the following columns id, key1, key2, key3.

So, then with the initial SELECT from that table we finally select the id and key1 from the tt.

Check if all elements in a list are identical

>>> a = [1, 2, 3, 4, 5, 6]
>>> z = [(a[x], a[x+1]) for x in range(0, len(a)-1)]
>>> z
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
# Replacing it with the test
>>> z = [(a[x] == a[x+1]) for x in range(0, len(a)-1)]
>>> z
[False, False, False, False, False]
>>> if False in z : Print "All elements are not equal"

Take nth column in a text file

If you are using structured data, this has the added benefit of not invoking an extra shell process to run tr and/or cut or something. ...

(Of course, you will want to guard against bad inputs with conditionals and sane alternatives.)

...
while read line ; 
do 
    lineCols=( $line ) ;
    echo "${lineCols[0]}"
    echo "${lineCols[1]}"
done < $myFQFileToRead ; 
...

IPhone/IPad: How to get screen width programmatically?

This can be done in in 3 lines of code:

// grab the window frame and adjust it for orientation
UIView *rootView = [[[UIApplication sharedApplication] keyWindow] 
                                   rootViewController].view;
CGRect originalFrame = [[UIScreen mainScreen] bounds];
CGRect adjustedFrame = [rootView convertRect:originalFrame fromView:nil];

No WebApplicationContext found: no ContextLoaderListener registered?

And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747

cURL not working (Error #77) for SSL connections on CentOS for non-root users

Check that you have the correct rights set on CA certificates bundle. Usually, that means read access for everyone to CA files in the /etc/ssl/certs directory, for instance /etc/ssl/certs/ca-certificates.crt.

You can see what files have been configured for you curl version with the

curl-config --configure
command :

$ curl-config --configure
 '--prefix=/usr' 
 '--mandir=/usr/share/man' 
 '--disable-dependency-tracking' 
 '--disable-ldap' 
 '--disable-ldaps' 
 '--enable-ipv6' 
 '--enable-manual' 
 '--enable-versioned-symbols' 
 '--enable-threaded-resolver' 
 '--without-libidn' 
 '--with-random=/dev/urandom' 
 '--with-ca-bundle=/etc/ssl/certs/ca-certificates.crt' 
 'CFLAGS=-march=x86-64 -mtune=generic -O2 -pipe -fstack-protector --param=ssp-buffer-size=4' 'LDFLAGS=-Wl,-O1,--sort-common,--as-needed,-z,relro' 
 'CPPFLAGS=-D_FORTIFY_SOURCE=2'

Here you need read access to /etc/ssl/certs/ca-certificates.crt

$ curl-config --configure
 '--build' 'i486-linux-gnu' 
 '--prefix=/usr' 
 '--mandir=/usr/share/man' 
 '--disable-dependency-tracking' 
 '--enable-ipv6' 
 '--with-lber-lib=lber' 
 '--enable-manual' 
 '--enable-versioned-symbols' 
 '--with-gssapi=/usr' 
 '--with-ca-path=/etc/ssl/certs' 
 'build_alias=i486-linux-gnu' 
 'CFLAGS=-g -O2' 
 'LDFLAGS=' 
 'CPPFLAGS='

And the same here.

Print a list in reverse order with range()?

You could use range(10)[::-1] which is the same thing as range(9, -1, -1) and arguably more readable (if you're familiar with the common sequence[::-1] Python idiom).

Is it possible to use the SELECT INTO clause with UNION [ALL]?

Try something like this: Create the final object table, tmpFerdeen with the structure of the union.

Then

INSERT INTO tmpFerdeen (
SELECT top(100)* 
FROM Customers
UNION All
SELECT top(100)* 
FROM CustomerEurope
UNION All
SELECT top(100)* 
FROM CustomerAsia
UNION All
SELECT top(100)* 
FROM CustomerAmericas
)

How can I make a DateTimePicker display an empty string?

Obfuscating the value by using the CustomFormat property, using checkbox cbEnableEndDate as the flag to indicate whether other code should ignore the value:

If dateTaskEnd > Date.FromOADate(0) Then
    dtTaskEnd.Format = DateTimePickerFormat.Custom
    dtTaskEnd.CustomFormat = "yyyy-MM-dd"
    dtTaskEnd.Value = dateTaskEnd 
    dtTaskEnd.Enabled = True
    cbEnableEndDate.Checked = True
Else
    dtTaskEnd.Format = DateTimePickerFormat.Custom
    dtTaskEnd.CustomFormat = " "
    dtTaskEnd.Value = Date.FromOADate(0)
    dtTaskEnd.Enabled = False
    cbEnableEndDate.Checked = False
End If

TypeScript or JavaScript type casting

You can cast like this:

return this.createMarkerStyle(<MarkerSymbolInfo> symbolInfo);

Or like this if you want to be compatible with tsx mode:

return this.createMarkerStyle(symbolInfo as MarkerSymbolInfo);

Just remember that this is a compile-time cast, and not a runtime cast.

Variable is accessed within inner class. Needs to be declared final

    public class ConfigureActivity extends Activity {

        EditText etOne;
        EditText etTwo;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_configure);

            Button btnConfigure = findViewById(R.id.btnConfigure1);   
            btnConfigure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            configure();
                        }
                    });
    }

    public  void configure(){
            String one = etOne.getText().toString();
            String two = etTwo.getText().toString();
    }
}

MySQL: #126 - Incorrect key file for table

I got this message when writing to a table after reducing the ft_min_word_len (full text min word length). To solve it, re-create the index by repairing the table.

@font-face src: local - How to use the local font if the user already has it?

I haven’t actually done anything with font-face, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.

The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.

Does Firefox download the font when you actually use it in a font declaration? (e.g. h1 { font: 'DejaVu Serif';)?

How to use java.Set

Since it is a HashSet you will need to override hashCode and equals methods. http://preciselyconcise.com/java/collections/d_set.php has an example explaining how to implement hashCode and equals methods

Google Maps API: open url by clicking on marker

google.maps.event.addListener(marker, 'click', (function(marker, i) {
  return function() {
    window.location.href = marker.url;
  }
})(marker, i));

Check if object value exists within a Javascript array of objects and if not add a new object to array

Let's assume we have an array of objects and you want to check if value of name is defined like this,

let persons = [ {"name" : "test1"},{"name": "test2"}];

if(persons.some(person => person.name == 'test1')) {
    ... here your code in case person.name is defined and available
}

What are passive event listeners?

Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.

It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.

Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart and touchmove handlers, which may prevent the scroll entirely by calling preventDefault() on the event.

Solution: {passive: true}

By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user.

document.addEventListener("touchstart", function(e) {
    console.log(e.defaultPrevented);  // will be false
    e.preventDefault();   // does nothing since the listener is passive
    console.log(e.defaultPrevented);  // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);

DOM Spec , Demo Video , Explainer Doc

What's the difference between "git reset" and "git checkout"?

One simple use case when reverting change:
1. Use reset if you want to undo staging of a modified file.
2. Use checkout if you want to discard changes to unstaged file/s.

Grant SELECT on multiple tables oracle

You can do it with dynamic query, just run the following script in pl-sql or sqlplus:

select 'grant select on user_name_owner.'||table_name|| 'to user_name1 ;' from dba_tables t where t.owner='user_name_owner'

and then execute result.

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

(This might be the wrong thread, as your problem seems more specific, but it's the thread that I found when searching for the issue's keywords)

Despite all good hints, the only thing that helped me, and that I'd like to share just in case, if everything else does not work :

Remove your .gradle directory in your home directory and have it re-build/re-downloaded for you by Android Studio.

Fixed all kinds of weird errors for me that neither were fixable by re-installing Android Studio itself nor the SDK.

How to convert UTF8 string to byte array?

function convertByte()
{
    var c=document.getElementById("str").value;
    var arr = [];
    var i=0;
    for(var ind=0;ind<c.length;ind++)
    {
        arr[ind]=c.charCodeAt(i);
        i++;
    }    
    document.getElementById("result").innerHTML="The converted value is "+arr.join("");    
}

"rm -rf" equivalent for Windows?

Go to the path and trigger this command.

rd /s /q "FOLDER_NAME"

/s : Removes the specified directory and all subdirectories including any files. Use /s to remove a tree.

/q : Runs rmdir in quiet mode. Deletes directories without confirmation.

/? : Displays help at the command prompt.

Python concatenate text files

outfile.write(infile.read()) # time: 2.1085190773010254s
shutil.copyfileobj(fd, wfd, 1024*1024*10) # time: 0.60599684715271s

A simple benchmark shows that the shutil performs better.

C compiler for Windows?

I use either BloodShed's DEV C++, CygWin, or Visual C++ Express. All of which are free and work well. I have found that for me, DEV C++ worked the best and was the least quirky. Each compiler has it's own quirks and deifferences, you need to try out a few and find the one with which you are most comfortable. I also liked the fact that DEV C++ allowed me to change the fonts that are used in the editor. I like Proggy Programming fonts!

How to give a pattern for new line in grep?

just found

grep $'\r'

It's using $'\r' for c-style escape in Bash.

in this article

What is the correct way to free memory in C#

As Brian points out the GC can collect anything that is unreachable including objects that are still in scope and even while instance methods of those objects are still executing. consider the following code:

class foo
{
    static int liveFooInstances;

    public foo()
    {
        Interlocked.Increment(ref foo.liveFooInstances);
    }

    public void TestMethod()
    {
        Console.WriteLine("entering method");
        while (Interlocked.CompareExchange(ref foo.liveFooInstances, 1, 1) == 1)
        {
            Console.WriteLine("running GC.Collect");
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
        Console.WriteLine("exiting method");
    }

    ~foo()
    {
        Console.WriteLine("in ~foo");
        Interlocked.Decrement(ref foo.liveFooInstances);
    }

}

class Program
{

    static void Main(string[] args)
    {
        foo aFoo = new foo();
        aFoo.TestMethod();
        //Console.WriteLine(aFoo.ToString()); // if this line is uncommented TestMethod will never return
    }
}

if run with a debug build, with the debugger attached, or with the specified line uncommented TestMethod will never return. But running without a debugger attached TestMethod will return.

Constantly print Subprocess output while process is running

@tokland

tried your code and corrected it for 3.4 and windows dir.cmd is a simple dir command, saved as cmd-file

import subprocess
c = "dir.cmd"

def execute(command):
    popen = subprocess.Popen(command, stdout=subprocess.PIPE,bufsize=1)
    lines_iterator = iter(popen.stdout.readline, b"")
    while popen.poll() is None:
        for line in lines_iterator:
            nline = line.rstrip()
            print(nline.decode("latin"), end = "\r\n",flush =True) # yield line

execute(c)

Resolve promises one after another (i.e. in sequence)?

Using modern ES:

const series = async (tasks) => {
  const results = [];

  for (const task of tasks) {
    const result = await task;

    results.push(result);
  }

  return results;
};

//...

const readFiles = await series(files.map(readFile));

How to group time by hour or by 10 minutes

The original answer the author gave works pretty well. Just to extend this idea, you can do something like

group by datediff(minute, 0, [Date])/10

which will allow you to group by a longer period then 60 minutes, say 720, which is half a day etc.

Is it possible to preview stash contents in git?

View list of stashed changes

git stash list

For viewing list of files changed in a particular stash

git stash show -p stash@{0} --name-only

For viewing a particular file in stash

git show stash@{0} path/to/file

Attaching click to anchor tag in angular

You can try something like this:

<a href="javascript: void(0);" (click)="method()">

OR

<a href="javascript: void(0);" [routerLink]="['/abc']">

SQL variable to hold list of integers

Assuming the variable is something akin to:

CREATE TYPE [dbo].[IntList] AS TABLE(
[Value] [int] NOT NULL
)

And the Stored Procedure is using it in this form:

ALTER Procedure [dbo].[GetFooByIds]
    @Ids [IntList] ReadOnly
As 

You can create the IntList and call the procedure like so:

Declare @IDs IntList;
Insert Into @IDs Select Id From dbo.{TableThatHasIds}
Where Id In (111, 222, 333, 444)
Exec [dbo].[GetFooByIds] @IDs

Or if you are providing the IntList yourself

DECLARE @listOfIDs dbo.IntList
INSERT INTO @listofIDs VALUES (1),(35),(118);

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?

If you want to convert string to double data type then most choose parseDouble() method. See the example code:

String str = "123.67";
double d = parseDouble(str);

You will get the value in double. See the StringToDouble tutorial at tutorialData.

How to display list items on console window in C#

While the answers with List<T>.ForEach are very good.

I found String.Join<T>(string separator, IEnumerable<T> values) method more useful.

Example :

List<string> numbersStrLst = new List<string>
            { "One", "Two", "Three","Four","Five"};

Console.WriteLine(String.Join(", ", numbersStrLst));//Output:"One, Two, Three, Four, Five"

int[] numbersIntAry = new int[] {1, 2, 3, 4, 5};
Console.WriteLine(String.Join("; ", numbersIntAry));//Output:"1; 2; 3; 4; 5"

Remarks :

If separator is null, an empty string (String.Empty) is used instead. If any member of values is null, an empty string is used instead.

Join(String, IEnumerable<String>) is a convenience method that lets you concatenate each element in an IEnumerable(Of String) collection without first converting the elements to a string array. It is particularly useful with Language-Integrated Query (LINQ) query expressions.

This should work just fine for the problem, whereas for others, having array values. Use other overloads of this same method, String.Join Method (String, Object[])

Reference: https://msdn.microsoft.com/en-us/library/dd783876(v=vs.110).aspx

How can I rotate an HTML <div> 90 degrees?

Use the css "rotate()" method:

_x000D_
_x000D_
div {
  width: 100px;
  height: 100px;
  background-color: yellow;
  border: 1px solid black;
}

div#rotate{
  transform: rotate(90deg);
}
_x000D_
<div>
normal div
</div>
<br>

<div id="rotate">
This div is rotated 90 degrees
</div>
_x000D_
_x000D_
_x000D_

Convert a string representation of a hex dump to a byte array using Java?

One-liners:

import javax.xml.bind.DatatypeConverter;

public static String toHexString(byte[] array) {
    return DatatypeConverter.printHexBinary(array);
}

public static byte[] toByteArray(String s) {
    return DatatypeConverter.parseHexBinary(s);
}

Warnings:

  • in Java 9 Jigsaw this is no longer part of the (default) java.se root set so it will result in a ClassNotFoundException unless you specify --add-modules java.se.ee (thanks to @eckes)
  • Not available on Android (thanks to Fabian for noting that), but you can just take the source code if your system lacks javax.xml for some reason. Thanks to @Bert Regelink for extracting the source.

Maven 3 warnings about build.plugins.plugin.version

Add a <version> element after the <plugin> <artifactId> in your pom.xml file. Find the following text:

<plugin>
  <artifactId>maven-compiler-plugin</artifactId>

Add the version tag to it:

<plugin>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>2.3.2</version>

The warning should be resolved.

Regarding this:

'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing

Many people have mentioned why the issue is happening, but fail to suggest a fix. All I needed to do was to go into my POM file for my project, and add the <version> tag as shown above.

To discover the version number, one way is to look in Maven's output after it finishes running. Where you are missing version numbers, Maven will display its default version:

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

Take that version number (as in the 2.3.2 above) and add it to your POM, as shown.

How to Check whether Session is Expired or not in asp.net

Here I am checking session values(two values filled in text box on previous page)

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["sessUnit_code"] == null || Session["sessgrcSerial"] == null)
    {
        Response.Write("<Script Language = 'JavaScript'> alert('Go to GRC Tab and fill Unit Code and GRC Serial number first')</script>");
    }
    else
    {

        lblUnit.Text = Session["sessUnit_code"].ToString();
        LblGrcSr.Text = Session["sessgrcSerial"].ToString();
    }
}

How do you get the current project directory from C# code when creating a custom MSBuild task?

This works on VS2017 w/ SDK Core MSBuild configurations.

You need to NuGet in the EnvDTE / EnvDTE80 packages.

Do not use COM or interop. anything.... garbage!!

 internal class Program {
    private static readonly DTE2 _dte2;

    // Static Constructor
    static Program() {
      _dte2 = (DTE2)Marshal.GetActiveObject("VisualStudio.DTE.15.0");
    }


    private static void FindProjectsIn(ProjectItem item, List<Project> results) {
      if (item.Object is Project) {
        var proj = (Project) item.Object;
        if (new Guid(proj.Kind) != new Guid(Constants.vsProjectItemKindPhysicalFolder))
          results.Add((Project) item.Object);
        else
          foreach (ProjectItem innerItem in proj.ProjectItems)
            FindProjectsIn(innerItem, results);
      }

      if (item.ProjectItems != null)
        foreach (ProjectItem innerItem in item.ProjectItems)
          FindProjectsIn(innerItem, results);
    }


    private static void FindProjectsIn(UIHierarchyItem item, List<Project> results) {
      if (item.Object is Project) {
        var proj = (Project) item.Object;
        if (new Guid(proj.Kind) != new Guid(Constants.vsProjectItemKindPhysicalFolder))
          results.Add((Project) item.Object);
        else
          foreach (ProjectItem innerItem in proj.ProjectItems)
            FindProjectsIn(innerItem, results);
      }

      foreach (UIHierarchyItem innerItem in item.UIHierarchyItems)
        FindProjectsIn(innerItem, results);
    }


    private static IEnumerable<Project> GetEnvDTEProjectsInSolution() {
      var ret = new List<Project>();
      var hierarchy = _dte2.ToolWindows.SolutionExplorer;
      foreach (UIHierarchyItem innerItem in hierarchy.UIHierarchyItems)
        FindProjectsIn(innerItem, ret);
      return ret;
    }


    private static void Main() {
      var projects = GetEnvDTEProjectsInSolution();
      var solutiondir = Path.GetDirectoryName(_dte2.Solution.FullName);

      // TODO
      ...

      var project = projects.FirstOrDefault(p => p.Name == <current project>);
      Console.WriteLine(project.FullName);
    }
  }

IIS 7, HttpHandler and HTTP Error 500.21

Luckily, it’s very easy to resolve. Run the follow command from an elevated command prompt:

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

If you’re on a 32-bit machine, you may have to use the following:

%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

Callback functions in C++

Boost's signals2 allows you to subscribe generic member functions (without templates!) and in a threadsafe way.

Example: Document-View Signals can be used to implement flexible Document-View architectures. The document will contain a signal to which each of the views can connect. The following Document class defines a simple text document that supports mulitple views. Note that it stores a single signal to which all of the views will be connected.

class Document
{
public:
    typedef boost::signals2::signal<void ()>  signal_t;

public:
    Document()
    {}

    /* Connect a slot to the signal which will be emitted whenever
      text is appended to the document. */
    boost::signals2::connection connect(const signal_t::slot_type &subscriber)
    {
        return m_sig.connect(subscriber);
    }

    void append(const char* s)
    {
        m_text += s;
        m_sig();
    }

    const std::string& getText() const
    {
        return m_text;
    }

private:
    signal_t    m_sig;
    std::string m_text;
};

Next, we can begin to define views. The following TextView class provides a simple view of the document text.

class TextView
{
public:
    TextView(Document& doc): m_document(doc)
    {
        m_connection = m_document.connect(boost::bind(&TextView::refresh, this));
    }

    ~TextView()
    {
        m_connection.disconnect();
    }

    void refresh() const
    {
        std::cout << "TextView: " << m_document.getText() << std::endl;
    }
private:
    Document&               m_document;
    boost::signals2::connection  m_connection;
};

Excel: Creating a dropdown using a list in another sheet?

That cannot be done in excel 2007. The list must be in the same sheet as your data. It might work in later versions though.

How to fix Error: this class is not key value coding-compliant for the key tableView.'

Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?

How to fix "could not find a base address that matches schema http"... in WCF

Try changing the security mode from "Transport" to "None".

      <!-- Transport security mode requires IIS to have a
           certificate configured for SSL. See readme for
           more information on how to set this up. -->
      <security mode="None">

fs: how do I locate a parent folder?

The easiest way would be to use path.resolve:

path.resolve(__dirname, '..', '..');

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

How about this?

SELECT Value, ReadTime, ReadDate
FROM YOURTABLE
WHERE CAST(ReadDate AS DATETIME) + ReadTime BETWEEN '2010-09-16 17:00:00' AND '2010-09-21 09:00:00'

EDIT: output according to OP's wishes ;-)

Is there a "previous sibling" selector?

I found a way to style all previous siblings (opposite of ~) that may work depending on what you need.

Let's say you have a list of links and when hovering on one, all the previous ones should turn red. You can do it like this:

_x000D_
_x000D_
/* default link color is blue */_x000D_
.parent a {_x000D_
  color: blue;_x000D_
}_x000D_
_x000D_
/* prev siblings should be red */_x000D_
.parent:hover a {_x000D_
  color: red;_x000D_
}_x000D_
.parent a:hover,_x000D_
.parent a:hover ~ a {_x000D_
  color: blue;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <a href="#">link</a>_x000D_
  <a href="#">link</a>_x000D_
  <a href="#">link</a>_x000D_
  <a href="#">link</a>_x000D_
  <a href="#">link</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

php exec() is not executing the command

You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick.

What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?

Send params from View to an other View, from Sender View to Receiver View use viewParam and includeViewParams=true

In Sender

  1. Declare params to be sent. We can send String, Object,…

Sender.xhtml

<f:metadata>
      <f:viewParam name="ID" value="#{senderMB._strID}" />
</f:metadata>
  1. We’re going send param ID, it will be included with “includeViewParams=true” in return String of click button event Click button fire senderMB.clickBtnDetail(dto) with dto from senderMB._arrData

Sender.xhtml

<p:dataTable rowIndexVar="index" id="dataTale"value="#{senderMB._arrData}" var="dto">
      <p:commandButton action="#{senderMB.clickBtnDetail(dto)}" value="??" 
      ajax="false"/>
</p:dataTable>

In senderMB.clickBtnDetail(dto) we assign _strID with argument we got from button event (dto), here this is Sender_DTO and assign to senderMB._strID

Sender_MB.java
    public String clickBtnDetail(sender_DTO sender_dto) {
        this._strID = sender_dto.getStrID();
        return "Receiver?faces-redirect=true&includeViewParams=true";
    }

The link when clicked will become http://localhost:8080/my_project/view/Receiver.xhtml?*ID=12345*

In Recever

  1. Get viewParam Receiver.xhtml In Receiver we declare f:viewParam to get param from get request (receive), the name of param of receiver must be the same with sender (page)

Receiver.xhtml

<f:metadata><f:viewParam name="ID" value="#{receiver_MB._strID}"/></f:metadata>

It will get param ID from sender View and assign to receiver_MB._strID

  1. Use viewParam In Receiver, we want to use this param in sql query before the page render, so that we use preRenderView event. We are not going to use constructor because constructor will be invoked before viewParam is received So that we add

Receiver.xhtml

<f:event listener="#{receiver_MB.preRenderView}" type="preRenderView" />

into f:metadata tag

Receiver.xhtml

<f:metadata>
<f:viewParam name="ID" value="#{receiver_MB._strID}" />
<f:event listener="#{receiver_MB.preRenderView}"
            type="preRenderView" />
</f:metadata>

Now we want to use this param in our read database method, it is available to use

Receiver_MB.java
public void preRenderView(ComponentSystemEvent event) throws Exception {
        if (FacesContext.getCurrentInstance().isPostback()) {
            return;
        }
        readFromDatabase();
    }
private void readFromDatabase() {
//use _strID to read and set property   
}

How to print without newline or space?

The new (as of Python 3.x) print function has an optional end parameter that lets you modify the ending character:

print("HELLO", end="")
print("HELLO")

Output:

HELLOHELLO

There's also sep for separator:

print("HELLO", "HELLO", "HELLO", sep="")

Output:

HELLOHELLOHELLO

If you wanted to use this in Python 2.x just add this at the start of your file:

from __future__ import print_function

Python subprocess/Popen with a modified environment

To temporarily set an environment variable without having to copy the os.envrion object etc, I do this:

process = subprocess.Popen(['env', 'RSYNC_PASSWORD=foobar', 'rsync', \
'rsync://[email protected]::'], stdout=subprocess.PIPE)

Is there a way to detect if a browser window is not currently active?

Using : Page Visibility API

document.addEventListener( 'visibilitychange' , function() {
    if (document.hidden) {
        console.log('bye');
    } else {
        console.log('well back');
    }
}, false );

Can i use ? http://caniuse.com/#feat=pagevisibility

cast or convert a float to nvarchar?

Do not use floats to store fixed-point, accuracy-required data. This example shows how to convert a float to NVARCHAR(50) properly, while also showing why it is a bad idea to use floats for precision data.

create table #f ([Column_Name] float)
insert #f select 9072351234
insert #f select 907235123400000000000

select
    cast([Column_Name] as nvarchar(50)),
    --cast([Column_Name] as int), Arithmetic overflow
    --cast([Column_Name] as bigint), Arithmetic overflow
    CAST(LTRIM(STR([Column_Name],50)) AS NVARCHAR(50))
from #f

Output

9.07235e+009    9072351234
9.07235e+020    907235123400000010000

You may notice that the 2nd output ends with '10000' even though the data we tried to store in the table ends with '00000'. It is because float datatype has a fixed number of significant figures supported, which doesn't extend that far.

"OverflowError: Python int too large to convert to C long" on windows but not mac

You'll get that error once your numbers are greater than sys.maxsize:

>>> p = [sys.maxsize]
>>> preds[0] = p
>>> p = [sys.maxsize+1]
>>> preds[0] = p
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long

You can confirm this by checking:

>>> import sys
>>> sys.maxsize
2147483647

To take numbers with larger precision, don't pass an int type which uses a bounded C integer behind the scenes. Use the default float:

>>> preds = np.zeros((1, 3))

Correctly Parsing JSON in Swift 3

Swift has a powerful type inference. Lets get rid of "if let" or "guard let" boilerplate and force unwraps using functional approach:

  1. Here is our JSON. We can use optional JSON or usual. I'm using optional in our example:
let json: Dictionary<String, Any>? = ["current": ["temperature": 10]]
  1. Helper functions. We need to write them only once and then reuse with any dictionary:
/// Curry
public func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C {
    return { a in
        { f(a, $0) }
    }
}

/// Function that takes key and optional dictionary and returns optional value
public func extract<Key, Value>(_ key: Key, _ json: Dictionary<Key, Any>?) -> Value? {
    return json.flatMap {
        cast($0[key])
    }
}

/// Function that takes key and return function that takes optional dictionary and returns optional value
public func extract<Key, Value>(_ key: Key) -> (Dictionary<Key, Any>?) -> Value? {
    return curry(extract)(key)
}

/// Precedence group for our operator
precedencegroup RightApplyPrecedence {
    associativity: right
    higherThan: AssignmentPrecedence
    lowerThan: TernaryPrecedence
}

/// Apply. g § f § a === g(f(a))
infix operator § : RightApplyPrecedence
public func §<A, B>(_ f: (A) -> B, _ a: A) -> B {
    return f(a)
}

/// Wrapper around operator "as".
public func cast<A, B>(_ a: A) -> B? {
    return a as? B
}
  1. And here is our magic - extract the value:
let temperature = (extract("temperature") § extract("current") § json) ?? NSNotFound

Just one line of code and no force unwraps or manual type casting. This code works in playground, so you can copy and check it. Here is an implementation on GitHub.

How to activate an Anaconda environment

For me, using Anaconda Prompt instead of cmd or PowerShell is the key.

In Anaconda Prompt, all I need to do is activate XXX

Check if an element contains a class in JavaScript?

Since .className is a string, you can use the string includes() method to check if your .className includes your class name:

element.className.includes("class1")

bootstrap 4 file input doesn't show the file name

Johann-S solution works great. (And it looks like he created the awesome plugin)

The Bootstrap 4.3 documentation example page uses this plugin to modify the filename: https://github.com/Johann-S/bs-custom-file-input

Use the Bootstrap custom file input classes. Add the plugin to your project, and add this code in your script file on the page.

$(document).ready(function () {
  bsCustomFileInput.init()
})

How can I set Image source with base64

img = new Image();
img.src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
img.outerHTML;
"<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==">"

Each GROUP BY expression must contain at least one column that is not an outer reference

Here's a simple query to find company name who has a medicine type of A and makes more than 2.

SELECT CNAME 
FROM COMPANY 
WHERE CNO IN (
    SELECT CNO 
    FROM MEDICINE 
    WHERE type='A' 
    GROUP BY CNO HAVING COUNT(type) > 2
)

How to get Javascript Select box's selected text

this.options[this.selectedIndex].innerHTML

should provide you with the "displayed" text of the selected item. this.value, like you said, merely provides the value of the value attribute.

Changing Locale within the app itself

I couldn't used android:anyDensity="true" because objects in my game would be positioned completely different... seems this also does the trick:

// creating locale
Locale locale2 = new Locale(loc); 
Locale.setDefault(locale2);
Configuration config2 = new Configuration();
config2.locale = locale2;

// updating locale
mContext.getResources().updateConfiguration(config2, null);

Is there a way to run Bash scripts on Windows?

In order to run natively, you will likely need to use Cygwin (which I cannot live without when using Windows). So right off the bat, +1 for Cygwin. Anything else would be uncivilized.

HOWEVER, that being said, I have recently begun using a combination of utilities to easily PORT Bash scripts to Windows so that my anti-Linux coworkers can easily run complex tasks that are better handled by GNU utilities.

I can usually port a Bash script to Batch in a very short time by opening the original script in one pane and writing a Batch file in the other pane. The tools that I use are as follows:

I prefer UnxUtils to GnuWin32 because of the fact that [someone please correct me if I'm wrong] GnuWin utils normally have to be installed, whereas UnxUtils are standalone binaries that just work out-of-the-box.

However, the CoreUtils do not include some familiar *NIX utilities such as cURL, which is also available for Windows (curl.haxx.se/download.html).

I create a folder for the projects, and always SET PATH=. in the .bat file so that no other commands other than the basic CMD shell commands are referenced (as well as the particular UnxUtils required in the project folder for the Batch script to function as expected).

Then I copy the needed CoreUtils .exe files into the project folder and reference them in the .bat file such as ".\curl.exe -s google.com", etc.

The Bat2Exe program is where the magic happens. Once your Batch file is complete and has been tested successfully, launch Bat2Exe.exe, and specify the path to the project folder. Bat2Exe will then create a Windows binary containing all of the files in that specific folder, and will use the first .bat that it comes across to use as the main executable. You can even include a .ico file to use as the icon for the final .exe file that is generated.

I have tried a few of these type of programs, and many of the generated binaries get flagged as malware, but the Bat2Exe version that I referenced works perfectly and the generated .exe files scan completely clean.

The resulting executable can be run interactively by double-clicking, or run from the command line with parameters, etc., just like a regular Batch file, except you will be able to utilize the functionality of many of the tools that you will normally use in Bash.

I realize this is getting quite long, but if I may digress a bit, I have also written a Batch script that I call PortaBashy that my coworkers can launch from a network share that contains a portable Cygwin installation. It then sets the %PATH% variable to the normal *NIX format (/usr/bin:/usr/sbin:/bin:/sbin), etc. and can either launch into the Bash shell itself or launch the more-powerful and pretty MinTTY terminal emulator.

There are always numerous ways to accomplish what you are trying to set out to do; it's just a matter of combining the right tools for the job, and many times it boils down to personal preference.

Eclipse executable launcher error: Unable to locate companion shared library

Try running eclipse.exe as administrator or using Eclipse Helios.

Is there a native jQuery function to switch elements?

I've found an interesting way to solve this using only jQuery:

$("#element1").before($("#element2"));

or

$("#element1").after($("#element2"));

:)

Twitter bootstrap float div right

You have two span6 divs within your row so that will take up the whole 12 spans that a row is made up of.

Adding pull-right to the second span6 div isn't going to do anything to it as it's already sitting to the right.

If you mean you want to have the text in the second span6 div aligned to the right then simple add a new class to that div and give it the text-align: right value e.g.

.myclass {
    text-align: right;
}

UPDATE:

EricFreese pointed out that in the 2.3 release of Bootstrap (last week) they've added text-align utility classes that you can use:

  • .text-left
  • .text-center
  • .text-right

http://twitter.github.com/bootstrap/base-css.html#typography

Break string into list of characters in Python

Or use a fancy list comprehension, which are supposed to be "computationally more efficient", when working with very very large files/lists

fd = open(filename,'r')
chars = [c for line in fd for c in line if c is not " "]
fd.close()

Btw: The answer that was accepted does not account for the whitespaces...

Best practice to look up Java Enum

update: As GreenTurtle correctly remarked, the following is wrong


I would just write

boolean result = Arrays.asList(FooEnum.values()).contains("Foo");

This is possibly less performant than catching a runtime exception, but makes for much cleaner code. Catching such exceptions is always a bad idea, since it is prone to misdiagnosis. What happens when the retrieval of the compared value itself causes an IllegalArgumentException ? This would then be treaten like a non matching value for the enumerator.

Hibernate, @SequenceGenerator and allocationSize

To be absolutely clear... what you describe does not conflict with the spec in any way. The spec talks about the values Hibernate assigns to your entities, not the values actually stored in the database sequence.

However, there is the option to get the behavior you are looking for. First see my reply on Is there a way to dynamically choose a @GeneratedValue strategy using JPA annotations and Hibernate? That will give you the basics. As long as you are set up to use that SequenceStyleGenerator, Hibernate will interpret allocationSize using the "pooled optimizer" in the SequenceStyleGenerator. The "pooled optimizer" is for use with databases that allow an "increment" option on the creation of sequences (not all databases that support sequences support an increment). Anyway, read up about the various optimizer strategies there.