Programs & Examples On #Scancodes

How to increase size of DOSBox window?

For using DOSBox with SDL, you will need to set or change the following:

[sdl]
windowresolution=1280x960
output=opengl

Here is three options to put those settings:

  1. Edit user's default configuration, for example, using vi:

    $ dosbox -printconf
    /home/USERNAME/.dosbox/dosbox-0.74.conf
    $ vi "$(dosbox -printconf)"
    $ dosbox
    
  2. For temporary resize, create a new configuration with the three lines above, say newsize.conf:

    $ dosbox -conf newsize.conf
    

    You can use -conf to load multiple configuration and/or with -userconf for default configuration, for example:

    $ dosbox -userconf -conf newsize.conf 
    [snip]
    ---
    CONFIG:Loading primary settings from config file /home/USERNAME/.dosbox/dosbox-0.74.conf
    CONFIG:Loading additional settings from config file newsize.conf
    [snip]
    
  3. Create a dosbox.conf under current directory, DOSBox loads it as default.

DOSBox should start up and resize to 1280x960 in this case.

Note that you probably would not get any size you desired, for instance, I set 1280x720 and I got 1152x720.

Import existing source code to GitHub

If you've got local source code you want to add to a new remote new git repository without 'cloning' the remote first, do the following (I often do this - you create your remote empty repository in bitbucket/github, then push up your source)

  1. Create the remote repository, and get the URL such as [email protected]:/youruser/somename.git or https://github.com/youruser/somename.git

    If your local GIT repo is already set up, skips steps 2 and 3


  2. Locally, at the root directory of your source, git init

    2a. If you initialize the repo with a .gitignore and a README.md you should do a git pull {url from step 1} to ensure you don't commit files to source that you want to ignore ;)

  3. Locally, add and commit what you want in your initial repo (for everything, git add . then git commit -m 'initial commit comment')


  4. to attach your remote repo with the name 'origin' (like cloning would do)
    git remote add origin [URL From Step 1]

  5. Execute git pull origin master to pull the remote branch so that they are in sync.
  6. to push up your master branch (change master to something else for a different branch):
    git push origin master

How to hide a button programmatically?

Please try this: playButton = (Button) findViewById(R.id.play); playButton.setVisibility(View.INVISIBLE); I think this will do it.

How to browse localhost on Android device?

I needed to see localhost on my android device as well (Samsung S3) as I was developing a Java Web-application.
By far the fastest and easiest way is to go to this link and follow instructions: https://developer.chrome.com/devtools/docs/remote-debugging

* Note: You have to use Google Chrome.*
My summary of the above link:

  • Connect PC with Phone over USB.
  • Turn on Phone's "Developer options" from Settings
  • Go to about:inspect URL in PC's browser
  • Check "Discover USB Devices" (forward Ports if you are using them in your web-application)
  • Copy/paste localhost required link to text field in browser and click Open.

Piece of cake

How to set socket timeout in C when making multiple connections?

Can't you implement your own timeout system?

Keep a sorted list, or better yet a priority heap as Heath suggests, of timeout events. In your select or poll calls use the timeout value from the top of the timeout list. When that timeout arrives, do that action attached to that timeout.

That action could be closing a socket that hasn't connected yet.

How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?

using System.Drawing;
using System.Drawing.Imaging;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

public void ScreenshotByElement()
{
    IWebDriver driver = new FirefoxDriver();
    String baseURL = "www.google.com/"; //url link
    String filePath = @"c:\\img1.png";      

    driver.Navigate().GoToUrl(baseURL);
    var remElement = driver.FindElement(By.Id("Butterfly"));
    Point location = remElement.Location;

    var screenshot = (driver as FirefoxDriver).GetScreenshot();
    using (MemoryStream stream = new MemoryStream(screenshot.AsByteArray))
    {
        using (Bitmap bitmap = new Bitmap(stream))
        {
            RectangleF part = new RectangleF(location.X, location.Y, remElement.Size.Width, remElement.Size.Height);
            using (Bitmap bn = bitmap.Clone(part, bitmap.PixelFormat))
            {
                bn.Save(filePath, ImageFormat.Png);                        
            }
        }
    }
}

How to configure heroku application DNS to Godaddy Domain?

There are 2 steps you need to perform,

  1. Add the custom domains addon and add the domain your going to use, eg www.mywebsite.com to your application
  2. Go to your domain registrar control panel and set www.mywebsite.com to be a CNAME entry to yourapp.herokuapp.com assuming you are using the CEDAR stack.
  3. There is a third step if you want to use a naked domain, eg mywebsite.com when you would have to add the IP addresses of the Heroku load balancers to your DNS for mywebsite.com

You can read more about this at http://devcenter.heroku.com/articles/custom-domains

At a guess you've missed out the first step perhaps?

UPDATE: Following the announcement of Bamboo's EOL proxy.heroku.com being retired (September 2014) for Bamboo applications so these should also now use the yourapp.herokuapp.com mapping now as well.

Git: force user and password prompt

Addition to third answer: If you're using non-english Windows, you can find "Credentials Manager" through "Control panel" > "User Accounts" > "Credentials Manager" Icon of Credentials Manager

css - position div to bottom of containing div

.outside {
    width: 200px;
    height: 200px;
    background-color: #EEE; /*to make it visible*/
}

Needs to be

.outside {
    position: relative;
    width: 200px;
    height: 200px;
    background-color: #EEE; /*to make it visible*/
}

Absolute positioning looks for the nearest relatively positioned parent within the DOM, if one isn't defined it will use the body.

Is there a way to specify a max height or width for an image?

You can try this one

img{
    max-height:500px;
    max-width:500px;
    height:auto;
    width:auto;
}

This keeps the aspect ratio of the image and prevents either the two dimensions exceed 500px

You can check this post

How do I read the file content from the Internal storage - Android App

Read a file as a string full version (handling exceptions, using UTF-8, handling new line):

// Calling:
/* 
    Context context = getApplicationContext();
    String filename = "log.txt";
    String str = read_file(context, filename);
*/  
public String read_file(Context context, String filename) {
        try {
            FileInputStream fis = context.openFileInput(filename);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            return sb.toString();
        } catch (FileNotFoundException e) {
            return "";
        } catch (UnsupportedEncodingException e) {
            return "";
        } catch (IOException e) {
            return "";
        }
    }

Note: you don't need to bother about file path only with file name.

IE8 support for CSS Media Query

IE8 (and lower versions) and Firefox prior to 3.5 do not support media query. Safari 3.2 partially supports it.

There are some workarounds that use JavaScript to add media query support to these browsers. Try these:

Media Queries jQuery plugin (only deals with max/min width)

css3-mediaqueries-js – a library that aims to add media query support to non-supporting browsers

How to center align the cells of a UICollectionView?

Based on user3676011 answer, I can suggest more detailed one with small correction. This solution works great on Swift 2.0.

enum CollectionViewContentPosition {
    case Left
    case Center
}

var collectionViewContentPosition: CollectionViewContentPosition = .Left

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
    insetForSectionAtIndex section: Int) -> UIEdgeInsets {

    if collectionViewContentPosition == .Left {
        return UIEdgeInsetsZero
    }

    // Center collectionView content

    let itemsCount: CGFloat = CGFloat(collectionView.numberOfItemsInSection(section))
    let collectionViewWidth: CGFloat = collectionView.bounds.width

    let itemWidth: CGFloat = 40.0
    let itemsMargin: CGFloat = 10.0

    let edgeInsets = (collectionViewWidth - (itemsCount * itemWidth) - ((itemsCount-1) * itemsMargin)) / 2

    return UIEdgeInsetsMake(0, edgeInsets, 0, 0)
}

There was an issue in

(CGFloat(elements.count) * 10))

where should be additional -1 mentioned.

Disable keyboard on EditText

This worked for me. First add this android:windowSoftInputMode="stateHidden" in your android manifest file, under your activity. like below:

<activity ... android:windowSoftInputMode="stateHidden">

Then on onCreate method of youractivity, add the foloowing code:

EditText editText = (EditText)findViewById(R.id.edit_text);
edit_text.setOnTouchListener(new OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        v.onTouchEvent(event);
        InputMethodManager inputMethod = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethod!= null) {
            inputMethod.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }                
        return true;
    }
});

Then if you want the pointer to be visible add this on your xml android:textIsSelectable="true".

This will make the pointer visible. In this way the keyboard will not popup when your activity starts and also will be hidden when you click on the edittext.

Start an external application from a Google Chrome Extension?

Previously, you would do this through NPAPI plugins.

However, Google is now phasing out NPAPI for Chrome, so the preferred way to do this is using the native messaging API. The external application would have to register a native messaging host in order to exchange messages with your application.

How can I add numbers in a Bash script?

Another portable POSIX compliant way to do in bash, which can be defined as a function in .bashrc for all the arithmetic operators of convenience.

addNumbers () {
    local IFS='+'
    printf "%s\n" "$(( $* ))"
}

and just call it in command-line as,

addNumbers 1 2 3 4 5 100
115

The idea is to use the Input-Field-Separator(IFS), a special variable in bash used for word splitting after expansion and to split lines into words. The function changes the value locally to use word-splitting character as the sum operator +.

Remember the IFS is changed locally and does NOT take effect on the default IFS behaviour outside the function scope. An excerpt from the man bash page,

The shell treats each character of IFS as a delimiter, and splits the results of the other expansions into words on these characters. If IFS is unset, or its value is exactly , the default, then sequences of , , and at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words.

The "$(( $* ))" represents the list of arguments passed to be split by + and later the sum value is output using the printf function. The function can be extended to add scope for other arithmetic operations also.

Android Error Building Signed APK: keystore.jks not found for signing config 'externalOverride'

Click on choose existing and again choose the location where your jks file is located.

enter image description here

I hope this trick works for you.

Get resultset from oracle stored procedure

FYI as of Oracle 12c, you can do this:

CREATE OR REPLACE PROCEDURE testproc(n number)
AS
  cur SYS_REFCURSOR;
BEGIN
    OPEN cur FOR SELECT object_id,object_name from all_objects where rownum < n;
    DBMS_SQL.RETURN_RESULT(cur);
END;
/

EXEC testproc(3);

OBJECT_ID OBJECT_NAME                                                                                                                     
---------- ------------
100 ORA$BASE                                                                                                                        
116 DUAL                                                                                                                            

This was supposed to get closer to other databases, and ease migrations. But it's not perfect to me, for instance SQL developer won't display it nicely as a normal SELECT.

I prefer the output of pipeline functions, but they need more boilerplate to code.

more info: https://oracle-base.com/articles/12c/implicit-statement-results-12cr1

How to get the html of a div on another page with jQuery ajax?

Unfortunately an ajax request gets the entire file, but you can filter the content once it's retrieved:

$.ajax({
   url:href,
   type:'GET',
   success: function(data) {
       var content = $('<div>').append(data).find('#content');
       $('#content').html( content );
   }
});

Note the use of a dummy element as find() only works with descendants, and won't find root elements.

or let jQuery filter it for you:

$('#content').load(href + ' #IDofDivToFind');

I'm assuming this isn't a cross domain request, as that won't work, only pages on the same domain.

How to find the first and second maximum number?

OK I found it.

=LARGE($E$4:$E$9;A12)

=large(array, k)

Array Required. The array or range of data for which you want to determine the k-th largest value.

K Required. The position (from the largest) in the array or cell range of data to return.

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured

“Failed to configure a DataSource” error. First, we fixed the issue by defining the data source. Next, we discussed how to work around the issue without configuring the data source at all.

https://www.baeldung.com/spring-boot-failed-to-configure-data-source

How I can print to stderr in C?

#include<stdio.h>

int main ( ) {
    printf( "hello " );
    fprintf( stderr, "HELP!" );
    printf( " world\n" );
    return 0;
}

$ ./a.exe
HELP!hello  world
$ ./a.exe 2> tmp1
hello  world
$ ./a.exe 1> tmp1
HELP!$
  1. stderr is usually unbuffered and stdout usually is. This can lead to odd looking output like this, which suggests code is executing in the wrong order. It isn't, it's just that the stdout buffer has yet to be flushed. Redirected or piped streams would of course not see this interleave as they would normally only see the output of stdout only or stderr only.

  2. Although initially both stdout and stderr come to the console, both are separate and can be individually redirected.

Why would one mark local variables and method parameters as "final" in Java?

I let Eclipse do it for me when they are being used in an anonymous class, which is increasing due to my use of Google Collection API.

How to stop a function

I'm just going to do this

def function():
  while True:
    #code here

    break

Use "break" to stop the function.

How can I append a query parameter to an existing URL?

Kotlin & clean, so you don't have to refactor before code review:

private fun addQueryParameters(url: String?): String? {
        val uri = URI(url)

        val queryParams = StringBuilder(uri.query.orEmpty())
        if (queryParams.isNotEmpty())
            queryParams.append('&')

        queryParams.append(URLEncoder.encode("$QUERY_PARAM=$param", Xml.Encoding.UTF_8.name))
        return URI(uri.scheme, uri.authority, uri.path, queryParams.toString(), uri.fragment).toString()
    }

When to use which design pattern?

I completely agree with @Peter Rasmussen.

Design patterns provide general solution to commonly occurring design problem.

I would like you to follow below approach.

  1. Understand intent of each pattern
  2. Understand checklist or use case of each pattern
  3. Think of solution to your problem and check if your solution falls into checklist of particular pattern
  4. If not, simply ignore the design-patterns and write your own solution.

Useful links:

sourcemaking : Explains intent, structure and checklist beautifully in multiple languages including C++ and Java

wikipedia : Explains structure, UML diagram and working examples in multiple languages including C# and Java .

Check list and Rules of thumb in each sourcemakding design-pattern provides alram bell you are looking for.

Date minus 1 year?

// set your date here
$mydate = "2009-01-01";

/* strtotime accepts two parameters.
The first parameter tells what it should compute.
The second parameter defines what source date it should use. */
$lastyear = strtotime("-1 year", strtotime($mydate));

// format and display the computed date
echo date("Y-m-d", $lastyear);

Visual Studio breakpoints not being hit

In my case I had a string of length 70kb. Compiler did not thrown any error. But Debugger failed to hit the break point. After spending 3 hours and scratching my hair I found the cause for not hitting the break point. After removing 70kb data break point worked as normal.

Does java.util.List.isEmpty() check if the list itself is null?

Invoking any method on any null reference will always result in an exception. Test if the object is null first:

List<Object> test = null;
if (test != null && !test.isEmpty()) {
    // ...
}

Alternatively, write a method to encapsulate this logic:

public static <T> boolean IsNullOrEmpty(Collection<T> list) {
    return list == null || list.isEmpty();
}

Then you can do:

List<Object> test = null;
if (!IsNullOrEmpty(test)) {
    // ...
}

How to center a table of the screen (vertically and horizontally)

This fixes the box dead center on the screen:

HTML

<table class="box" border="1px">
    <tr>
        <td>
            my content
        </td>
    </tr>
</table>

CSS

.box {
    width:300px;
    height:300px;
    background-color:#d9d9d9;
    position:fixed;
    margin-left:-150px; /* half of width */
    margin-top:-150px;  /* half of height */
    top:50%;
    left:50%;
}

View Results

http://jsfiddle.net/bukov/wJ7dY/168/

What is the difference between utf8mb4 and utf8 charsets in MySQL?

The utf8mb4 character set is useful because nowadays we need support for storing not only language characters but also symbols, newly introduced emojis, and so on.

A nice read on How to support full Unicode in MySQL databases by Mathias Bynens can also shed some light on this.

What is Python Whitespace and how does it work?

Every programming language has its own way of structuring the code.
whenever you write a block of code, it has to be organised in a way to be understood by everyone.

Usually used in conditional and classes and defining the definition.
It represents the parent, child and grandchild and further.

Example:

def example()
    print "name"
    print "my name"
example()

Here you can say example() is a parent and others are children.

Converting two lists into a matrix

Simple you can try this

a=list(zip(portfolio, index))

jQuery convert line breaks to br (nl2br equivalent)

you can simply do:

textAreaContent=textAreaContent.replace(/\n/g,"<br>");

Eclipse error: "Editor does not contain a main type"

Try closing and reopening the file, then press Ctrl+F11.

Verify that the name of the file you are running is the same as the name of the project you are working in, and that the name of the public class in that file is the same as the name of the project you are working in as well.

Otherwise, restart Eclipse. Let me know if this solves the problem! Otherwise, comment, and I'll try and help.

How to get script of SQL Server data?

SQL Server Management Studio

This is your best tool for performing this task. You can generate a script that will build whichever tables you wish from a database as well as insert the data in those tables (as far as I know you have to export all of the data in the selected tables however).

To do this follow these steps:

  1. Right-click on your database and select Tasks > Generate Scripts

  2. In the Generate and Publish Scripts wizard, select the "Select specific database objects" option

  3. Expand the "Tables" tree and select all of the tables you wish to export the scheme and data for, then click Next

  4. In the next screen choose how you wish to save the script (the Output Type must remain set as "Save scripts to a specific location"), then click the Advanced button in the top right corner

  5. In the newly opened window, under the General section is a setting called "Types of data to script", set this to "Scheme and data" and click OK

  6. Click Next, review the export summary and click Next again. This will generate the script to your selected destination.

To restore your database, simply create a new database and change the first line of your generated script to USE [Your.New.Database.Name], then execute. Your new database will now have all of the tables and data you selected from the original database.

How to join multiple lines of file names into one with custom delimiter?

EDIT: Simply "ls -m" If you want your delimiter to be a comma

Ah, the power and simplicity !

ls -1 | tr '\n' ','

Change the comma "," to whatever you want. Note that this includes a "trailing comma"

Troubleshooting misplaced .git directory (nothing to commit)

I just had this problem myself because I was in the wrong folder. I was nested 1 level in, so there were no git files to be found.

When I execute cd .. to the correct directory, I was able to commit, as expected.

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

How to decode HTML entities using jQuery?

I just had to have an HTML entity charater (⇓) as a value for a HTML button. The HTML code looks good from the beginning in the browser:

<input type="button" value="Embed & Share  &dArr;" id="share_button" />

Now I was adding a toggle that should also display the charater. This is my solution

$("#share_button").toggle(
    function(){
        $("#share").slideDown();
        $(this).attr("value", "Embed & Share " + $("<div>").html("&uArr;").text());
    }

This displays ⇓ again in the button. I hope this might help someone.

How can I programmatically generate keypress events in C#?

Easily! (because someone else already did the work for us...)

After spending a lot of time trying to this with the suggested answers I came across this codeplex project Windows Input Simulator which made it simple as can be to simulate a key press:

  1. Install the package, can be done or from the NuGet package manager or from the package manager console like:

    Install-Package InputSimulator

  2. Use this 2 lines of code:

    inputSimulator = new InputSimulator() inputSimulator.Keyboard.KeyDown(VirtualKeyCode.RETURN)

And that's it!

-------EDIT--------

The project page on codeplex is flagged for some reason, this is the link to the NuGet gallery.

How to insert newline in string literal?

Well, simple options are:

  • string.Format:

    string x = string.Format("first line{0}second line", Environment.NewLine);
    
  • String concatenation:

    string x = "first line" + Environment.NewLine + "second line";
    
  • String interpolation (in C#6 and above):

    string x = $"first line{Environment.NewLine}second line";
    

You could also use \n everywhere, and replace:

string x = "first line\nsecond line\nthird line".Replace("\n",
                                                         Environment.NewLine);

Note that you can't make this a string constant, because the value of Environment.NewLine will only be available at execution time.

C# DLL config file

It is not trivial to create a .NET configuration file for a .DLL, and for good reason. The .NET configuration mechanism has a lot of features built into it to facilitate easy upgrading/updating of the app, and to protect installed apps from trampling each others configuration files.

There is a big difference between how a DLL is used and how an application is used. You are unlikely to have multiple copies of an application installed on the same machine for the same user. But you may very well have 100 different apps or libraries all making use of some .NET DLL.

Whereas there is rarely a need to track settings separately for different copies of an app within one user profile, it's very unlikely that you would want all of the different usages of a DLL to share configuration with each other. For this reason, when you retrieve a Configuration object using the "normal" method, the object you get back is tied to the configuration of the App Domain you are executing in, rather than the particular assembly.

The App Domain is bound to the root assembly which loaded the assembly which your code is actually in. In most cases this will be the assembly of your main .EXE, which is what loaded up the .DLL. It is possible to spin up other app domains within an application, but you must explicitly provide information on what the root assembly of that app domain is.

Because of all this, the procedure for creating a library-specific config file is not so convenient. It is the same process you would use for creating an arbitrary portable config file not tied to any particular assembly, but for which you want to make use of .NET's XML schema, config section and config element mechanisms, etc. This entails creating an ExeConfigurationFileMap object, loading in the data to identify where the config file will be stored, and then calling ConfigurationManager.OpenMappedExeConfiguration to open it up into a new Configuration instance. This will cut you off from the version protection offered by the automatic path generation mechanism.

Statistically speaking, you're probably using this library in an in-house setting, and it's unlikely you'll have multiple apps making use of it within any one machine/user. But if not, there is something you should keep in mind. If you use a single global config file for your DLL, regardless of the app that is referencing it, you need to worry about access conflicts. If two apps referencing your library happen to be running at the same time, each with their own Configuration object open, then when one saves changes, it will cause an exception next time you try to retrieve or save data in the other app.

The safest and simplest way of getting around this is to require that the assembly which is loading your DLL also provide some information about itself, or to detect it by examining the App Domain of the referencing assembly. Use this to create some sort of folder structure for keeping separate user config files for each app referencing your DLL.

If you are certain you want to have global settings for your DLL no matter where it is referenced, you'll need to determine your location for it rather than .NET figuring out an appropriate one automatically. You'll also need to be aggressive about managing access to the file. You'll need to cache as much as possible, keeping the Configuration instance around ONLY as long as it takes to load or to save, opening immediately before and disposing immediately after. And finally, you'll need a lock mechanism to protect the file while it's being edited by one of the apps that use the library.

Insert variable values in the middle of a string

There's now (C# 6) a more succinct way to do it: string interpolation.

From another question's answer:

In C# 6 you can use string interpolation:

string name = "John";
string result = $"Hello {name}";

The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

Ajax.BeginForm looks to be a fail.

Using a regular Html.Begin for, this does the trick just nicely:

$('#detailsform').submit(function(e) {
    e.preventDefault();
    $.post($(this).attr("action"), $(this).serialize(), function(r) {
        $("#edit").html(r);
    });
}); 

CSS Transition doesn't work with top, bottom, left, right

Perhaps you need to specify a top value in your css rule set, so that it will know what value to animate from.

How to export private key from a keystore of self-signed certificate

http://anandsekar.github.io/exporting-the-private-key-from-a-jks-keystore/

public class ExportPrivateKey {
        private File keystoreFile;
        private String keyStoreType;
        private char[] password;
        private String alias;
        private File exportedFile;

        public static KeyPair getPrivateKey(KeyStore keystore, String alias, char[] password) {
                try {
                        Key key=keystore.getKey(alias,password);
                        if(key instanceof PrivateKey) {
                                Certificate cert=keystore.getCertificate(alias);
                                PublicKey publicKey=cert.getPublicKey();
                                return new KeyPair(publicKey,(PrivateKey)key);
                        }
                } catch (UnrecoverableKeyException e) {
        } catch (NoSuchAlgorithmException e) {
        } catch (KeyStoreException e) {
        }
        return null;
        }

        public void export() throws Exception{
                KeyStore keystore=KeyStore.getInstance(keyStoreType);
                BASE64Encoder encoder=new BASE64Encoder();
                keystore.load(new FileInputStream(keystoreFile),password);
                KeyPair keyPair=getPrivateKey(keystore,alias,password);
                PrivateKey privateKey=keyPair.getPrivate();
                String encoded=encoder.encode(privateKey.getEncoded());
                FileWriter fw=new FileWriter(exportedFile);
                fw.write(“—–BEGIN PRIVATE KEY—–\n“);
                fw.write(encoded);
                fw.write(“\n“);
                fw.write(“—–END PRIVATE KEY—–”);
                fw.close();
        }


        public static void main(String args[]) throws Exception{
                ExportPrivateKey export=new ExportPrivateKey();
                export.keystoreFile=new File(args[0]);
                export.keyStoreType=args[1];
                export.password=args[2].toCharArray();
                export.alias=args[3];
                export.exportedFile=new File(args[4]);
                export.export();
        }
}

How to check if an NSDictionary or NSMutableDictionary contains a key?

As Adirael suggested objectForKey to check key existance but When you call objectForKeyin nullable dictionary, app gets crashed so I fixed this from following way.

- (instancetype)initWithDictionary:(NSDictionary*)dictionary {
id object = dictionary;

if (dictionary && (object != [NSNull null])) {
    self.name = [dictionary objectForKey:@"name"];
    self.age = [dictionary objectForKey:@"age"];
}
return self;

}

Spring Data JPA Update @Query not updating?

The underlying problem here is the 1st level cache of JPA. From the JPA spec Version 2.2 section 3.1. emphasise is mine:

An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance.

This is important because JPA tracks changes to that entity in order to flush them to the database. As a side effect it also means within a single persistence context an entity gets only loaded once. This why reloading the changed entity doesn't have any effect.

You have a couple of options how to handle this:

  1. Evict the entity from the EntityManager. This may be done by calling EntityManager.detach, annotating the updating method with @Modifying(clearAutomatically = true) which evicts all entities. Make sure changes to these entities get flushed first or you might end up loosing changes.

  2. Use EntityManager.refresh().

  3. Use a different persistence context to load the entity. The easiest way to do this is to do it in a separate transaction. With Spring this can be done by having separate methods annotated with @Transactional on beans called from a bean not annotated with @Transactional. Another way is to use a TransactionTemplate which works especially nicely in tests where it makes transaction boundaries very visible.

How to implement a tree data-structure in Java?

Here:

public class Tree<T> {
    private Node<T> root;

    public Tree(T rootData) {
        root = new Node<T>();
        root.data = rootData;
        root.children = new ArrayList<Node<T>>();
    }

    public static class Node<T> {
        private T data;
        private Node<T> parent;
        private List<Node<T>> children;
    }
}

That is a basic tree structure that can be used for String or any other object. It is fairly easy to implement simple trees to do what you need.

All you need to add are methods for add to, removing from, traversing, and constructors. The Node is the basic building block of the Tree.

How to detect control+click in Javascript from an onclick div attribute?

pure javascript:

var ctrlKeyCode = 17;
var cntrlIsPressed = false;

document.addEventListener('keydown', function(event){
    if(event.which=="17")
        cntrlIsPressed = true;
});

document.addEventListener('keyup', function(){
    if(event.which=="17")
        cntrlIsPressed = true;
});



function selectMe(mouseButton)
{
    if(cntrlIsPressed)
    {
        switch(mouseButton)
        {
            case 1:
                alert("Cntrl +  left click");
                break;
            case 2:
                alert("Cntrl + right click");
                break;
            default:
                break;
        }
    }
}

Using sed to mass rename files

The sed command

s/\(.\).\(.*\)/mv & \1\2/

means to replace:

\(.\).\(.*\)

with:

mv & \1\2

just like a regular sed command. However, the parentheses, & and \n markers change it a little.

The search string matches (and remembers as pattern 1) the single character at the start, followed by a single character, follwed by the rest of the string (remembered as pattern 2).

In the replacement string, you can refer to these matched patterns to use them as part of the replacement. You can also refer to the whole matched portion as &.

So what that sed command is doing is creating a mv command based on the original file (for the source) and character 1 and 3 onwards, effectively removing character 2 (for the destination). It will give you a series of lines along the following format:

mv F00001-0708-RG-biasliuyda F0001-0708-RG-biasliuyda
mv abcdef acdef

and so on.

database vs. flat files

What types of files is not mentioned. If they're media files, go ahead with flat files. You probably just need a DB for tags and some way to associate the "external BLOBs" to the records in the DB. But if full text search is something you need, there's no other way to go but migrate to a full DB.

Another thing, your filesystem might provide the ceiling as far as number of physical files are concerned.

Format timedelta to string

timedelta to string, use for print running time info.

def strfdelta_round(tdelta, round_period='second'):
  """timedelta to string,  use for measure running time
  attend period from days downto smaller period, round to minimum period
  omit zero value period  
  """
  period_names = ('day', 'hour', 'minute', 'second', 'millisecond')
  if round_period not in period_names:
    raise Exception(f'round_period "{round_period}" invalid, should be one of {",".join(period_names)}')
  period_seconds = (86400, 3600, 60, 1, 1/pow(10,3))
  period_desc = ('days', 'hours', 'mins', 'secs', 'msecs')
  round_i = period_names.index(round_period)
  
  s = ''
  remainder = tdelta.total_seconds()
  for i in range(len(period_names)):
    q, remainder = divmod(remainder, period_seconds[i])
    if int(q)>0:
      if not len(s)==0:
        s += ' '
      s += f'{q:.0f} {period_desc[i]}'
    if i==round_i:
      break
    if i==round_i+1:
      s += f'{remainder} {period_desc[round_i]}'
      break
    
  return s

e.g. auto omit zero leading period:

>>> td = timedelta(days=0, hours=2, minutes=5, seconds=8, microseconds=3549)
>>> strfdelta_round(td, 'second')
'2 hours 5 mins 8 secs'

or omit middle zero period:

>>> td = timedelta(days=2, hours=0, minutes=5, seconds=8, microseconds=3549)
>>> strfdelta_round(td, 'millisecond')
'2 days 5 mins 8 secs 3 msecs'

or round to minutes, omit below minutes:

>>> td = timedelta(days=1, hours=2, minutes=5, seconds=8, microseconds=3549)
>>> strfdelta_round(td, 'minute')
'1 days 2 hours 5 mins'

Clang vs GCC - which produces faster binaries?

Phoronix did some benchmarks about this, but it is about a snapshot version of Clang/LLVM from a few months back. The results being that things were more-or-less a push; neither GCC nor Clang is definitively better in all cases.

Since you'd use the latest Clang, it's maybe a little less relevant. Then again, GCC 4.6 is slated to have some major optimizations for Core 2 and i7, apparently.

I figure Clang's faster compilation speed will be nicer for original developers, and then when you push the code out into the world, Linux distro/BSD/etc. end-users will use GCC for the faster binaries.

How can I dynamically add a directive in AngularJS?

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

What is trunk, branch and tag in Subversion?

To use Subversion in Visual Studio 2008, install TortoiseSVN and AnkhSVN.

TortoiseSVN is a really easy to use Revision control / version control / source control software for Windows. Since it's not an integration for a specific IDE you can use it with whatever development tools you like. TortoiseSVN is free to use. You don't need to get a loan or pay a full years salary to use it.

AnkhSVN is a Subversion SourceControl Provider for Visual Studio. The software allows you to perform the most common version control operations directly from inside the Microsoft Visual Studio IDE. With AnkhSVN you no longer need to leave your IDE to perform tasks like viewing the status of your source code, updating your Subversion working copy and committing changes. You can even browse your repository and you can plug-in your favorite diff tool.

How to fix error "Updating Maven Project". Unsupported IClasspathEntry kind=4?

This error is also thrown if the update command is used on a project instrumented for code coverage with Clover.

To resolve in this scenario: Un-instrument the project folders you wish to update. Run the maven update then instrument for code coverage again.

How can I get npm start at a different directory?

Below Command where project is a folder which contains package.json file

npm run --prefix project ${COMMAND}

is working as well. Useful in Docker based applications.

Convert String to SecureString

I just want to point out to all the people saying, "That's not the point of SecureString", that many of the people asking this question might be in an application where, for whatever reason, justified or not, they are not particularly concerned about having a temporary copy of the password sit on the heap as a GC-able string, but they have to use an API that only accepts SecureString objects. So, you have an app where you don't care whether the password is on the heap, maybe it's internal-use only and the password is only there because it's required by the underlying network protocols, and you find that that string where the password is stored cannot be used to e.g. set up a remote PowerShell Runspace -- but there is no easy, straight-forward one-liner to create that SecureString that you need. It's a minor inconvenience -- but probably worth it to ensure that the applications that really do need SecureString don't tempt the authors to use System.String or System.Char[] intermediaries. :-)

How do I set the request timeout for one controller action in an asp.net mvc application

I had to add "Current" using .NET 4.5:

HttpContext.Current.Server.ScriptTimeout = 300;

How do I add a linker or compile flag in a CMake file?

Suppose you want to add those flags (better to declare them in a constant):

SET(GCC_COVERAGE_COMPILE_FLAGS "-fprofile-arcs -ftest-coverage")
SET(GCC_COVERAGE_LINK_FLAGS    "-lgcov")

There are several ways to add them:

  1. The easiest one (not clean, but easy and convenient, and works only for compile flags, C & C++ at once):

    add_definitions(${GCC_COVERAGE_COMPILE_FLAGS})
    
  2. Appending to corresponding CMake variables:

    SET(CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}")
    SET(CMAKE_EXE_LINKER_FLAGS  "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS}")
    
  3. Using target properties, cf. doc CMake compile flag target property and need to know the target name.

    get_target_property(TEMP ${THE_TARGET} COMPILE_FLAGS)
    if(TEMP STREQUAL "TEMP-NOTFOUND")
      SET(TEMP "") # Set to empty string
    else()
      SET(TEMP "${TEMP} ") # A space to cleanly separate from existing content
    endif()
    # Append our values
    SET(TEMP "${TEMP}${GCC_COVERAGE_COMPILE_FLAGS}" )
    set_target_properties(${THE_TARGET} PROPERTIES COMPILE_FLAGS ${TEMP} )
    

Right now I use method 2.

Group By Eloquent ORM

Eloquent uses the query builder internally, so you can do:

$users = User::orderBy('name', 'desc')
                ->groupBy('count')
                ->having('count', '>', 100)
                ->get();

How to make certain text not selectable with CSS

Use a simple background image for the textarea suffice.

Or

<div onselectstart="return false">your text</div>

How do I get the path to the current script with Node.js?

I found it after looking through the documentation again. What I was looking for were the __filename and __dirname module-level variables.

  • __filename is the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/kyle/some/dir/file.js)
  • __dirname is the directory name of the current module. (ex:/home/kyle/some/dir)

How to remove RVM (Ruby Version Manager) from my system

For other shell newbies trying to fix the PATH variable

After following instructions in accepted answer, check and modify your PATH variable if necessary :

env | grep PATH 

if you see "rvm" anywhere, you need to figure out where you are setting PATH and modify. I was setting it in 3 files - so check all the following files:

vim .bashrc  

Delete the lines in the file referencing rvm using the dd command. :wq to save and exit.
source .bashrc to "reload"

Repeat this process (starting with the vim command) for .profile and .bash_profile

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

Solution WITHOUT using a png. Based on this SO answer: Adding the little arrow to the right side of a cell in an iPhone TableView Cell

Just flipping the UITableViewCell horizontally!

UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 5, 70, 20)];

// Add the disclosure
CGRect frm;
UITableViewCell *disclosure = [[UITableViewCell alloc] init];
disclosure.transform = CGAffineTransformScale(CGAffineTransformIdentity, -1, 1);
frm = self.btnBack.bounds;
disclosure.frame = CGRectMake(frm.origin.x, frm.origin.y, frm.size.width-25, frm.size.height);
disclosure.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
disclosure.userInteractionEnabled = NO;
[self.btnBack addSubview:disclosure];

// Add the label
UILabel *lbl = [[UILabel alloc] init];
frm = CGRectOffset(self.btnBack.bounds, 15, 0);
lbl.frame = frm;
lbl.textAlignment = NSTextAlignmentCenter;
lbl.text = @"BACK";
[self addSubview:lbl];

How to use Chrome's network debugger with redirects

Another great solution to debug the Network calls before redirecting to other pages is to select the beforeunload event break point

This way you assure to break the flow right before it redirecting it to another page, this way all network calls, network data and console logs are still there.

This solution is best when you want to check what is the response of the calls

Chrome beforeunload event break point

P.S: You can also use XHR break points if you want to stop right before a specific call or any call (see image example) XHR break point

LogCat message: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included

I am encounted this problem when I am using Admob JUST because I forgot to write my Ad Unit ID into @string.

Which terminal command to get just IP address and nothing else?

In man hostname there is even more easier way which automatically excluding loopback IP and showing only space separated list of all assigned to host ip addresses:

root@srv:~# hostname --all-ip-addresses
11.12.13.14 192.168.15.19 

root@srv:~# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
   link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
   inet 127.0.0.1/8 scope host lo
   inet6 ::1/128 scope host 
   valid_lft forever preferred_lft forever
2: venet0: <BROADCAST,POINTOPOINT,NOARP,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN 
  link/void 
  inet 11.12.13.14/32 scope global venet0:0
  inet 192.168.15.19/32 scope global venet0:1

How to capitalize first letter of each word, like a 2-word city?

The JavaScript function:

String.prototype.capitalize = function(){
       return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
      };

To use this function:

capitalizedString = someString.toLowerCase().capitalize();

Also, this would work on multiple words string.

To make sure the converted City name is injected into the database, lowercased and first letter capitalized, then you would need to use JavaScript before you send it over to server side. CSS simply styles, but the actual data would remain pre-styled. Take a look at this jsfiddle example and compare the alert message vs the styled output.

Include another JSP file

1.<a href="index.jsp?p=products">Products</a> when user clicks on Products link,you can directly call products.jsp.

I mean u can maintain name of the JSP file same as parameter Value.

<%
 if(request.getParameter("p")!=null)
 { 
   String contextPath="includes/";
   String p = request.getParameter("p");
   p=p+".jsp";
   p=contextPath+p;

%>    

<%@include file="<%=p%>" %>

<% 
 }
%>

or

2.you can maintain external resource file with key,value pairs. like below

products : products.jsp

customer : customers.jsp

you can programatically retrieve the name of JSP file from properies file.

this way you can easily change the name of JSP file

Set the Value of a Hidden field using JQuery

The selector should not be #input. That means a field with id="input" which is not your case. You want:

$('#chag_sort').val(sort2);

Or if your hidden input didn't have an unique id but only a name="chag_sort":

$('input[name="chag_sort"]').val(sort2);

Convert varchar into datetime in SQL Server

I found this helpful for my conversion, without string manipulation. https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql

CONVERT(VARCHAR(23), @lastUploadEndDate, 121)

yyyy-mm-dd hh:mi:ss.mmm(24h) was the format I needed.

How do I use sudo to redirect output to a location I don't have permission to write to?

Make sudo run a shell, like this:

sudo sh -c "echo foo > ~root/out"

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

In the where criteria add collate SQL_Latin1_General_CP1_CI_AS

This works for me.

WHERE U.Fullname = @SearchTerm  collate SQL_Latin1_General_CP1_CI_AS

Parse date without timezone javascript

simple solution

const handler1 = {
  construct(target, args) {
    let newDate = new target(...args);
    var tzDifference = newDate.getTimezoneOffset();
    return new target(newDate.getTime() + tzDifference * 60 * 1000);
  }
};

Date = new Proxy(Date, handler1);

How to change the href for a hyperlink using jQuery

This snippet invokes when a link of class 'menu_link' is clicked, and shows the text and url of the link. The return false prevents the link from being followed.

<a rel='1' class="menu_link" href="option1.html">Option 1</a>
<a rel='2' class="menu_link" href="option2.html">Option 2</a>

$('.menu_link').live('click', function() {
   var thelink = $(this);
   alert ( thelink.html() );
   alert ( thelink.attr('href') );
   alert ( thelink.attr('rel') );

   return false;
});

Find control by name from Windows Forms controls

Use Control.ControlCollection.Find.

TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";

EDIT for asker:

Control[] tbxs = this.Controls.Find(txtbox_and_message[0,0], true);
if (tbxs != null && tbxs.Length > 0)
{
    tbxs[0].Text = "Found!";
}

How to move up a directory with Terminal in OS X

Typing cd will take you back to your home directory. Whereas typing cd .. will move you up only one directory (the direct parent of the current directory).

Bootstrap 3 .col-xs-offset-* doesn't work?

Alternatively, you can add an empty div for the xs-offset (would save you having to manage the content in more than one place)

<div class="col-xs-1 visible-xs"></div><div class="col-xs-2">col</div>

The bootstrap devs seem to be refusing to add those xs- ofsets and push/pull classes, see here: https://github.com/twbs/bootstrap/issues/9689

How would I create a UIAlertView in Swift?

Click of View

@IBAction func testClick(sender: UIButton) {

  var uiAlert = UIAlertController(title: "Title", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
  self.presentViewController(uiAlert, animated: true, completion: nil)

  uiAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
   println("Click of default button")
  }))

  uiAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { action in
   println("Click of cancel button")
  }))

}

Done with two buttons OK & Cancel

How to upgrade glibc from version 2.13 to 2.15 on Debian?

Your script contains errors as well, for example if you have dos2unix installed your install works but if you don't like I did then it will fail with dependency issues.

I found this by accident as I was making a script file of this to give to my friend who is new to Linux and because I made the scripts on windows I directed him to install it, at the time I did not have dos2unix installed thus I got errors.

here is a copy of the script I made for your solution but have dos2unix installed.

#!/bin/sh
echo "deb http://ftp.debian.org/debian sid main" >> /etc/apt/sources.list
apt-get update
apt-get -t sid install libc6 libc6-dev libc6-dbg
echo "Please remember to hash out sid main from your sources list. /etc/apt/sources.list"

this script has been tested on 3 machines with no errors.

Javascript onclick hide div

HTML

<div id='hideme'><strong>Warning:</strong>These are new products<a href='#' class='close_notification' title='Click to Close'><img src="images/close_icon.gif" width="6" height="6" alt="Close" onClick="hide('hideme')" /></a

Javascript:

function hide(obj) {

    var el = document.getElementById(obj);

        el.style.display = 'none';

}

In javascript, how do you search an array for a substring match

People here are making this waaay too difficult. Just do the following...

myArray.findIndex(element => element.includes("substring"))

findIndex() is an ES6 higher order method that iterates through the elements of an array and returns the index of the first element that matches some criteria (provided as a function). In this case I used ES6 syntax to declare the higher order function. element is the parameter of the function (which could be any name) and the fat arrow declares what follows as an anonymous function (which does not need to be wrapped in curly braces unless it takes up more than one line).

Within findIndex() I used the very simple includes() method to check if the current element includes the substring that you want.

Service located in another namespace

To access services in two different namespaces you can use url like this:

HTTP://<your-service-name>.<namespace-with-that-service>.svc.cluster.local

To list out all your namespaces you can use:

kubectl get namespace

And for service in that namespace you can simply use:

kubectl get services -n <namespace-name>

this will help you.

Android WebView not loading an HTTPS URL

In case you want to use the APK outside the Google Play Store, e.g., private a solution like the following will probably work:

    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        /*...*/
        handler.proceed();
    }

In case you want to add an additional optional layer of security, you can try to make use of certificate pinning. IMHO this is not necessary for private or internal usage tough.

If you plan to publish the app on the Google Play Store, then you should avoid @Override onReceivedSslError(...){...}. Especially making use of handler.proceed(). Google will find this code snippet and will reject your app for sure since the solution with handler.proceed() will suppress all kinds of built-in security mechanisms.

And just because of the fact that browsers do not complain about your https connection, it does not mean that the SSL certificate itself is trusted at all!

In my case, the SSL certificate chain was broken. You can quickly test such issues with SSL Checker or more intermediate with SSLLabs. But please do not ask me how this can happen. I have absolutely no clue.

Anyway, after reinstalling the SSL certificate, all errors regarding the "untrusted SSL certificate in WebView whatsoever" disappeared finally. I also removed the @Override for onReceivedSslError(...) and got rid of handler.proceed(), and é voila my app was not rejected by Google Play Store (again).

How to export dataGridView data Instantly to Excel on button click?

that's what i use for my gridview, try to use it for yr data , it works perfectly :

        GridView1.AllowPaging = false;
        GridView1.DataBind();

        StringBuilder sb = new StringBuilder();

        for (int k = 0; k < GridView1.Columns.Count; k++)
        {
            //add separator
            sb.Append(GridView1.Columns[k].HeaderText+";");

        }


        //append new line
        sb.Append("\r\n");
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            for (int k = 0; k < GridView1.Columns.Count; k++)
            {
                sb.Append(GridView1.Rows[i].Cells[k].Text+";");
            }
            sb.AppendLine();
        }

How to indent a few lines in Markdown markup?

On gitlab.com a single en space (U+2002) followed by a single em space (U+2003) works decently.

Presumably other repetitions or combinations of not-exactly-accounted-for space characters would also suffice.

Getting Keyboard Input

You can use Scanner to get the next line and do whatever you need to do with the line entered. You can also use JOptionPane to popup a dialog asking for inputs.

Scanner example:

Scanner input = new Scanner(System.in);
System.out.print("Enter something > ");
String inputString = input.nextLine();
System.out.print("You entered : ");
System.out.println(inputString);

JOptionPane example:

String input = JOptionPane.showInputDialog(null,
     "Enter some text:");
JOptionPane.showMessageDialog(null,"You entered "+ input);

You will need these imports:

import java.util.Scanner;
import javax.swing.JOptionPane;

A complete Java class of the above

import java.util.Scanner;
import javax.swing.JOptionPane;
public class GetInputs{
    public static void main(String args[]){
        //Scanner example
        Scanner input = new Scanner(System.in);
        System.out.print("Enter something > ");
        String inputString = input.nextLine();
        System.out.print("You entered : ");
        System.out.println(inputString);

        //JOptionPane example
        String input = JOptionPane.showInputDialog(null,
        "Enter some text:");
        JOptionPane.showMessageDialog(null,"You entered "+ input);
    }
}

String to date in Oracle with milliseconds

Oracle stores only the fractions up to second in a DATE field.

Use TIMESTAMP instead:

SELECT  TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM    dual

, possibly casting it to a DATE then:

SELECT  CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM    dual

Printing Lists as Tabular Data

>>> import pandas
>>> pandas.DataFrame(data, teams_list, teams_list)
           Man Utd  Man City  T Hotspur
Man Utd    1        2         1        
Man City   0        1         0        
T Hotspur  2        4         2        

Verify External Script Is Loaded

If the script creates any variables or functions in the global space you can check for their existance:

External JS (in global scope) --

var myCustomFlag = true;

And to check if this has run:

if (typeof window.myCustomFlag == 'undefined') {
    //the flag was not found, so the code has not run
    $.getScript('<external JS>');
}

Update

You can check for the existence of the <script> tag in question by selecting all of the <script> elements and checking their src attributes:

//get the number of `<script>` elements that have the correct `src` attribute
var len = $('script').filter(function () {
    return ($(this).attr('src') == '<external JS>');
}).length;

//if there are no scripts that match, the load it
if (len === 0) {
    $.getScript('<external JS>');
}

Or you can just bake this .filter() functionality right into the selector:

var len = $('script[src="<external JS>"]').length;

Receive result from DialogFragment

There is a much simpler way to receive a result from a DialogFragment.

First, in your Activity, Fragment, or FragmentActivity you need to add in the following information:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Stuff to do, dependent on requestCode and resultCode
    if(requestCode == 1) { // 1 is an arbitrary number, can be any int
         // This is the return result of your DialogFragment
         if(resultCode == 1) { // 1 is an arbitrary number, can be any int
              // Now do what you need to do after the dialog dismisses.
         }
     }
}

The requestCode is basically your int label for the DialogFragment you called, I'll show how this works in a second. The resultCode is the code that you send back from the DialogFragment telling your current waiting Activity, Fragment, or FragmentActivity what happened.

The next piece of code to go in is the call to the DialogFragment. An example is here:

DialogFragment dialogFrag = new MyDialogFragment();
// This is the requestCode that you are sending.
dialogFrag.setTargetFragment(this, 1);     
// This is the tag, "dialog" being sent.
dialogFrag.show(getFragmentManager(), "dialog");

With these three lines you are declaring your DialogFragment, setting a requestCode (which will call the onActivityResult(...) once the Dialog is dismissed, and you are then showing the dialog. It's that simple.

Now, in your DialogFragment you need to just add one line directly before the dismiss() so that you send a resultCode back to the onActivityResult().

getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, getActivity().getIntent());
dismiss();

That's it. Note, the resultCode is defined as int resultCode which I've set to resultCode = 1; in this case.

That's it, you can now send the result of your DialogFragment back to your calling Activity, Fragment, or FragmentActivity.

Also, it looks like this information was posted previously, but there wasn't a sufficient example given so I thought I'd provide more detail.

EDIT 06.24.2016 I apologize for the misleading code above. But you most certainly cannot receive the result back to the activity seeing as the line:

dialogFrag.setTargetFragment(this, 1);

sets a target Fragment and not Activity. So in order to do this you need to use implement an InterfaceCommunicator.

In your DialogFragment set a global variable

public InterfaceCommunicator interfaceCommunicator;

Create a public function to handle it

public interface InterfaceCommunicator {
    void sendRequestCode(int code);
}

Then when you're ready to send the code back to the Activity when the DialogFragment is done running, you simply add the line before you dismiss(); your DialogFragment:

interfaceCommunicator.sendRequestCode(1); // the parameter is any int code you choose.

In your activity now you have to do two things, the first is to remove that one line of code that is no longer applicable:

dialogFrag.setTargetFragment(this, 1);  

Then implement the interface and you're all done. You can do that by adding the following line to the implements clause at the very top of your class:

public class MyClass Activity implements MyDialogFragment.InterfaceCommunicator

And then @Override the function in the activity,

@Override
public void sendRequestCode(int code) {
    // your code here
}

You use this interface method just like you would the onActivityResult() method. Except the interface method is for DialogFragments and the other is for Fragments.

Convert audio files to mp3 using ffmpeg

Never mind,

I am converting my audio files to mp2 by using the command:

ffmpeg -i input.wav -f mp2 output.mp3

This command works perfectly.

I know that this actually converts the files to mp2 format, but then the resulting file sizes are the same..

Angular 4/5/6 Global Variables

Not really recommended but none of the other answers are really global variables. For a truly global variable you could do this.

Index.html

<body>
  <app-root></app-root>
  <script>
    myTest = 1;
  </script>
</body>

Component or anything else in Angular

..near the top right after imports:

declare const myTest: any;

...later:

console.warn(myTest); // outputs '1'

How to delete all files older than 3 days when "Argument list too long"?

Another solution for the original question, esp. useful if you want to remove only SOME of the older files in a folder, would be smth like this:

find . -name "*.sess" -mtime +100 

and so on.. Quotes block shell wildcards, thus allowing you to "find" millions of files :)

Tricks to manage the available memory in an R session

I make aggressive use of the subset parameter with selection of only the required variables when passing dataframes to the data= argument of regression functions. It does result in some errors if I forget to add variables to both the formula and the select= vector, but it still saves a lot of time due to decreased copying of objects and reduces the memory footprint significantly. Say I have 4 million records with 110 variables (and I do.) Example:

# library(rms); library(Hmisc) for the cph,and rcs functions
Mayo.PrCr.rbc.mdl <- 
cph(formula = Surv(surv.yr, death) ~ age + Sex + nsmkr + rcs(Mayo, 4) + 
                                     rcs(PrCr.rat, 3) +  rbc.cat * Sex, 
     data = subset(set1HLI,  gdlab2 & HIVfinal == "Negative", 
                           select = c("surv.yr", "death", "PrCr.rat", "Mayo", 
                                      "age", "Sex", "nsmkr", "rbc.cat")
   )            )

By way of setting context and the strategy: the gdlab2 variable is a logical vector that was constructed for subjects in a dataset that had all normal or almost normal values for a bunch of laboratory tests and HIVfinal was a character vector that summarized preliminary and confirmatory testing for HIV.

Check if a string contains a string in C++

Actually, you can try to use boost library,I think std::string doesn't supply enough method to do all the common string operation.In boost,you can just use the boost::algorithm::contains:

#include <string>
#include <boost/algorithm/string.hpp>

int main() {
    std::string s("gengjiawen");
    std::string t("geng");
    bool b = boost::algorithm::contains(s, t);
    std::cout << b << std::endl;
    return 0;
}

MessageBox with YesNoCancel - No & Cancel triggers same event

This is how you can do it without a Dim, using MessageBox.Show instead of MsgBox. This is in my opinion the cleanest way of writing it!

Select Case MessageBox.Show("Message", "Title", MessageBoxButtons.YesNo)
    Case vbYes
        ' Other Code goes here
    Case vbNo
        ' Other Code goes here
End Select

You can shorten it down even further by using If:

If MessageBox.Show("Message", "Title", MessageBoxButtons.YesNo) = vbYes Then
    ' Other Code goes here
End If

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

codes need to save UTF8 without BOM while recording. Sometimes, written codes with (Notepad++) or other coding tools and use UTF8 encode, this error occurs. I'm sorry, I do not know English. This is just my experience.

Java: How to check if object is null?

drawable.equals(null)

The above line calls the "equals(...)" method on the drawable object.

So, when drawable is not null and it is a real object, then all goes well as calling the "equals(null)" method will return "false"

But when "drawable" is null, then it means calling the "equals(...)" method on null object, means calling a method on an object that doesn't exist so it throws "NullPointerException"

To check whether an object exists and it is not null, use the following

if(drawable == null) {
    ...
    ...
}

In above condition, we are checking that the reference variable "drawable" is null or contains some value (reference to its object) so it won't throw exception in case drawable is null as checking

null == null

is valid.

Set value for particular cell in pandas DataFrame with iloc

One thing I would add here is that the at function on a dataframe is much faster particularly if you are doing a lot of assignments of individual (not slice) values.

df.at[index, 'col_name'] = x

In my experience I have gotten a 20x speedup. Here is a write up that is Spanish but still gives an impression of what's going on.

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

You should run your entire script as superuser. If you want to run some command as non-superuser, use "-u" option of sudo:

#!/bin/bash

sudo -u username command1
command2
sudo -u username command3
command4

When running as root, sudo doesn't ask for a password.

How to go up a level in the src path of a URL in HTML?

Use ../:

background-image: url('../images/bg.png');

You can use that as often as you want, e.g. ../../images/ or even at different positions, e.g. ../images/../images/../images/ (same as ../images/ of course)

SQL Server 2008 Row Insert and Update timestamps

try

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    [CreateTS] [smalldatetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [smalldatetime] NOT NULL

)

PS I think a smalldatetime is good enough. You may decide differently.

Can you not do this at the "moment of impact" ?

In Sql Server, this is common:

Update dbo.MyTable 
Set 

ColA = @SomeValue , 
UpdateDS = CURRENT_TIMESTAMP
Where...........

Sql Server has a "timestamp" datatype.

But it may not be what you think.

Here is a reference:

http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx

Here is a little RowVersion (synonym for timestamp) example:

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)


INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Maybe a complete working example:

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER INSERT, UPDATE
AS

BEGIN

Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where 
triggerInsertedTable.Name = myAlias.Name

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Matching on the "Name" value is probably not wise.

Try this more mainstream example with a SurrogateKey

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    SurrogateKey int not null Primary Key Identity (1001,1),
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER UPDATE
AS

BEGIN

   UPDATE dbo.Names
    SET UpdateTS = CURRENT_TIMESTAMP
    From  dbo.Names myAlias
    WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

How to set default vim colorscheme

It's as simple as adding a line to your ~/.vimrc:

colorscheme color_scheme_name

How to cast List<Object> to List<MyClass>

you can always cast any object to any type by up-casting it to Object first. in your case:

(List<Customer>)(Object)list; 

you must be sure that at runtime the list contains nothing but Customer objects.

Critics say that such casting indicates something wrong with your code; you should be able to tweak your type declarations to avoid it. But Java generics is too complicated, and it is not perfect. Sometimes you just don't know if there is a pretty solution to satisfy the compiler, even though you know very well the runtime types and you know what you are trying to do is safe. In that case, just do the crude casting as needed, so you can leave work for home.

How to write and save html file in python?

You can try:

colour = ["red", "red", "green", "yellow"]

with open('mypage.html', 'w') as myFile:
    myFile.write('<html>')
    myFile.write('<body>')
    myFile.write('<table>')

    s = '1234567890'
    for i in range(0, len(s), 60):
        myFile.write('<tr><td>%04d</td>' % (i+1));
    for j, k in enumerate(s[i:i+60]):
        myFile.write('<td><font style="background-color:%s;">%s<font></td>' % (colour[j %len(colour)], k));


    myFile.write('</tr>')
    myFile.write('</table>')
    myFile.write('</body>')
    myFile.write('</html>')

jquery get all input from specific form

Use HTML Form "elements" attribute:

$.each($("form").elements, function(){ 
    console.log($(this));
    });

Now it's not necessary to provide such names as "input, textarea, select ..." etc.

Difference between HttpModule and HttpClientModule

This is a good reference, it helped me switch my http requests to httpClient.

It compares the two in terms of differences and gives code examples.

This is just a few differences I dealt with while changing services to httpclient in my project (borrowing from the article I mentioned) :

Importing

import {HttpModule} from '@angular/http';
import {HttpClientModule} from '@angular/common/http';

Requesting and parsing response:

@angular/http

 this.http.get(url)
      // Extract the data in HTTP Response (parsing)
      .map((response: Response) => response.json() as GithubUser)
      .subscribe((data: GithubUser) => {
        // Display the result
        console.log('TJ user data', data);
      });

@angular/common/http

 this.http.get(url)
      .subscribe((data: GithubUser) => {
        // Data extraction from the HTTP response is already done
        // Display the result
        console.log('TJ user data', data);
      });

Note: You no longer have to extract the returned data explicitly; by default, if the data you get back is type of JSON, then you don't have to do anything extra.

But, if you need to parse any other type of response like text or blob, then make sure you add the responseType in the request. Like so:

Making the GET HTTP request with responseType option:

 this.http.get(url, {responseType: 'blob'})
      .subscribe((data) => {
        // Data extraction from the HTTP response is already done
        // Display the result
        console.log('TJ user data', data);
      });

Adding Interceptor

I also used interceptors for adding the token for my authorization to every request, reference.

like so:

@Injectable()
export class MyFirstInterceptor implements HttpInterceptor {

    constructor(private currentUserService: CurrentUserService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        // get the token from a service
        const token: string = this.currentUserService.token;

        // add it if we have one
        if (token) {
            req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
        }

        // if this is a login-request the header is 
        // already set to x/www/formurl/encoded. 
        // so if we already have a content-type, do not 
        // set it, but if we don't have one, set it to 
        // default --> json
        if (!req.headers.has('Content-Type')) {
            req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
        }

        // setting the accept header
        req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
        return next.handle(req);
    }
}

Its a pretty nice upgrade!

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

I suspect that you have two tables with the same name. One is owned by the schema 'dbo' (dbo.PerfDiag), and the other is owned by the default schema of the account used to connect to SQL Server (something like userid.PerfDiag).

When you have an unqualified reference to a schema object (such as a table) — one not qualified by schema name — the object reference must be resolved. Name resolution occurs by searching in the following sequence for an object of the appropriate type (table) with the specified name. The name resolves to the first match:

  • Under the default schema of the user.
  • Under the schema 'dbo'.

The unqualified reference is bound to the first match in the above sequence.

As a general recommended practice, one should always qualify references to schema objects, for performance reasons:

  • An unqualified reference may invalidate a cached execution plan for the stored procedure or query, since the schema to which the reference was bound may change depending on the credentials executing the stored procedure or query. This results in recompilation of the query/stored procedure, a performance hit. Recompilations cause compile locks to be taken out, blocking others from accessing the needed resource(s).

  • Name resolution slows down query execution as two probes must be made to resolve to the likely version of the object (that owned by 'dbo'). This is the usual case. The only time a single probe will resolve the name is if the current user owns an object of the specified name and type.

[Edited to further note]

The other possibilities are (in no particular order):

  • You aren't connected to the database you think you are.
  • You aren't connected to the SQL Server instance you think you are.

Double check your connect strings and ensure that they explicitly specify the SQL Server instance name and the database name.

Python: How to convert datetime format?

>>> import datetime
>>> d = datetime.datetime.strptime('2011-06-09', '%Y-%m-%d')
>>> d.strftime('%b %d,%Y')
'Jun 09,2011'

In pre-2.5 Python, you can replace datetime.strptime with time.strptime, like so (untested): datetime.datetime(*(time.strptime('2011-06-09', '%Y-%m-%d')[0:6]))

Git diff between current branch and master but not including unmerged master commits

git diff `git merge-base master branch`..branch

Merge base is the point where branch diverged from master.

Git diff supports a special syntax for this:

git diff master...branch

You must not swap the sides because then you would get the other branch. You want to know what changed in branch since it diverged from master, not the other way round.

Loosely related:


Note that .. and ... syntax does not have the same semantics as in other Git tools. It differs from the meaning specified in man gitrevisions.

Quoting man git-diff:

  • git diff [--options] <commit> <commit> [--] [<path>…]

    This is to view the changes between two arbitrary <commit>.

  • git diff [--options] <commit>..<commit> [--] [<path>…]

    This is synonymous to the previous form. If <commit> on one side is omitted, it will have the same effect as using HEAD instead.

  • git diff [--options] <commit>...<commit> [--] [<path>…]

    This form is to view the changes on the branch containing and up to the second <commit>, starting at a common ancestor of both <commit>. "git diff A...B" is equivalent to "git diff $(git-merge-base A B) B". You can omit any one of <commit>, which has the same effect as using HEAD instead.

Just in case you are doing something exotic, it should be noted that all of the <commit> in the above description, except in the last two forms that use ".." notations, can be any <tree>.

For a more complete list of ways to spell <commit>, see "SPECIFYING REVISIONS" section in gitrevisions[7]. However, "diff" is about comparing two endpoints, not ranges, and the range notations ("<commit>..<commit>" and "<commit>...<commit>") do not mean a range as defined in the "SPECIFYING RANGES" section in gitrevisions[7].

How to convert an integer to a string in any base?

Strings aren't the only choice for representing numbers: you can use a list of integers to represent the order of each digit. Those can easily be converted to a string.

None of the answers reject base < 2; and most will run very slowly or crash with stack overflows for very large numbers (such as 56789 ** 43210). To avoid such failures, reduce quickly like this:

def n_to_base(n, b):
    if b < 2: raise # invalid base
    if abs(n) < b: return [n]
    ret = [y for d in n_to_base(n, b*b) for y in divmod(d, b)]
    return ret[1:] if ret[0] == 0 else ret # remove leading zeros

def base_to_n(v, b):
    h = len(v) // 2
    if h == 0: return v[0]
    return base_to_n(v[:-h], b) * (b**h) + base_to_n(v[-h:], b)

assert ''.join(['0123456789'[x] for x in n_to_base(56789**43210,10)])==str(56789**43210)

Speedwise, n_to_base is comparable with str for large numbers (about 0.3s on my machine), but if you compare against hex you may be surprised (about 0.3ms on my machine, or 1000x faster). The reason is because the large integer is stored in memory in base 256 (bytes). Each byte can simply be converted to a two-character hex string. This alignment only happens for bases that are powers of two, which is why there are special cases for 2,8, and 16 (and base64, ascii, utf16, utf32).

Consider the last digit of a decimal string. How does it relate to the sequence of bytes that forms its integer? Let's label the bytes s[i] with s[0] being the least significant (little endian). Then the last digit is sum([s[i]*(256**i) % 10 for i in range(n)]). Well, it happens that 256**i ends with a 6 for i > 0 (6*6=36) so that last digit is (s[0]*5 + sum(s)*6)%10. From this, you can see that the last digit depends on the sum of all the bytes. This nonlocal property is what makes converting to decimal harder.

What's the difference between 'int?' and 'int' in C#?

int? is shorthand for Nullable<int>.

This may be the post you were looking for.

WPF Check box: Check changed handling

What about the Checked event? Combine that with AttachedCommandBehaviors or something similar, and a DelegateCommand to get a function fired in your viewmodel everytime that event is called.

Show/Hide the console window of a C# console application

Here’s how:

using System.Runtime.InteropServices;

[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

const int SW_HIDE = 0;
const int SW_SHOW = 5;

var handle = GetConsoleWindow();

// Hide
ShowWindow(handle, SW_HIDE);

// Show
ShowWindow(handle, SW_SHOW);

Get month and year from date cells Excel

You could right click on those cells, go to format, select custom, then type mm yyyy.

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

On delete cascade with doctrine2

There are two kinds of cascades in Doctrine:

1) ORM level - uses cascade={"remove"} in the association - this is a calculation that is done in the UnitOfWork and does not affect the database structure. When you remove an object, the UnitOfWork will iterate over all objects in the association and remove them.

2) Database level - uses onDelete="CASCADE" on the association's joinColumn - this will add On Delete Cascade to the foreign key column in the database:

@ORM\JoinColumn(name="father_id", referencedColumnName="id", onDelete="CASCADE")

I also want to point out that the way you have your cascade={"remove"} right now, if you delete a Child object, this cascade will remove the Parent object. Clearly not what you want.

Read url to string in few lines of java code

If your url is of type java.net.URL, then you can just convert it to uri and then to string

url.toURI().toString()

C# - Simplest way to remove first occurrence of a substring from another string

If you'd like a simple method to resolve this problem. (Can be used as an extension)

See below:

    public static string RemoveFirstInstanceOfString(this string value, string removeString)
    {
        int index = value.IndexOf(removeString, StringComparison.Ordinal);
        return index < 0 ? value : value.Remove(index, removeString.Length);
    }

Usage:

    string valueWithPipes = "| 1 | 2 | 3";
    string valueWithoutFirstpipe = valueWithPipes.RemoveFirstInstanceOfString("|");
    //Output, valueWithoutFirstpipe = " 1 | 2 | 3";

Inspired by and modified @LukeH's and @Mike's answer.

Don't forget the StringComparison.Ordinal to prevent issues with Culture settings. https://www.jetbrains.com/help/resharper/2018.2/StringIndexOfIsCultureSpecific.1.html

Get selected option from select element

Using the selectedOptions property (HTML5) you can get the selected option(s)

document.getElementbyId("id").selectedOptions; 

With JQuery can be achieved by doing this

$("#id")[0].selectedOptions; 

or

$("#id").prop("selectedOptions");

The property contains an HTMLCollection array similitar to this one selected option

[<option value=?"1">?ABC</option>]

or multiple selections

[<option value=?"1">?ABC</option>, <option value=?"2">?DEF</option> ...]

HTML/CSS - Adding an Icon to a button

<a href="#" class="btnTest">Test</a>


.btnTest{
   background:url('images/icon.png') no-repeat left center;
   padding-left:20px;
}    

Why doesn't JavaScript support multithreading?

As far as I have heared Google Chrome will have multithreaded javascript, so it is a "current implementations" problem.

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

Another way to do this is:

// inflate the layout
View myLayout = LayoutInflater.from(this).inflate(R.layout.MY_LAYOUT,null);

// load the text view
TextView myView = (TextView) myLayout.findViewById(R.id.MY_VIEW);

Convert Pixels to Points

There are 72 points per inch; if it is sufficient to assume 96 pixels per inch, the formula is rather simple:

points = pixels * 72 / 96

There is a way to get the configured pixels per inch of your display in Windows using GetDeviceCaps. Microsoft has a guide called "Developing DPI-Aware Applications", look for the section "Creating DPI-Aware Fonts".

The W3C has defined the pixel measurement px as exactly 1/96th of 1in regardless of the actual resolution of your display, so the above formula should be good for all web work.

trigger click event from angularjs directive

This is an extension to Langdon's answer with a directive approach to the problem. If you're going to have multiple galleries on the page this may be one way to go about it without much fuss.

Usage:

<gallery images="items"></gallery>
<gallery images="cats"></gallery>

See it working here

What are the Android SDK build-tools, platform-tools and tools? And which version should be used?

You can find details about these in this Android - Command Line Tools


tl;dr:

SDK Tools:

  1. Android SDK Manager (sdkmanager)
  2. AVD Manager (avdmanager)
  3. Dalvik Debug Monitor Server (ddms)

Build Tools:

  1. signer
  2. proGuard
  3. zipalign
  4. jobb

Platform Tools:

  1. adb
  2. aidl, aapt, dexdump, and dx
  3. bmgr
  4. logcat

How to serve up a JSON response using Go?

You may use this package renderer, I have written to solve this kind of problem, it's a wrapper to serve JSON, JSONP, XML, HTML etc.

Securely storing passwords for use in python script

the secure way is encrypt your sensitive data by AES and the encryption key is derivation by password-based key derivation function (PBE), the master password used to encrypt/decrypt the encrypt key for AES.

master password -> secure key-> encrypt data by the key

You can use pbkdf2

from PBKDF2 import PBKDF2
from Crypto.Cipher import AES
import os
salt = os.urandom(8)    # 64-bit salt
key = PBKDF2("This passphrase is a secret.", salt).read(32) # 256-bit key
iv = os.urandom(16)     # 128-bit IV
cipher = AES.new(key, AES.MODE_CBC, iv)

make sure to store the salt/iv/passphrase , and decrypt using same salt/iv/passphase

Weblogic used similar approach to protect passwords in config files

what is Array.any? for javascript

If you really want to got nuts, add a new method to the prototype:

if (!('empty' in Array.prototype)) {
  Array.prototype.empty = function () {
    return this.length === 0;
  };
}

[1, 2].empty() // false
[].empty() // true

DEMO

How to debug a referenced dll (having pdb)

Make sure your DLL is not registered in the GAC. Visual Studio will use the version in the GAC and it will probably have no debugging information.

How to find the parent element using javascript

Use the change event of the select:

$('#my_select').change(function()
{
   $(this).parents('td').css('background', '#000000');
});

How to change an element's title attribute using jQuery

Another option, if you prefer, would be to get the DOM element from the jQuery object and use standard DOM accessors on it:

$("#myElement")[0].title = "new title value";

The "jQuery way", as mentioned by others, is to use the attr() method. See the API documentation for attr() here.

An error occurred while signing: SignTool.exe not found

I needed Signing hence couldn't un-check as suggested.

Then goto Control Panel -> Programs and Features -> Microsoft Visual Studio 2015 Click Change then the installer will load and you need to click Modify to add ClickOnce Publishing Tools feature.

Check if element is visible in DOM

The accepted answer did not worked for me.

Year 2020 breakdown.

  1. The (elem.offsetParent !== null) method works fine in Firefox but not in Chrome. In Chrome position: fixed will also make offsetParent return null even the element if visible in the page.

    User Phrogz conducted a large test (2,304 divs) on elements with varying properties to demonstrate the issue. https://stackoverflow.com/a/11639664/4481831 . Run it with multiple browsers to see the differences.

    Demo:

    _x000D_
    _x000D_
    //different results in Chrome and Firefox
    console.log(document.querySelector('#hidden1').offsetParent); //null Chrome & Firefox
    console.log(document.querySelector('#fixed1').offsetParent); //null in Chrome, not null in Firefox
    _x000D_
        <div id="hidden1" style="display:none;"></div>
        <div id="fixed1" style="position:fixed;"></div>
    _x000D_
    _x000D_
    _x000D_

  2. The (getComputedStyle(elem).display !== 'none') does not work because the element can be invisible because one of the parents display property is set to none, getComputedStyle will not catch that.

    Demo:

    _x000D_
    _x000D_
    var child1 = document.querySelector('#child1');
    console.log(getComputedStyle(child1).display);
    //child will show "block" instead of "none"
    _x000D_
    <div id="parent1" style="display:none;">
      <div id="child1" style="display:block"></div>
    </div>
    _x000D_
    _x000D_
    _x000D_

  3. The (elem.clientHeight !== 0). This method is not influenced by position: fixed and it also check if element parents are not-visible. But it has problems with simple elements that do not have a css layout, see more here

    Demo:

    _x000D_
    _x000D_
    console.log(document.querySelector('#div1').clientHeight); //not zero
    console.log(document.querySelector('#span1').clientHeight); //zero
    _x000D_
    <div id="div1">test1 div</div>
    <span id="span1">test2 span</span>
    _x000D_
    _x000D_
    _x000D_

  4. The (elem.getClientRects().length !== 0) may seem to solve the problems of the previous 3 methods. However it has problems with elements that use CSS tricks (other then display: none) to hide in the page.

    Demo

    _x000D_
    _x000D_
    console.log(document.querySelector('#notvisible1').getClientRects().length);
    console.log(document.querySelector('#notvisible1').clientHeight);
    console.log(document.querySelector('#notvisible2').getClientRects().length);
    console.log(document.querySelector('#notvisible2').clientHeight);
    console.log(document.querySelector('#notvisible3').getClientRects().length);
    console.log(document.querySelector('#notvisible3').clientHeight);
    _x000D_
    <div id="notvisible1" style="height:0; overflow:hidden; background-color:red;">not visible 1</div>
    
    <div id="notvisible2" style="visibility:hidden; background-color:yellow;">not visible 2</div>
    
    <div id="notvisible3" style="opacity:0; background-color:blue;">not visible 3</div>
    _x000D_
    _x000D_
    _x000D_

Conclusion.

So what I have showed you is that no method is perfect. To make a proper visibility check, you must use a combination of the last 3 methods.

How to get filename without extension from file path in Ruby

require 'pathname'

Pathname.new('/opt/local/bin/ruby').basename
# => #<Pathname:ruby>

I haven't been a Windows user in a long time, but the Pathname rdoc says it has no issues with directory-name separators on Windows.

C#: HttpClient with POST parameters

A cleaner alternative would be to use a Dictionary to handle parameters. They are key-value pairs after all.

private static readonly HttpClient httpclient;

static MyClassName()
{
    // HttpClient is intended to be instantiated once and re-used throughout the life of an application. 
    // Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. 
    // This will result in SocketException errors.
    // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
    httpclient = new HttpClient();    
} 

var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);

var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
    // Do something with response. Example get content:
    // var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}

Also dont forget to Dispose() httpclient, if you dont use the keyword using

As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.

Edit:

You may want to look into response.EnsureSuccessStatusCode(); instead of if (response.StatusCode == HttpStatusCode.OK).

You may want to keep your httpclient and dont Dispose() it. See: Do HttpClient and HttpClientHandler have to be disposed?

Edit:

Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html

How to keep the header static, always on top while scrolling?

Instead of working with positioning and padding/margin and without knowing the header's size, there's a way to keep the header fixed by playing with the scroll.

See the this plunker with a fixed header:

<html lang="en" style="height: 100%">
<body style="height: 100%">
<div style="height: 100%; overflow: hidden">
  <div>Header</div>
  <div style="height: 100%; overflow: scroll">Content - very long Content...

The key here is a mix of height: 100% with overflow.

See a specific question on removing the scroll from the header here and answer here.

How do I disable directory browsing?

Apart from the aformentioned two methods (edit /etc/apache2/apache2.conf or add Options -Indexes in .htaccess file), here is another one

a2dismod autoindex

Restart the apache2 server afterwards

sudo service apache2 restart

Why is using the JavaScript eval function a bad idea?

eval() is very powerful and can be used to execute a JS statement or evaluate an expression. But the question isn't about the uses of eval() but lets just say some how the string you running with eval() is affected by a malicious party. At the end you will be running malicious code. With power comes great responsibility. So use it wisely is you are using it. This isn't related much to eval() function but this article has pretty good information: http://blogs.popart.com/2009/07/javascript-injection-attacks/ If you are looking for the basics of eval() look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval

Save bitmap to location

After Android 4.4 Kitkat, and as of 2017 share of Android 4.4 and less is about 20% and decreasing, it's not possible to save to SD card using File class and getExternalStorageDirectory() method. This method returns your device internal memory and images save visible to every app. You can also save images only private to your app and to be deleted when user deletes your app with openFileOutput() method.

Starting with Android 6.0, you can format your SD card as an internal memory but only private to your device.(If you format SD car as internal memory, only your device can access or see it's contents) You can save to that SD card using other answers but if you want to use a removable SD card you should read my answer below.

You should use Storage Access Framework to get uri to folder onActivityResult method of activity to get folder selected by user, and add retreive persistiable permission to be able to access folder after user restarts the device.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {

        // selectDirectory() invoked
        if (requestCode == REQUEST_FOLDER_ACCESS) {

            if (data.getData() != null) {
                Uri treeUri = data.getData();
                tvSAF.setText("Dir: " + data.getData().toString());
                currentFolder = treeUri.toString();
                saveCurrentFolderToPrefs();

                // grantUriPermission(getPackageName(), treeUri,
                // Intent.FLAG_GRANT_READ_URI_PERMISSION |
                // Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

                final int takeFlags = data.getFlags()
                        & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                // Check for the freshest data.
                getContentResolver().takePersistableUriPermission(treeUri, takeFlags);

            }
        }
    }
}

Now, save save folder to shared preferences not to ask user to select folder every time you want to save an image.

You should use DocumentFile class to save your image, not File or ParcelFileDescriptor, for more info you can check this thread for saving image to SD card with compress(CompressFormat.JPEG, 100, out); method and DocumentFile classes.

WAMP won't turn green. And the VCRUNTIME140.dll error

Since you already had a running version of WAMP and it stopped working, you probably had VCRUNTIME140.dll already installed. In that case:

  1. Open Programs and Features
  2. Right-click on the respective Microsoft Visual C++ 20xx Redistributable installers and choose "Change"
  3. Choose "Repair". Do this for both x86 and x64

This did the trick for me.

npm command to uninstall or prune unused packages in Node.js

If you're not worried about a couple minutes time to do so, a solution would be to rm -rf node_modules and npm install again to rebuild the local modules.

Counting repeated characters in a string in Python

My first idea was to do this:

chars = "abcdefghijklmnopqrstuvwxyz"
check_string = "i am checking this string to see how many times each character appears"

for char in chars:
  count = check_string.count(char)
  if count > 1:
    print char, count

This is not a good idea, however! This is going to scan the string 26 times, so you're going to potentially do 26 times more work than some of the other answers. You really should do this:

count = {}
for s in check_string:
  if s in count:
    count[s] += 1
  else:
    count[s] = 1

for key in count:
  if count[key] > 1:
    print key, count[key]

This ensures that you only go through the string once, instead of 26 times.

Also, Alex's answer is a great one - I was not familiar with the collections module. I'll be using that in the future. His answer is more concise than mine is and technically superior. I recommend using his code over mine.

npm install error from the terminal

First download json package file from https://github.com/npm/read-package-json and then run npm install from terminal.

Best way to restrict a text field to numbers only?

Here is my solution: a combination of the working ones below.

var checkInput = function(e) {
        if (!e) {
            e = window.event;
        }

        var code = e.keyCode || e.which;

        if (!e.ctrlKey) {

            //46, 8, 9, 27, 13 = backspace, delete, tab, escape, and enter
            if (code == 8 || code == 13 || code == 9 || code == 27 || code == 46)
                return true;
            //35..39 - home, end, left, right
            if (code >= 35 && code <= 39)
                return true;
            //numpad numbers
            if (code >= 96 && code <= 105)
                return true;
            //keyboard numbers
            if (isNaN(parseInt(String.fromCharCode(code), 10))) {
                e.preventDefault();
                return false;
            }
        }
        return true;
    };

Half circle with CSS (border, outline only)

I had a similar issue not long time ago and this was how I solved it

_x000D_
_x000D_
.rotated-half-circle {_x000D_
  /* Create the circle */_x000D_
  width: 40px;_x000D_
  height: 40px;_x000D_
  border: 10px solid black;_x000D_
  border-radius: 50%;_x000D_
  /* Halve the circle */_x000D_
  border-bottom-color: transparent;_x000D_
  border-left-color: transparent;_x000D_
  /* Rotate the circle */_x000D_
  transform: rotate(-45deg);_x000D_
}
_x000D_
<div class="rotated-half-circle"></div>
_x000D_
_x000D_
_x000D_

What is the difference between conversion specifiers %i and %d in formatted IO functions (*printf / *scanf)

They are the same when used for output, e.g. with printf.

However, these are different when used as input specifier e.g. with scanf, where %d scans an integer as a signed decimal number, but %i defaults to decimal but also allows hexadecimal (if preceded by 0x) and octal (if preceded by 0).

So 033 would be 27 with %i but 33 with %d.

Get the last three chars from any string - Java

This method would be helpful :

String rightPart(String text,int length)
{
    if (text.length()<length) return text;
    String raw = "";
    for (int i = 1; i <= length; i++) {
        raw += text.toCharArray()[text.length()-i];
    }
    return new StringBuilder(raw).reverse().toString();
}

How to set a hidden value in Razor

There is a Hidden helper alongside HiddenFor which lets you set the value.

@Html.Hidden("RequiredProperty", "default")

EDIT Based on the edit you've made to the question, you could do this, but I believe you're moving into territory where it will be cheaper and more effective, in the long run, to fight for making the code change. As has been said, even by yourself, the controller or view model should be setting the default.

This code:

<ul>
@{
        var stacks = new System.Diagnostics.StackTrace().GetFrames();
        foreach (var frame in stacks)
        {
            <li>@frame.GetMethod().Name - @frame.GetMethod().DeclaringType</li>
        }
}
</ul>

Will give output like this:

Execute - ASP._Page_Views_ViewDirectoryX__SubView_cshtml
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
ExecutePageHierarchy - System.Web.Mvc.WebViewPage
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
RenderView - System.Web.Mvc.RazorView
Render - System.Web.Mvc.BuildManagerCompiledView
RenderPartialInternal - System.Web.Mvc.HtmlHelper
RenderPartial - System.Web.Mvc.Html.RenderPartialExtensions
Execute - ASP._Page_Views_ViewDirectoryY__MainView_cshtml

So assuming the MVC framework will always go through the same stack, you can grab var frame = stacks[8]; and use the declaring type to determine who your parent view is, and then use that determination to set (or not) the default value. You could also walk the stack instead of directly grabbing [8] which would be safer but even less efficient.

"Access is denied" JavaScript error when trying to access the document object of a programmatically-created <iframe> (IE-only)

Following the exceedingly simple method from Andralor here fixed the issue for me: https://github.com/fancyapps/fancyBox/issues/766

Essentially, call the iframe again onUpdate:

$('a.js-fancybox-iframe').fancybox({
    type: 'iframe',
    scrolling : 'visible',
    autoHeight: true,
    onUpdate: function(){
     $("iframe.fancybox-iframe");
   }
 });

Decimal separator comma (',') with numberDecimal inputType in EditText

I think this solution is less complex than the others written here:

<EditText
    android:inputType="numberDecimal"
    android:digits="0123456789," />

This way when you press the '.' in the soft keyboard nothing happens; only numbers and comma are allowed.

How do I pass an object from one activity to another on Android?

Maybe it's an unpopular answer, but in the past I've simply used a class that has a static reference to the object I want to persist through activities. So,

public class PersonHelper
{
    public static Person person;
}

I tried going down the Parcelable interface path, but ran into a number of issues with it and the overhead in your code was unappealing to me.

How can I read the client's machine/computer name from the browser?

Well you could get the ip address using asp.net, then do a reverse DNS lookup on the ip to get the hostname.

From the ASP.NET Developer's cookbook ... Performing a Reverse-DNS Lookup.

Java integer list

code that works, but output is:

10
20
30
40
50

so:

    List<Integer> myCoords = new ArrayList<Integer>();
    myCoords.add(10);
    myCoords.add(20);
    myCoords.add(30);
    myCoords.add(40);
    myCoords.add(50);
    for (Integer number : myCoords) {
        System.out.println(number);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

What are abstract classes and abstract methods?

ABSTRACT CLASSES AND ABSTARCT METHODS FULL DESCRIPTION GO THROUGH IT

abstract method do not have body.A well defined method can't be declared abstract.

A class which has abstract method must be declared as abstract.

Abstract class can't be instantiated.

Navigation Drawer (Google+ vs. YouTube)

Edit #3:

The Navigation Drawer pattern is officially described in the Android documentation!

enter image description here Check out the following links:

  • Design docs can be found here.
  • Developer docs can be found here.

Edit #2:

Roman Nurik (an Android design engineer at Google) has confirmed that the recommended behavior is to not move the Action Bar when opening the drawer (like the YouTube app). See this Google+ post.


Edit #1:

I answered this question a while ago, but I'm back to re-emphasize that Prixing has the best fly-out menu out there... by far. It's absolutely beautiful, perfectly smooth, and it puts Facebook, Google+, and YouTube to shame. EverNote is pretty good too... but still not as perfect as Prixing. Check out this series of posts on how the flyout menu was implemented (from none other than the head developer at Prixing himself!).


Original Answer:

Adam Powell and Richard Fulcher talk about this at 49:47 - 52:50 in the Google I/O talk titled "Navigation in Android".

To summarize their answer, as of the date of this posting the slide out navigation menu is not officially part of the Android application design standard. As you have probably discovered, there's currently no native support for this feature, but there was talk about making this an addition to an upcoming revision of the support package.

With regards to the YouTube and G+ apps, it does seem odd that they behave differently. My best guess is that the reason the YouTube app fixes the position of the action bar is,

  1. One of the most important navigational options for users using the YouTube app is search, which is performed in the SearchView in the action bar. It would make sense to make the action bar static in this regard, since it would allow the user to always have the option to search for new videos.

  2. The G+ app uses a ViewPager to display its content, so making the pull out menu specific to the layout content (i.e. everything under the action bar) wouldn't make much sense. Swiping is supposed to provide a means of navigating between pages, not a means of global navigation. This might be why they decided to do it differently in the G+ app than they did in the YouTube app.

    On another note, check out the Google Play app for another version of the "pull out menu" (when you are at the left most page, swipe left and a pull out, "half-page" menu will appear).

You're right in that this isn't very consistent behavior, but it doesn't seem like there is a 100% consensus within the Android team on how this behavior should be implemented yet. I wouldn't be surprised if in the future the apps are updated so that the navigation in both apps are identical (they seemed very keen on making navigation consistent across all Google-made apps in the talk).

Populate data table from data reader

As Sagi stated in their answer DataTable.Load is a good solution. If you are trying to load multiple tables from a single reader you do not need to call DataReader.NextResult. The DataTable.Load method also advances the reader to the next result set (if any).

// Read every result set in the data reader.
while (!reader.IsClosed)
{
    DataTable dt = new DataTable();
    // DataTable.Load automatically advances the reader to the next result set
    dt.Load(reader);
    items.Add(dt);
}

Save string to the NSUserDefaults?

[[NSUserDefaults standardUserDefaults] setValue:aString forKey:aKey]

MySQL stored procedure vs function, which would I use when?

One significant difference is that you can include a function in your SQL queries, but stored procedures can only be invoked with the CALL statement:

UDF Example:

CREATE FUNCTION hello (s CHAR(20))
   RETURNS CHAR(50) DETERMINISTIC
   RETURN CONCAT('Hello, ',s,'!');
Query OK, 0 rows affected (0.00 sec)

CREATE TABLE names (id int, name varchar(20));
INSERT INTO names VALUES (1, 'Bob');
INSERT INTO names VALUES (2, 'John');
INSERT INTO names VALUES (3, 'Paul');

SELECT hello(name) FROM names;
+--------------+
| hello(name)  |
+--------------+
| Hello, Bob!  |
| Hello, John! |
| Hello, Paul! |
+--------------+
3 rows in set (0.00 sec)

Sproc Example:

delimiter //

CREATE PROCEDURE simpleproc (IN s CHAR(100))
BEGIN
   SELECT CONCAT('Hello, ', s, '!');
END//
Query OK, 0 rows affected (0.00 sec)

delimiter ;

CALL simpleproc('World');
+---------------------------+
| CONCAT('Hello, ', s, '!') |
+---------------------------+
| Hello, World!             |
+---------------------------+
1 row in set (0.00 sec)

How to connect mySQL database using C++

I had to include -lmysqlcppconn to my build in order to get it to work.

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

On the physical device, iPhone 6 Plus's main screen's bounds is 2208x1242 and nativeBounds is 1920x1080. There is hardware scaling involved to resize to the physical display.

On the simulator, the iPhone 6 Plus's main screen's bounds and nativeBounds are both 2208x1242.

In other words... Videos, OpenGL, and other things based on CALayers that deal with pixels will deal with the real 1920x1080 frame buffer on device (or 2208x1242 on sim). Things dealing with points in UIKit will be deal with the 2208x1242 (x3) bounds and get scaled as appropriate on device.

The simulator does not have access to the same hardware that is doing the scaling on device and there's not really much of a benefit to simulating it in software as they'd produce different results than the hardware. Thus it makes sense to set the nativeBounds of a simulated device's main screen to the bounds of the physical device's main screen.

iOS 8 added API to UIScreen (nativeScale and nativeBounds) to let a developer determine the resolution of the CADisplay corresponding to the UIScreen.

How do I override nested NPM dependency versions?

NPM shrinkwrap offers a nice solution to this problem. It allows us to override that version of a particular dependency of a particular sub-module.

Essentially, when you run npm install, npm will first look in your root directory to see whether a npm-shrinkwrap.json file exists. If it does, it will use this first to determine package dependencies, and then falling back to the normal process of working through the package.json files.

To create an npm-shrinkwrap.json, all you need to do is

 npm shrinkwrap --dev

code:

{
  "dependencies": {
    "grunt-contrib-connect": {
      "version": "0.3.0",
      "from": "[email protected]",
      "dependencies": {
        "connect": {
          "version": "2.8.1",
          "from": "connect@~2.7.3"
        }
      }
    }
  }
}

Eclipse Java error: This selection cannot be launched and there are no recent launches

Click on the drop down next to the Run button, After that choose Run Configuration, shows three option, for example i choose java application add class(Name of the class of your project) in that then Click on the ok button ...Run your application :)

Neeraj

Can't get value of input type="file"?

You can read it, but you can't set it. value="123" will be ignored, so it won't have a value until you click on it and pick a file.

Even then, the value will likely be mangled with something like c:\fakepath\ to keep the details of the user's filesystem private.

Replace transparency in PNG images with white background

here's how to replace the same image in all folders in a directory with white instead of transparent:

mogrify -background white -flatten */*.png

Get Environment Variable from Docker Container

The downside of using docker exec is that it requires a running container, so docker inspect -f might be handy if you're unsure a container is running.

Example #1. Output a list of space-separated environment variables in the specified container:

docker inspect -f \
   '{{range $index, $value := .Config.Env}}{{$value}} {{end}}' container_name

the output will look like this:

ENV_VAR1=value1 ENV_VAR2=value2 ENV_VAR3=value3

Example #2. Output each env var on new line and grep the needed items, for example, the mysql container's settings could be retrieved like this:

docker inspect -f \
    '{{range $index, $value := .Config.Env}}{{println $value}}{{end}}' \
    container_name | grep MYSQL_

will output:

MYSQL_PASSWORD=secret
MYSQL_ROOT_PASSWORD=supersecret
MYSQL_USER=demo
MYSQL_DATABASE=demodb
MYSQL_MAJOR=5.5
MYSQL_VERSION=5.5.52

Example #3. Let's modify the example above to get a bash friendly output which can be directly used in your scripts:

docker inspect -f \
   '{{range $index, $value := .Config.Env}}export {{$value}}{{println}}{{end}}' \
   container_name | grep MYSQL

will output:

export MYSQL_PASSWORD=secret
export MYSQL_ROOT_PASSWORD=supersecret
export MYSQL_USER=demo
export MYSQL_DATABASE=demodb
export MYSQL_MAJOR=5.5
export MYSQL_VERSION=5.5.52

If you want to dive deeper, then go to Go’s text/template package documentation with all the details of the format.

How do I get the last day of a month?

If you want the date, given a month and a year, this seems about right:

public static DateTime GetLastDayOfMonth(this DateTime dateTime)
{
    return new DateTime(dateTime.Year, dateTime.Month, DateTime.DaysInMonth(dateTime.Year, dateTime.Month));
}

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

First, create the derived value:

df.loc[0, 'C'] = df.loc[0, 'D']

Then iterate through the remaining rows and fill the calculated values:

for i in range(1, len(df)):
    df.loc[i, 'C'] = df.loc[i-1, 'C'] * df.loc[i, 'A'] + df.loc[i, 'B']


  Index_Date   A   B    C    D
0 2015-01-31  10  10   10   10
1 2015-02-01   2   3   23   22
2 2015-02-02  10  60  290  280

Python 2.7: %d, %s, and float()

See String Formatting Operations:

%d is the format code for an integer. %f is the format code for a float.

%s prints the str() of an object (What you see when you print(object)).

%r prints the repr() of an object (What you see when you print(repr(object)).

For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:

>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
        1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
      1.12

Most efficient way to reverse a numpy array

Because this seems to not be marked as answered yet... The Answer of Thomas Arildsen should be the proper one: just use

np.flipud(your_array) 

if it is a 1d array (column array).

With matrizes do

fliplr(matrix)

if you want to reverse rows and flipud(matrix) if you want to flip columns. No need for making your 1d column array a 2dimensional row array (matrix with one None layer) and then flipping it.

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

Syntax errors is not checked easily in external servers, just runtime errors.

What I do? Just like you, I use

ini_set('display_errors', 'On');
error_reporting(E_ALL);

However, before run I check syntax errors in a PHP file using an online PHP syntax checker.

The best, IMHO is PHP Code Checker

I copy all the source code, paste inside the main box and click the Analyze button.

It is not the most practical method, but the 2 procedures are complementary and it solves the problem completely

How to delete rows in tables that contain foreign keys to other tables

From your question, I think it is safe to assume you have CASCADING DELETES turned on.
All that is needed in that case is

DELETE FROM MainTable
WHERE PrimaryKey = ???

You database engine will take care of deleting the corresponding referencing records.

iOS: How to store username/password within an app?

There is a small bug in the above code (by the way Dave it was very helpful your post thank you)

In the part where we save the credentials it also needs the following code in order to work properly.

[self.keychainItem setObject:@"myCredentials" forKey:(__bridge id)(kSecAttrService)];

most probably is because the second time we try to (re-)sign in with the same credentials it finds them already assigned in the keychain items and the app crashes. with the above code it works like a charm.

XPath using starts-with function

Use:

//REVENUE_YEAR[starts-with(.,'2552')]/../REGION/text() 

Package opencv was not found in the pkg-config search path

When you run cmake add the additional parameter -D OPENCV_GENERATE_PKGCONFIG=YES (this will generate opencv.pc file)

Then make and sudo make install as before.

Use the name opencv4 instead of just opencv Eg:-

pkg-config --modversion opencv4

Javascript - Track mouse position

ES6 based code:

let handleMousemove = (event) => {
  console.log(`mouse position: ${event.x}:${event.y}`);
};

document.addEventListener('mousemove', handleMousemove);

If you need throttling for mousemoving, use this:

let handleMousemove = (event) => {
  console.warn(`${event.x}:${event.y}\n`);
};

let throttle = (func, delay) => {
  let prev = Date.now() - delay;
  return (...args) => {
    let current = Date.now();
    if (current - prev >= delay) {
      prev = current;
      func.apply(null, args);
    }
  }
};

// let's handle mousemoving every 500ms only
document.addEventListener('mousemove', throttle(handleMousemove, 500));

here is example

How to query for today's date and 7 days before data?

Try this way:

select * from tab
where DateCol between DateAdd(DD,-7,GETDATE() ) and GETDATE() 

How can I account for period (AM/PM) using strftime?

format = '%Y-%m-%d %H:%M %p'

The format is using %H instead of %I. Since %H is the "24-hour" format, it's likely just discarding the %p information. It works just fine if you change the %H to %I.

How to set environment variable or system property in spring tests?

The right way to do this, starting with Spring 4.1, is to use a @TestPropertySource annotation.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
    ...    
}

See @TestPropertySource in the Spring docs and Javadocs.

How to edit CSS style of a div using C# in .NET

How do you do this without runat="server"? For example, if you have a

<body runat="server" id="body1">

...and try to update it from within an Updatepanel it will never get updated.

However, if you keep it as an ordinary non-server HTML control you can. Here's the Jquery to update it:

$("#body1").addClass('modalBackground');

How do you do this in codebehind though?

How to check if a string is a valid JSON string in JavaScript without using Try/Catch

I thought I'd add my approach, in the context of a practical example. I use a similar check when dealing with values going in and coming out of Memjs, so even though the value saved may be string, array or object, Memjs expects a string. The function first checks if a key/value pair already exists, if it does then a precheck is done to determine if value needs to be parsed before being returned:

  function checkMem(memStr) {
    let first = memStr.slice(0, 1)
    if (first === '[' || first === '{') return JSON.parse(memStr)
    else return memStr
  }

Otherwise, the callback function is invoked to create the value, then a check is done on the result to see if the value needs to be stringified before going into Memjs, then the result from the callback is returned.

  async function getVal() {
    let result = await o.cb(o.params)
    setMem(result)
    return result

    function setMem(result) {
      if (typeof result !== 'string') {
        let value = JSON.stringify(result)
        setValue(key, value)
      }
      else setValue(key, result)
    }
  }

The complete code is below. Of course this approach assumes that the arrays/objects going in and coming out are properly formatted (i.e. something like "{ key: 'testkey']" would never happen, because all the proper validations are done before the key/value pairs ever reach this function). And also that you are only inputting strings into memjs and not integers or other non object/arrays-types.

async function getMem(o) {
  let resp
  let key = JSON.stringify(o.key)
  let memStr = await getValue(key)
  if (!memStr) resp = await getVal()
  else resp = checkMem(memStr)
  return resp

  function checkMem(memStr) {
    let first = memStr.slice(0, 1)
    if (first === '[' || first === '{') return JSON.parse(memStr)
    else return memStr
  }

  async function getVal() {
    let result = await o.cb(o.params)
    setMem(result)
    return result

    function setMem(result) {
      if (typeof result !== 'string') {
        let value = JSON.stringify(result)
        setValue(key, value)
      }
      else setValue(key, result)
    }
  }
}

Python creating a dictionary of lists

Personally, I just use JSON to convert things to strings and back. Strings I understand.

import json
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
mydict = {}
hash = json.dumps(s)
mydict[hash] = "whatever"
print mydict
#{'[["yellow", 1], ["blue", 2], ["yellow", 3], ["blue", 4], ["red", 1]]': 'whatever'}

jQuery: how to change title of document during .ready()?

Like this:

$(document).ready(function ()
{
    document.title = "Hello World!";
});

Be sure to set a default-title if you want your site to be properly indexed by search-engines.

A little tip:

$(function ()
{
    // this is a shorthand for the whole document-ready thing
    // In my opinion, it's more readable 
});

Aborting a stash pop in Git

OK, I think I have managed to find a work-flow that will get you back to where you need to be (as if you had not done the pop).

TAKE A BACKUP BEFOREHAND!! I don't know whether this will work for you, so copy your whole repo just in case it doesn't work.

1) Fix the merge problems and fix all the conflict by selecting all the changes that come from the patch (in tortoisemerge, this shows up as one.REMOETE (theirs)).

git mergetool

2) Commit these changes (they will already be added via the mergetool command). Give it a commit message of "merge" or something you remember.

git commit -m "merge"

3) Now you will still have your local unstaged changes that you started originally, with a new commit from the patch (we can get rid of this later). Now commit your unstaged changes

git add .
git add -u .
git commit -m "local changes"

4) Reverse the patch. This can be done with the following command:

git stash show -p | git apply -R

5) Commit these changes:

git commit -a -m "reversed patch"

6) Get rid of the patch/unpatch commits

git rebase -i HEAD^^^

from this, remove the two lines with 'merge' and 'reversed patch' in it.

7) Get your unstanged changes back and undo the 'local changes' commit

git reset HEAD^

I've run through it with a simple example and it gets you back to where you want to be - directly before the stash was popped, with your local changes and with the stash still being available to pop.

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

Either of these methods may be "better", i.e. more suitable, depending on what you want to do.

A server-side redirect is faster insofar as you get the data from a different page without making a round trip to the browser. But the URL seen in the browser is still the original address, so you're creating a little inconsistency there.

A client-side redirect is more versatile insofar as it can send you to a completely different server, or change the protocol (e.g. from HTTP to HTTPS), or both. And the browser is aware of the new URL. But it takes an extra back-and-forth between server and client.

Unloading classes in java?

You can unload a ClassLoader but you cannot unload specific classes. More specifically you cannot unload classes created in a ClassLoader that's not under your control.

If possible, I suggest using your own ClassLoader so you can unload.

How to get all the values of input array element jquery

By Using map

var values = $("input[name='pname[]']")
              .map(function(){return $(this).val();}).get();

Angular2: Cannot read property 'name' of undefined

In Angular, there is the support elvis operator ?. to protect against a view render failure. They call it the safe navigation operator. Take the example below:

The current person name is {{nullObject?.name}}

Since it is trying to access name property of a null value, the whole view disappears and you can see the error inside the browser console. It works perfectly with long property paths such as a?.b?.c?.d. So I recommend you to use it everytime you need to access a property inside a template.

error: RPC failed; curl transfer closed with outstanding read data remaining

Changing git clone protocol to try.

for example, this error happened when "git clone https://xxxxxxxxxxxxxxx"

you can try with "git clone git://xxxxxxxxxxxxxx", maybe ok then.

Is there an easy way to add a border to the top and bottom of an Android View?

To add a 1dp white border at the bottom only and to have a transparent background you can use the following which is simpler than most answers here.

For the TextView or other view add:

android:background="@drawable/borderbottom"

And in the drawable directory add the following XML, called borderbottom.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="-2dp" android:left="-2dp" android:right="-2dp">
        <shape android:shape="rectangle">
            <stroke android:width="1dp" android:color="#ffffffff" />
            <solid android:color="#00000000" />
        </shape>
    </item>
</layer-list>

If you want a border at the top, change the android:top="-2dp" to android:bottom="-2dp"

The colour does not need to be white and the background does not need to be transparent either.

The solid element may not be required. This will depend on your design (thanks V. Kalyuzhnyu).

Basically, this XML will create a border using the rectangle shape, but then pushes the top, right and left sides beyond the render area for the shape. This leaves just the bottom border visible.

XPath Query: get attribute href from a tag

For the following HTML document:

<html>
  <body>
    <a href="http://www.example.com">Example</a> 
    <a href="http://www.stackoverflow.com">SO</a> 
  </body>
</html>

The xpath query /html/body//a/@href (or simply //a/@href) will return:

    http://www.example.com
    http://www.stackoverflow.com

To select a specific instance use /html/body//a[N]/@href,

    $ /html/body//a[2]/@href
    http://www.stackoverflow.com

To test for strings contained in the attribute and return the attribute itself place the check on the tag not on the attribute:

    $ /html/body//a[contains(@href,'example')]/@href
    http://www.example.com

Mixing the two:

    $ /html/body//a[contains(@href,'com')][2]/@href
    http://www.stackoverflow.com

Collections sort(List<T>,Comparator<? super T>) method example

Building upon your existing Student class, this is how I usually do it, especially if I need more than one comparator.

public class Student implements Comparable<Student> {

    String name;
    int age;

    public Student(String name, int age) {
       this.name = name;
       this.age = age;
    }

    @Override
    public String toString() {
        return name + ":" + age;
    }

    @Override
    public int compareTo(Student o) {
        return Comparators.NAME.compare(this, o);
    }


    public static class Comparators {

        public static Comparator<Student> NAME = new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.name.compareTo(o2.name);
            }
        };
        public static Comparator<Student> AGE = new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.age - o2.age;
            }
        };
        public static Comparator<Student> NAMEANDAGE = new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                int i = o1.name.compareTo(o2.name);
                if (i == 0) {
                    i = o1.age - o2.age;
                }
                return i;
            }
        };
    }
}

Usage:

List<Student> studentList = new LinkedList<>();
Collections.sort(studentList, Student.Comparators.AGE);

EDIT

Since the release of Java 8 the inner class Comparators may be greatly simplified using lambdas. Java 8 also introduces a new method for the Comparator object thenComparing, which removes the need for doing manual checking of each comparator when nesting them. Below is the Java 8 implementation of the Student.Comparators class with these changes taken into account.

public static class Comparators {
    public static final Comparator<Student> NAME = (Student o1, Student o2) -> o1.name.compareTo(o2.name);
    public static final Comparator<Student> AGE = (Student o1, Student o2) -> Integer.compare(o1.age, o2.age);
    public static final Comparator<Student> NAMEANDAGE = (Student o1, Student o2) -> NAME.thenComparing(AGE).compare(o1, o2);
}