Programs & Examples On #Awtrobot

The Robot class (java.awt.Robot) is used to programmatically trigger input events such as key press events and mouse actions & can also perform screenshot capture.

Reference - What does this error mean in PHP?

Notice: Undefined variable

Happens when you try to use a variable that wasn't previously defined.

A typical example would be

foreach ($items as $item) {
    // do something with item
    $counter++;
}

If you didn't define $counter before, the code above will trigger the notice.

The correct way would be to set the variable before using it, even if it's just an empty string like

$counter = 0;
foreach ($items as $item) {
    // do something with item
    $counter++;
}

Similarly, a variable is not accessible outside its scope, for example when using anonymous functions.

$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) {
  // Prefix is undefined
  return "${prefix} ${food}";
}, $food);

This should instead be passed using use

$prefix = "Blueberry";
$food = ["cake", "cheese", "pie"];
$prefixedFood = array_map(function ($food) use ($prefix) {
  return "${prefix} ${food}";
}, $food);

Notice: Undefined property

This error means much the same thing, but refers to a property of an object. Reusing the example above, this code would trigger the error because the counter property hasn't been set.

$obj = new stdclass;
$obj->property = 2342;
foreach ($items as $item) {
    // do something with item
    $obj->counter++;
}

Related Questions:

How to clean node_modules folder of packages that are not in package.json?

Just in-case somebody needs it, here's something I've done recently to resolve this:

npm ci - If you want to clean everything and install all packages from scratch:

-It does a clean install: if the node_modules folder exists, npm deletes it and installs a fresh one.

-It checks for consistency: if package-lock.json doesn’t exist or if it doesn’t match the contents of package.json, npm stops with an error.

https://docs.npmjs.com/cli/v6/commands/npm-ci

npm-dedupe - If you want to clean-up the current node_modules directory without deleting and re-installing all the packages

Searches the local package tree and attempts to simplify the overall structure by moving dependencies further up the tree, where they can be more effectively shared by multiple dependent packages.

https://docs.npmjs.com/cli/v6/commands/npm-dedupe

Java : Cannot format given Object as a Date

SimpleDateFormat.format(...) takes a Date as parameter and format Date to String. So you need have a look API carefully

Can VS Code run on Android?

To date, there isn't a native VS Code editor for android, but projects do exist like Microsoft/monaco-editor which aim to provide a native experience in the browser.

CodeSandbox is a sophisticated online editor built around Monaco

Reading and writing value from a textfile by using vbscript code

This script will read lines from large file and write to new small files. Will duplicate the header of the first line (Header) to all child files

Dim strLine
lCounter = 1
fCounter = 1
cPosition = 1
MaxLine = 1000
splitAt = MaxLine
Dim fHeader
sFile = "inputFile.txt"
dFile = LEFT(sFile, (LEN(sFile)-4))& "_0" & fCounter & ".txt"
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile(sFile,1)
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
do while not objFileToRead.AtEndOfStream
        strLine = objFileToRead.ReadLine()
        objFileToWrite.WriteLine(strLine)
        If cPosition = 1 Then
            fHeader = strLine
        End If
        If cPosition = splitAt Then
            fCounter = fCounter + 1
            splitAt = splitAt + MaxLine
            objFileToWrite.Close
            Set objFileToWrite = Nothing
            If fCounter < 10 Then
                dFile=LEFT(dFile, (LEN(dFile)-5))& fCounter & ".txt"
                Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
                objFileToWrite.WriteLine(fHeader)
            ElseIf fCounter <100 Or fCounter = 100 Then
                dFile=LEFT(dFile, (LEN(dFile)-6))& fCounter & ".txt"
                Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
                objFileToWrite.WriteLine(fHeader)
            Else
                dFile=LEFT(dFile, (LEN(dFile)-7)) & fCounter & ".txt"
                Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
                objFileToWrite.WriteLine(fHeader)
            End If
        End If
        lCounter=lCounter + 1
        cPosition=cPosition + 1
Loop
objFileToWrite.Close
Set objFileToWrite = Nothing
objFileToRead.Close
Set objFileToRead = Nothing

Google Chromecast sender error if Chromecast extension is not installed or using incognito

Update: After several attempts, it looks like this may have been fixed in latest Chrome builds (per Paul Irish's comment below). That would suggest we will see this fixed in stable Chrome June-July 2016. Let's see ...

This is a known bug with the official Chromecast JavaScript library. Instead of failing silently, it dumps these error messages in all non-Chrome browsers as well as Chrome browsers where the Chromecast extension isn't present.

The Chromecast team have indicated they won't fix this bug.

If you are a developer shipping with this library, you can't do anything about it according to Chromecast team. You can only inform users to ignore the errors. (I believe Chromecast team is not entirely correct as the library could, at the least, avoid requesting the extension scipt if the browser is not Chrome. And I suspect it could be possible to suppress the error even if it is Chrome, but haven't tried anything.)

If you are a user annoyed by these console messages, you can switch to Chrome if not using it already. Within Chrome, either:

Update [Nov 13, 2014]: The problem has now been acknowledged by Google. A member of the Chromecast team seems to suggest the issue will be bypassed by a change the team is currently working on.

Update 2 [Feb 17, 2015]: The team claim there's nothing they can do to remove the error logs as it's a standard Chrome network error and they are still working on a long-term fix. Public comments on the bug tracker were closed with that update.

Update 3 [Dec 4, 2015]: This has finally been fixed! In the end, Chrome team simply added some code to block out this specific error. Hopefully some combination of devtools and extensions API will be improved in the future to make it possible to fix this kind of problem without patching the browser. Chrome Canary already has the patch, so it should roll out to all users around mid-January. Additionally, the team has confirmed the issue no longer affects other browsers as the SDK was updated to only activate if it's in Chrome.

Update 4 (April 30): Nope, not yet anyway. Thankfully Google's developer relations team are more aware than certain other stakeholders how badly this has affected developer experience. More whitelist updates have recently been made to clobber these log messages. Current status at top of the post.

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

SQL Server stored procedure Nullable parameter

It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.

Other than that, I would suggest two things...

First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...

    ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0

Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.

Get the item doubleclick event of listview

Either use the MouseDoubleClick event, and also, all the MouseClick events have a click count in the eventargs variable 'e'. So if e.ClickCount == 2, then doubleclicked.

Regex pattern including all special characters

You have a dash in the middle of the character class, which will mean a character range. Put the dash at the end of the class like so:

[$&+,:;=?@#|'<>.^*()%!-]

How to get values from IGrouping

foreach (var v in structure) 
{     
    var group = groups.Single(g => g.Key == v. ??? );
    v.ListOfSmth = group.ToList();
}

First you need to select the desired group. Then you can use the ToList method of on the group. The IGrouping is a IEnumerable of the values.

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

Add @JsonInclude(JsonInclude.Include.NON_NULL) (forces Jackson to serialize null values) to the class as well as @JsonIgnore to the password field.

You could of course set @JsonIgnore on createdBy and updatedBy as well if you always want to ignore then and not just in this specific case.

UPDATE

In the event that you do not want to add the annotation to the POJO itself, a great option is Jackson's Mixin Annotations. Check out the documentation

SQL Server 2008: TOP 10 and distinct together

Few ideas:

  1. You have quite a few fields in your select statement. Any value being different from another will make that row distinct.
  2. TOP clauses are usually paired with WHERE clauses. Otherwise TOP doesn't mean much. Top of what? The way you specify "top of what" is to sort by using WHERE
  3. It's entirely possible to get the same results even though you use TOP and DISTINCT and WHERE. Check to make sure that the data you're querying is indeed capable of being filtered and ordered in the manner you expect.

Try something like this:

SELECT DISTINCT TOP 10 p.id, pl.nm -- , pl.val, pl.txt_val
FROM dm.labs pl
JOIN mas_data.patients p    
on pl.id = p.id
where pl.nm like '%LDL%'
and val is not null
ORDER BY pl.nm

Note that i commented out some of the SELECT to limit your result set and DISTINCT logic.

How to center content in a bootstrap column?

//add this to your css
    .myClass{
          margin 0 auto;
          }

// add the class to the span tag( could add it to the div and not using a span  
// at all
    <div class="row">
   <div class="col-xs-1 center-block">
       <span class="myClass">aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
   </div>
 </div>

How do I keep track of pip-installed packages in an Anaconda (Conda) environment?

I followed @Viktor Kerkez's answer and have had mixed success. I found that sometimes this recipe of

conda skeleton pypi PACKAGE

conda build PACKAGE

would look like everything worked but I could not successfully import PACKAGE. Recently I asked about this on the Anaconda user group and heard from @Travis Oliphant himself on the best way to use conda to build and manage packages that do not ship with Anaconda. You can read this thread here, but I'll describe the approach below to hopefully make the answers to the OP's question more complete...

Example: I am going to install the excellent prettyplotlib package on Windows using conda 2.2.5.

1a) conda build --build-recipe prettyplotlib

You'll see the build messages all look good until the final TEST section of the build. I saw this error

File "C:\Anaconda\conda-bld\test-tmp_dir\run_test.py", line 23 import None SyntaxError: cannot assign to None TESTS FAILED: prettyplotlib-0.1.3-py27_0

1b) Go into /conda-recipes/prettyplotlib and edit the meta.yaml file. Presently, the packages being set up like in step 1a result in yaml files that have an error in the test section. For example, here is how mine looked for prettyplotlib

test:   # Python imports   imports:
    - 
    - prettyplotlib
    - prettyplotlib

Edit this section to remove the blank line preceded by the - and also remove the redundant prettyplotlib line. At the time of this writing I have found that I need to edit most meta.yaml files like this for external packages I am installing with conda, meaning that there is a blank import line causing the error along with a redundant import of the given package.

1c) Rerun the command from 1a, which should complete with out error this time. At the end of the build you'll be asked if you want to upload the build to binstar. I entered No and then saw this message:

If you want to upload this package to binstar.org later, type:

$ binstar upload C:\Anaconda\conda-bld\win-64\prettyplotlib-0.1.3-py27_0.tar.bz2

That tar.bz2 file is the build that you now need to actually install.

2) conda install C:\Anaconda\conda-bld\win-64\prettyplotlib-0.1.3-py27_0.tar.bz2

Following these steps I have successfully used conda to install a number of packages that do not come with Anaconda. Previously, I had installed some of these using pip, so I did pip uninstall PACKAGE prior to installing PACKAGE with conda. Using conda, I can now manage (almost) all of my packages with a single approach rather than having a mix of stuff installed with conda, pip, easy_install, and python setup.py install.

For context, I think this recent blog post by @Travis Oliphant will be helpful for people like me who do not appreciate everything that goes into robust Python packaging but certainly appreciate when stuff "just works". conda seems like a great way forward...

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

For some people, the accepted answer is not working, I found this other answer and it is working for me: How can I pass a parameter to a setTimeout() callback?

var hello = "Hello World";
setTimeout(alert, 1000, hello); 

'hello' is the parameter being passed, you can pass all the parameters after the timeout time. Thanks to @Fabio Phms for the answer.

SQLSTATE[HY000] [2002] Connection refused within Laravel homestead

I just ran into this and found that changing this in the .env file from 127.0.0.1 to localhost fixed it.

DB_HOST=localhost

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

Changed to:

SELECT FORMAT(SA.[RequestStartDate],'dd/MM/yyyy') as 'Service Start Date', SA.[RequestEndDate] as 'Service End Date', FROM (......)SA WHERE......

Have no idea which SQL engine you are using, for other SQL engine, CONVERT can be used in SELECT statement to change the format in the form you needed.

Richtextbox wpf binding

 <RichTextBox>
     <FlowDocument PageHeight="180">
         <Paragraph>
             <Run Text="{Binding Text, Mode=TwoWay}"/>
          </Paragraph>
     </FlowDocument>
 </RichTextBox>

This seems to be the easiest way by far and isn't displayed in any of these answers.

In the view model just have the Text variable.

Adding rows to tbody of a table using jQuery

As @wirey said appendTo should work, if not then you can try this:

$("#tblEntAttributes tbody").append(newRowContent);

Best way to iterate through a Perl array

IMO, implementation #1 is typical and being short and idiomatic for Perl trumps the others for that alone. A benchmark of the three choices might offer you insight into speed, at least.

Regex to check with starts with http://, https:// or ftp://

If you wanna do it in case-insensitive way, this is better:

System.out.println(test.matches("^(?i)(https?|ftp)://.*$")); 

How to start Fragment from an Activity

Simple way

  1. Create a new java class

    public class ActivityName extends FragmentActivity {
    @Override
     public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        if (savedInstanceState == null){
        getSupportFragmentManager().beginTransaction()
                .add(android.R.id.content, new Fragment_name_which_you_wantto_open()).commit();}
     }
    }
    
  2. in your activity where u want to call fragment

     Intent i = new Intent(Currentactivityname.this,ActivityName.class);
     startActivity(i);
    

Another Method

  1. Place frame layout in your activity where u want to open fragment

      <FrameLayout
            android:id="@+id/frameLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </FrameLayout>
    
  2. Paste this code where u want to open fragment

        Fragment mFragment = null;
            mFragment = new Name_of_fragment_which_you_want_to_open();
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.frameLayout, mFragment).commit();
    

How to create an Explorer-like folder browser control?

Microsoft provides a walkthrough for creating a Windows Explorer style interface in C#.

There are also several examples on Code Project and other sites. Immediate examples are Explorer Tree, My Explorer, File Browser and Advanced File Explorer but there are others. Explorer Tree seems to look the best from the brief glance I took.

I used the search term windows explorer tree view C# in Google to find these links.

Convert data file to blob

As pointed in the comments, file is a blob:

file instanceof Blob; // true

And you can get its content with the file reader API https://developer.mozilla.org/en/docs/Web/API/FileReader

Read more: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

_x000D_
_x000D_
var input = document.querySelector('input[type=file]');
var textarea = document.querySelector('textarea');

function readFile(event) {
  textarea.textContent = event.target.result;
  console.log(event.target.result);
}

function changeFile() {
  var file = input.files[0];
  var reader = new FileReader();
  reader.addEventListener('load', readFile);
  reader.readAsText(file);
}

input.addEventListener('change', changeFile);
_x000D_
<input type="file">
<textarea rows="10" cols="50"></textarea>
_x000D_
_x000D_
_x000D_

Set selected radio from radio group with a value

Or you can just write value attribute to it:

$(':radio[value=<yourvalue>]').attr('checked',true);

This works for me.

Android - How to decode and decompile any APK file?

To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.

How to jquery alert confirm box "yes" & "no"

See following snippet :

_x000D_
_x000D_
$(document).on("click", "a.deleteText", function() {_x000D_
    if (confirm('Are you sure ?')) {_x000D_
        $(this).prev('span.text').remove();_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
    <span class="text">some text</span>_x000D_
    <a href="#" class="deleteText"><span class="delete-icon"> x Delete </span></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

Actually, You can play with JdbcTemplate and customize your own method as you prefer. My suggestion is to make something like this:

public String test() {
    String cert = null;
    String sql = "select ID_NMB_SRZ from codb_owner.TR_LTM_SLS_RTN
        where id_str_rt = '999' and ID_NMB_SRZ = '60230009999999'";
    ArrayList<String> certList = (ArrayList<String>) jdbc.query(
        sql, new RowMapperResultSetExtractor(new UserMapper()));
    cert =  DataAccessUtils.singleResult(certList);

    return cert;
}

It works as the original jdbc.queryForObject, but without throw new EmptyResultDataAccessException when size == 0.

SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row

MS-SQL has a setting to prevent recursive trigger firing. This is confirgured via the sp_configure stored proceedure, where you can turn recursive or nested triggers on or off.

In this case, it would be possible, if you turn off recursive triggers to link the record from the inserted table via the primary key, and make changes to the record.

In the specific case in the question, it is not really a problem, because the result is to delete the record, which won't refire this particular trigger, but in general that could be a valid approach. We implemented optimistic concurrency this way.

The code for your trigger that could be used in this way would be:

ALTER TRIGGER myTrigger
    ON someTable
    AFTER INSERT
AS BEGIN
DELETE FROM someTable
    INNER JOIN inserted on inserted.primarykey = someTable.primarykey
    WHERE ISNUMERIC(inserted.someField) = 1
END

Splitting string with pipe character ("|")

Or.. Pattern#quote:

String[] value_split = rat_values.split(Pattern.quote("|"));

This is happening because String#split accepts a regex:

| has a special meaning in regex.

quote will return a String representation for the regex.

How to find the location of the Scheduled Tasks folder

For Windows 7 and up, scheduled tasks are not run by cmd.exe, but rather by MMC (Microsoft Management Console). %SystemRoot%\Tasks should work on any other Windows version though.

How to detect browser using angularjs?

There is a library ng-device-detector which makes detecting entities like browser, os easy.

Here is tutorial that explains how to use this library. Detect OS, browser and device in AngularJS

ngDeviceDetector

You need to add re-tree.js and ng-device-detector.js scripts into your html

Inject "ng.deviceDetector" as dependency in your module.

Then inject "deviceDetector" service provided by the library into your controller or factory where ever you want the data.

"deviceDetector" contains all data regarding browser, os and device.

How to display pdf in php

if(isset($_GET['content'])){
  $content = $_GET['content'];
  $dir = $_GET['dir'];
  header("Content-type:".$content);
  @readfile($dir);
}

$directory = (file_exists("mydir/"))?"mydir/":die("file/directory doesn't exists");// checks directory if existing.
 //the line above is just a one-line if statement (syntax: (conditon)?code here if true : code if false; )
 if($handle = opendir($directory)){ //opens directory if existing.
   while ($file = readdir($handle)) { //assign each file with link <a> tag with GET params
     echo '<a target="_blank" href="?content=application/pdf&dir='.$directory.'">'.$file.'</a>';
}

}

if you click the link a new window will appear with the pdf file

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

Your application has an AppCompat theme

<application
    android:theme="@style/AppTheme">

But, you overwrote the Activity (which extends AppCompatActivity) with a theme that isn't descendant of an AppCompat theme

<activity android:name=".MainActivity"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >

You could define your own fullscreen theme like so (notice AppCompat in the parent=)

<style name="AppFullScreenTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

Then set that on the Activity.

<activity android:name=".MainActivity"
    android:theme="@style/AppFullScreenTheme" >

Note: There might be an AppCompat theme that's already full screen, but don't know immediately

Finding diff between current and last version

As pointed out on a comment by amalloy, if by "current and last versions" you mean the last commit and the commit before that, you could simply use

git show

Using HttpClient and HttpPost in Android with post parameters

I've just checked and i have the same code as you and it works perferctly. The only difference is how i fill my List for the params :

I use a : ArrayList<BasicNameValuePair> params

and fill it this way :

 params.add(new BasicNameValuePair("apikey", apikey);

I do not use any JSONObject to send params to the webservices.

Are you obliged to use the JSONObject ?

What is the best way to conditionally apply attributes in AngularJS?

Was able to get this working:

ng-attr-aria-current="{{::item.isSelected==true ? 'page' : undefined}}"

The nice thing here is that if item.isSelected is false then the attribute simply isn't rendered.

How to completely remove borders from HTML table

In a bootstrap environment none of the top answers helped, but applying the following removed all borders:

.noBorder {
    border:none !important;
}

Applied as:

<td class="noBorder">

How to hash a string into 8 digits?

Raymond's answer is great for python2 (though, you don't need the abs() nor the parens around 10 ** 8). However, for python3, there are important caveats. First, you'll need to make sure you are passing an encoded string. These days, in most circumstances, it's probably also better to shy away from sha-1 and use something like sha-256, instead. So, the hashlib approach would be:

>>> import hashlib
>>> s = 'your string'
>>> int(hashlib.sha256(s.encode('utf-8')).hexdigest(), 16) % 10**8
80262417

If you want to use the hash() function instead, the important caveat is that, unlike in Python 2.x, in Python 3.x, the result of hash() will only be consistent within a process, not across python invocations. See here:

$ python -V
Python 2.7.5
$ python -c 'print(hash("foo"))'
-4177197833195190597
$ python -c 'print(hash("foo"))'
-4177197833195190597

$ python3 -V
Python 3.4.2
$ python3 -c 'print(hash("foo"))'
5790391865899772265
$ python3 -c 'print(hash("foo"))'
-8152690834165248934

This means the hash()-based solution suggested, which can be shortened to just:

hash(s) % 10**8

will only return the same value within a given script run:

#Python 2:
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543
$ python2 -c 's="your string"; print(hash(s) % 10**8)'
52304543

#Python 3:
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
12954124
$ python3 -c 's="your string"; print(hash(s) % 10**8)'
32065451

So, depending on if this matters in your application (it did in mine), you'll probably want to stick to the hashlib-based approach.

Multiple argument IF statement - T-SQL

That's the way to create complex boolean expressions: combine them with AND and OR. The snippet you posted doesn't throw any error for the IF.

How can I verify a Google authentication API access token?

I need to somehow query Google and ask: Is this access token valid for [email protected]?

No. All you need is request standard login with Federated Login for Google Account Users from your API domain. And only after that you could compare "persistent user ID" with one you have from 'public interface'.

The value of realm is used on the Google Federated Login page to identify the requesting site to the user. It is also used to determine the value of the persistent user ID returned by Google.

So you need be from same domain as 'public interface'.

And do not forget that user needs to be sure that your API could be trusted ;) So Google will ask user if it allows you to check for his identity.

How to take a screenshot programmatically on iOS

As of iOS10, this gets a bit simpler. UIKit comes with UIGraphicsImageRender that allows you to

... accomplish drawing tasks, without having to handle configuration such as color depth and image scale, or manage Core Graphics contexts

Apple Docs - UIGraphicsImageRenderer

So you can now do something like this:

let renderer = UIGraphicsImageRenderer(size: someView.bounds.size)

let image = renderer.image(actions: { context in
    someView.drawHierarchy(in: someView.bounds, afterScreenUpdates: true)
})

Many of the answers here worked for me in most cases. But when trying to take a snapshot of an ARSCNView, I was only able to do it using the method described above. Although it might be worth noting that at this time, ARKit is still in beta and Xcode is in beta 4

Why are my PHP files showing as plain text?

You should install the PHP 5 library for Apache.

For Debian and Ubuntu:

apt-get install libapache2-mod-php5

And restart the Apache:

service apache2 restart

SQL Data Reader - handling Null column values

private static void Render(IList<ListData> list, IDataReader reader)
        {
            while (reader.Read())
            {

                listData.DownUrl = (reader.GetSchemaTable().Columns["DownUrl"] != null) ? Convert.ToString(reader["DownUrl"]) : null;
                //??????,????null
                list.Add(listData);
            }
            reader.Close();
        }

Get Wordpress Category from Single Post

<div class="post_category">
        <?php $category = get_the_category();
             $allcategory = get_the_category(); 
        foreach ($allcategory as $category) {
        ?>
           <a class="btn"><?php echo $category->cat_name;; ?></a>
        <?php 
        }
        ?>
 </div>

How to write log base(2) in c/c++

uint16_t log2(uint32_t n) {//but truncated
     if (n==0) throw ...
     uint16_t logValue = -1;
     while (n) {//
         logValue++;
         n >>= 1;
     }
     return logValue;
 }

Basically the same as tomlogic's.

Argument list too long error for rm, cp, mv commands

you can use this commend

find -name "*.pdf"  -delete

Configure hibernate to connect to database via JNDI Datasource

Tomcat-7 JNDI configuration:

Steps:

  1. Open the server.xml in the tomcat-dir/conf
  2. Add below <Resource> tag with your DB details inside <GlobalNamingResources>
<Resource name="jdbc/mydb"
          global="jdbc/mydb"
          auth="Container"
          type="javax.sql.DataSource"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/test"
          username="root"
          password=""
          maxActive="10"
          maxIdle="10"
          minIdle="5"
          maxWait="10000"/>
  1. Save the server.xml file
  2. Open the context.xml in the tomcat-dir/conf
  3. Add the below <ResourceLink> inside the <Context> tag.
<ResourceLink name="jdbc/mydb" 
              global="jdbc/mydb"
              auth="Container"
              type="javax.sql.DataSource" />
  1. Save the context.xml
  2. Open the hibernate-cfg.xml file and add and remove below properties.
Adding:
-------
<property name="connection.datasource">java:comp/env/jdbc/mydb</property>

Removing:
--------
<!--<property name="connection.url">jdbc:mysql://localhost:3306/mydb</property> -->
<!--<property name="connection.username">root</property> -->
<!--<property name="connection.password"></property> -->
  1. Save the file and put latest .WAR file in tomcat.
  2. Restart the tomcat. the DB connection will work.

Return content with IHttpActionResult for non-OK response

Above things are really helpful.

While creating web services, If you will take case of services consumer will greatly appreciated. I tried to maintain uniformity of the output. Also you can give remark or actual error message. The web service consumer can only check IsSuccess true or not else will sure there is problem, and act as per situation.

  public class Response
    {
        /// <summary>
        /// Gets or sets a value indicating whether this instance is success.
        /// </summary>
        /// <value>
        /// <c>true</c> if this instance is success; otherwise, <c>false</c>.
        /// </value>
        public bool IsSuccess { get; set; } = false;

        /// <summary>
        /// Actual response if succeed 
        /// </summary>
        /// <value>
        /// Actual response if succeed 
        /// </value>
        public object Data { get; set; } = null;

        /// <summary>
        /// Remark if anythig to convey
        /// </summary>
        /// <value>
        /// Remark if anythig to convey
        /// </value>
        public string Remark { get; set; } = string.Empty;
        /// <summary>
        /// Gets or sets the error message.
        /// </summary>
        /// <value>
        /// The error message.
        /// </value>
        public object ErrorMessage { get; set; } = null;


    }  




[HttpGet]
        public IHttpActionResult Employees()
        {
            Response _res = new Response();
            try
            { 
                DalTest objDal = new DalTest(); 
                _res.Data = objDal.GetTestData();
                _res.IsSuccess = true;
                return Ok<Response>(_res);
            }
            catch (Exception ex)
            {
                _res.IsSuccess = false;
                _res.ErrorMessage = ex;
                return ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, _res )); 
            } 
        }

You are welcome to give suggestion if any :)

Run Stored Procedure in SQL Developer?

For those using SqlDeveloper 3+, in case you missed that:

SqlDeveloper has feature to execute stored proc/function directly, and output are displayed in a easy-to-read manner.

Just right click on the package/stored proc/ stored function, Click on Run and choose target to be the proc/func you want to execute, SqlDeveloper will generate the code snippet to execute (so that you can put your input parameters). Once executed, output parameters are displayed in lower half of the dialog box, and it even have built-in support for ref cursor: result of cursor will be displayed as a separate output tab.

How do I get TimeSpan in minutes given two Dates?

double totalMinutes = (end-start).TotalMinutes;

How do I get the first element from an IEnumerable<T> in .net?

Use FirstOrDefault or a foreach loop as already mentioned. Manually fetching an enumerator and calling Current should be avoided. foreach will dispose your enumerator for you if it implements IDisposable. When calling MoveNext and Current you have to dispose it manually (if aplicable).

jQuery getTime function

Yes, it is possible:

jQuery.now()

or simply

$.now()

see jQuery Documentation for jQuery.now()

Difference between Width:100% and width:100vw?

You can solve this issue be adding max-width:

#element {
   width: 100vw;
   height: 100vw;
   max-width: 100%;
}

When you using CSS to make the wrapper full width using the code width: 100vw; then you will notice a horizontal scroll in the page, and that happened because the padding and margin of html and body tags added to the wrapper size, so the solution is to add max-width: 100%

Regex Until But Not Including

The explicit way of saying "search until X but not including X" is:

(?:(?!X).)*

where X can be any regular expression.

In your case, though, this might be overkill - here the easiest way would be

[^z]*

This will match anything except z and therefore stop right before the next z.

So .*?quick[^z]* will match The quick fox jumps over the la.

However, as soon as you have more than one simple letter to look out for, (?:(?!X).)* comes into play, for example

(?:(?!lazy).)* - match anything until the start of the word lazy.

This is using a lookahead assertion, more specifically a negative lookahead.

.*?quick(?:(?!lazy).)* will match The quick fox jumps over the.

Explanation:

(?:        # Match the following but do not capture it:
 (?!lazy)  # (first assert that it's not possible to match "lazy" here
 .         # then match any character
)*         # end of group, zero or more repetitions.

Furthermore, when searching for keywords, you might want to surround them with word boundary anchors: \bfox\b will only match the complete word fox but not the fox in foxy.

Note

If the text to be matched can also include linebreaks, you will need to set the "dot matches all" option of your regex engine. Usually, you can achieve that by prepending (?s) to the regex, but that doesn't work in all regex engines (notably JavaScript).

Alternative solution:

In many cases, you can also use a simpler, more readable solution that uses a lazy quantifier. By adding a ? to the * quantifier, it will try to match as few characters as possible from the current position:

.*?(?=(?:X)|$)

will match any number of characters, stopping right before X (which can be any regex) or the end of the string (if X doesn't match). You may also need to set the "dot matches all" option for this to work. (Note: I added a non-capturing group around X in order to reliably isolate it from the alternation)

How to set a Fragment tag by code?

Nowadays there's a simpler way to achieve this if you are using a DialogFragment (not a Fragment):

val yourDialogFragment = YourDialogFragment()
yourDialogFragment.show(
    activity.supportFragmentManager,
    "YOUR_TAG_FRAGMENT"
)

Under the hood, the show() method does create a FragmentTransaction and adds the tag by using the add() method. But it's much more convenient to use the show() method in my opinion.

You could shorten it for Fragment too, by using a Kotlin Extension :)

Unit tests vs Functional tests

TLDR:

To answer the question: Unit Testing is a subtype of Functional Testing.


There are two big groups: Functional and Non-Functional Testing. The best (non-exhaustive) illustration that I found is this one (source: www.inflectra.com):

enter image description here

(1) Unit Testing: testing of small snippets of code (functions/methods). It may be considered as (white-box) functional testing.

When functions are put together, you create a module = a standalone piece, possibly with a User Interface that can be tested (Module Testing). Once you have at least two separate modules, then you glue them together and then comes:

(2) Integration Testing: when you put two or more pieces of (sub)modules or (sub)systems together and see if they play nicely together.

Then you integrate the 3rd module, then the 4th and 5th in whatever order you or your team see fit, and once all the jigsaw pieces are placed together, comes

(3) System Testing: testing SW as a whole. This is pretty much "Integration testing of all pieces together".

If that's OK, then comes

(4) Acceptance Testing: did we build what the customer asked for actually? Of course, Acceptance Testing should be done throughout the lifecycle, not just at the last stage, where you realise that the customer wanted a sportscar and you built a van.

enter image description here

navbar color in Twitter Bootstrap

The best way currently to do the same would be to install LESS command line compiler using

$ npm install -g less jshint recess uglify-js

Once you have done this, then go to the less folder in the directory and then edit the file variables.less and you can change a lot of variables according to what you need including the color of the navigation bar

@navbarCollapseWidth:             979px;

@navbarHeight:                    40px;
@navbarBackgroundHighlight:       #ffffff;
@navbarBackground:                darken(@navbarBackgroundHighlight, 5%);
@navbarBorder:                    darken(@navbarBackground, 12%);

@navbarText:                      #777;
@navbarLinkColor:                 #777;
@navbarLinkColorHover:            @grayDark;
@navbarLinkColorActive:           @gray;
@navbarLinkBackgroundHover:       transparent;
@navbarLinkBackgroundActive:      darken(@navbarBackground, 5%);

Once you have done this, go to your bootstrap directory and run the command make.

Android: how to handle button click

Question#1 - These are the only way to handle view clicks.

Question#2 -
Option#1/Option#4 - There's not much difference between option#1 and option#4. The only difference I see is in one case activity is implementing the OnClickListener, whereas, in the other case, there'd be an anonymous implementation.

Option#2 - In this method an anonymous class will be generated. This method is a bit cumborsome, as, you'd need to do it multiple times, if you have multiple buttons. For Anonymous classes, you have to be careful for handling memory leaks.

Option#3 - Though, this is a easy way. Usually, Programmers try not to use any method until they write it, and hence this method is not widely used. You'd see mostly people use Option#4. Because it is cleaner in term of code.

How to prevent Browser cache for php site

Prevent browser cache is not a good idea depending on the case. Looking for a solution I found solutions like this:

<link rel="stylesheet" type="text/css" href="meu.css?v=<?=filemtime($file);?>">

the problem here is that if the file is overwritten during an update on the server, which is my scenario, the cache is ignored because timestamp is modified even the content of the file is the same.

I use this solution to force browser to download assets only if its content is modified:

<link rel="stylesheet" type="text/css" href="meu.css?v=<?=hash_file('md5', $file);?>">

How to get city name from latitude and longitude coordinates in Google Maps?

Try this

  List<Address> list = geoCoder.getFromLocation(location
            .getLatitude(), location.getLongitude(), 1);
    if (list != null & list.size() > 0) {
        Address address = list.get(0);
        result = address.getLocality();
        return result;

How to input a regex in string.replace?

The easiest way

import re

txt='this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>.  and there are many other lines in the txt files with<[3> such tags </[3>'

out = re.sub("(<[^>]+>)", '', txt)
print out

Oracle: how to INSERT if a row doesn't exist

If name is a PK, then just insert and catch the error. The reason to do this rather than any check is that it will work even with multiple clients inserting at the same time. If you check and then insert, you have to hold a lock during that time, or expect the error anyway.

The code for this would be something like

BEGIN
  INSERT INTO table( name, age )
    VALUES( 'johnny', null );
EXCEPTION
  WHEN dup_val_on_index
  THEN
    NULL; -- Intentionally ignore duplicates
END;

How to change option menu icon in the action bar?

you can achieve this by doing

<item
    android:id="@+id/menus"
    android:actionProviderClass="@android:style/Widget.Holo.ActionButton.Overflow"
    android:icon="@drawable/your_icon"
    android:showAsAction="always">
  <item android:id="@+id/Bugreport"
   android:title="@string/option_bugreport" />

  <item android:id="@+id/Info"
  android:title="@string/option_info" />

 <item android:id="@+id/About"
   android:title="@string/option_about" />
  </item>

How to use CSS to surround a number with a circle?

I am surprised nobody used flex which is easier to understand, so I put my version of answer here:

  1. To create a circle, make sure width equals height
  2. To adapt to font-size of number in the circle, use em rather than px
  3. To center the number in the circle, use flex with justify-content: center; align-items: center;
  4. if the number grows (>1000 for example), increase the width and height at same time

Here is an example:

_x000D_
_x000D_
.circled-number {
  color: #666;
  border: 2px solid #666;
  border-radius: 50%;
  font-size: 1rem;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 2em; 
  height: 2em;
}

.circled-number--big {
  color: #666;
  border: 2px solid #666;
  border-radius: 50%;
  font-size: 1rem;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 4em; 
  height: 4em;
}
_x000D_
<div class="circled-number">
  30
</div>

<div class="circled-number--big">
  3000000
</div>
_x000D_
_x000D_
_x000D_

What is a Question Mark "?" and Colon ":" Operator Used for?

Maybe It can be perfect example for Android, For example:

void setWaitScreen(boolean set) {
    findViewById(R.id.screen_main).setVisibility(
            set ? View.GONE : View.VISIBLE);
    findViewById(R.id.screen_wait).setVisibility(
            set ? View.VISIBLE : View.GONE);
}

Axios get in url works but with second parameter as object it doesn't

axios.get accepts a request config as the second parameter (not query string params).

You can use the params config option to set query string params as follows:

axios.get('/api', {
  params: {
    foo: 'bar'
  }
});

INSTALL_FAILED_DUPLICATE_PERMISSION... C2D_MESSAGE

While giving this error it will clearly mention the package name of the app because of which the permission was denied. And just uninstalling the application will not solve the problem. In order to solve problem we need to do the following step:

  1. Go to settings
  2. Go to app
  3. Go to downloaded app list
  4. You can see the uninstalled application in the list
  5. Click on the application, go to more option
  6. Click on uninstall for all users options

Problem solved :D

Do fragments really need an empty constructor?

Here is my simple solution:

1 - Define your fragment

public class MyFragment extends Fragment {

    private String parameter;

    public MyFragment() {
    }

    public void setParameter(String parameter) {
        this.parameter = parameter;
    } 
}

2 - Create your new fragment and populate the parameter

    myfragment = new MyFragment();
    myfragment.setParameter("here the value of my parameter");

3 - Enjoy it!

Obviously you can change the type and the number of parameters. Quick and easy.

How to do one-liner if else statement?

One possible way to do this in just one line by using a map, simple I am checking whether a > b if it is true I am assigning c to a otherwise b

c := map[bool]int{true: a, false: b}[a > b]

However, this looks amazing but in some cases it might NOT be the perfect solution because of evaluation order. For example, if I am checking whether an object is not nil get some property out of it, look at the following code snippet which will panic in case of myObj equals nil

type MyStruct struct {
   field1 string
   field2 string 
}

var myObj *MyStruct
myObj = nil 

myField := map[bool]string{true: myObj.field1, false: "empty!"}[myObj != nil}

Because map will be created and built first before evaluating the condition so in case of myObj = nil this will simply panic.

Not to forget to mention that you can still do the conditions in just one simple line, check the following:

var c int
...
if a > b { c = a } else { c = b}

How do I address unchecked cast warnings?

Almost every problem in Computer Science can be solved by adding a level of indirection*, or something.

So introduce a non-generic object that is of a higher-level that a Map. With no context it isn't going to look very convincing, but anyway:

public final class Items implements java.io.Serializable {
    private static final long serialVersionUID = 1L;
    private Map<String,String> map;
    public Items(Map<String,String> map) {
        this.map = New.immutableMap(map);
    }
    public Map<String,String> getMap() {
        return map;
    }
    @Override public String toString() {
        return map.toString();
    }
}

public final class New {
    public static <K,V> Map<K,V> immutableMap(
        Map<? extends K, ? extends V> original
    ) {
        // ... optimise as you wish...
        return Collections.unmodifiableMap(
            new HashMap<String,String>(original)
        );
    }
}

static Map<String, String> getItems(HttpSession session) {
    Items items = (Items)
        session.getAttribute("attributeKey");
    return items.getMap();
}

*Except too many levels of indirection.

How to test if a list contains another list?

Here is my answer. This function will help you to find out whether B is a sub-list of A. Time complexity is O(n).

`def does_A_contain_B(A, B): #remember now A is the larger list
    b_size = len(B)
    for a_index in range(0, len(A)):
        if A[a_index : a_index+b_size]==B:
            return True
    else:
        return False`

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

Indeed, the 9th byte indicates the check state of the button, but the answers above don't take into account the checkbox which enables manual configuration. This check state value is also present in this ninth byte. The real answer should thus be:

Byte value

00001001 = Manual proxy is checked

00000101 = Use automatic configuration script is checked

00000011 = Automatically detect settings is checked

When multiple checkboxes are checked, the value of the 9th byte is the result of the bitwise OR operation on the values for which the checkbox is checked.

How to return a result (startActivityForResult) from a TabHost Activity?

For start Activity 2 from Activity 1 and get result, you could use startActivityForResult and implement onActivityResult in Activity 1 and use setResult in Activity2.

Intent intent = new Intent(this, Activity2.class);
intent.putExtra(NUMERO1, numero1);
intent.putExtra(NUMERO2, numero2);
//startActivity(intent);
startActivityForResult(intent, MI_REQUEST_CODE);

Running a command in a new Mac OS X Terminal window

You could also invoke the new command feature of Terminal by pressing the Shift + ? + N key combination. The command you put into the box will be run in a new Terminal window.

Hide header in stack navigator React navigation

UPDATE as of version 5

As of version 5 it is the option headerShown in screenOptions

Example of usage:

<Stack.Navigator
  screenOptions={{
    headerShown: false
  }}
>
  <Stack.Screen name="route-name" component={ScreenComponent} />
</Stack.Navigator>

If you want only to hide the header on 1 screen you can do this by setting the screenOptions on the screen component see below for example:

<Stack.Screen options={{headerShown: false}} name="route-name" component={ScreenComponent} />

See also the blog about version 5

UPDATE
As of version 2.0.0-alpha.36 (2019-11-07),
there is a new navigationOption: headershown

      navigationOptions: {
        headerShown: false,
      }

https://reactnavigation.org/docs/stack-navigator#headershown

https://github.com/react-navigation/react-navigation/commit/ba6b6ae025de2d586229fa8b09b9dd5732af94bd

Old answer

I use this to hide the stack bar (notice this is the value of the second param):

{
    headerMode: 'none',
    navigationOptions: {
        headerVisible: false,
    }
}

When you use the this method it will be hidden on all screens.

In your case it will look like this:

const MainNavigation = StackNavigator({
  otp: { screen: OTPlogin },
  otpverify: { screen: OTPverification },
  userVerified: {
    screen: TabNavigator({
    List: { screen: List },
    Settings: { screen: Settings }
   }),
 }
},
{
  headerMode: 'none',
  navigationOptions: {
    headerVisible: false,
  }
 }
);

Best way to convert pdf files to tiff files

https://pypi.org/project/pdf2tiff/

You could also use pdf2ps, ps2image and then convert from the resulting image to tiff with other utilities (I remember 'paul' [paul - Yet another image viewer (displays PNG, TIFF, GIF, JPG, etc.])

How do I create an iCal-type .ics file that can be downloaded by other users?

There is also this tool you can use. It supports multi-events .ics file creation. It also supports timezone as well.

http://apps.marudot.com/ical/

Replace substring with another substring C++

std::string replace(const std::string & in
                  , const std::string & from
                  , const std::string & to){
  if(from.size() == 0 ) return in;
  std::string out = "";
  std::string tmp = "";
  for(int i = 0, ii = -1; i < in.size(); ++i) {
    // change ii
    if     ( ii <  0 &&  from[0] == in[i] )  {
      ii  = 0;
      tmp = from[0]; 
    } else if( ii >= 0 && ii < from.size()-1 )  {
      ii ++ ;
      tmp = tmp + in[i];
      if(from[ii] == in[i]) {
      } else {
        out = out + tmp;
        tmp = "";
        ii = -1;
      }
    } else {
      out = out + in[i];
    }
    if( tmp == from ) {
      out = out + to;
      tmp = "";
      ii = -1;
    }
  }
  return out;
};

How can I set the default value for an HTML <select> element?

You just need to put attribute "selected" on a particular option instead direct to select element.

Here is snippet for same and multiple working example with different values.

_x000D_
_x000D_
   Select Option 3 :- _x000D_
   <select name="hall" id="hall">_x000D_
    <option>1</option>_x000D_
    <option>2</option>_x000D_
    <option selected="selected">3</option>_x000D_
    <option>4</option>_x000D_
    <option>5</option>_x000D_
   </select>_x000D_
   _x000D_
   <br/>_x000D_
   <br/>_x000D_
   <br/>_x000D_
   Select Option 5 :- _x000D_
   <select name="hall" id="hall">_x000D_
    <option>1</option>_x000D_
    <option>2</option>_x000D_
    <option>3</option>_x000D_
    <option>4</option>_x000D_
    <option selected="selected">5</option>_x000D_
   </select>_x000D_
   _x000D_
    <br/>_x000D_
   <br/>_x000D_
   <br/>_x000D_
   Select Option 2 :- _x000D_
   <select name="hall" id="hall">_x000D_
    <option>1</option>_x000D_
    <option selected="selected">2</option>_x000D_
    <option>3</option>_x000D_
    <option>4</option>_x000D_
    <option>5</option>_x000D_
   </select>
_x000D_
_x000D_
_x000D_

React.js: onChange event for contentEditable

I suggest using a mutationObserver to do this. It gives you a lot more control over what is going on. It also gives you more details on how the browse interprets all the keystrokes

Here in TypeScript

import * as React from 'react';

export default class Editor extends React.Component {
    private _root: HTMLDivElement; // Ref to the editable div
    private _mutationObserver: MutationObserver; // Modifications observer
    private _innerTextBuffer: string; // Stores the last printed value

    public componentDidMount() {
        this._root.contentEditable = "true";
        this._mutationObserver = new MutationObserver(this.onContentChange);
        this._mutationObserver.observe(this._root, {
            childList: true, // To check for new lines
            subtree: true, // To check for nested elements
            characterData: true // To check for text modifications
        });
    }

    public render() {
        return (
            <div ref={this.onRootRef}>
                Modify the text here ...
            </div>
        );
    }

    private onContentChange: MutationCallback = (mutations: MutationRecord[]) => {
        mutations.forEach(() => {
            // Get the text from the editable div
            // (Use innerHTML to get the HTML)
            const {innerText} = this._root; 

            // Content changed will be triggered several times for one key stroke
            if (!this._innerTextBuffer || this._innerTextBuffer !== innerText) {
                console.log(innerText); // Call this.setState or this.props.onChange here
                this._innerTextBuffer = innerText;
            }
        });
    }

    private onRootRef = (elt: HTMLDivElement) => {
        this._root = elt;
    }
}

How can I update a row in a DataTable in VB.NET?

You can access columns by index, by name and some other ways:

dtResult.Rows(i)("columnName") = strVerse

You should probably make sure your DataTable has some columns first...

How to change the Text color of Menu item in Android?

Thanks to max.musterman, this is the solution I got to work in level 22:

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    MenuItem searchMenuItem = menu.findItem(R.id.search);
    SearchView searchView = (SearchView) searchMenuItem.getActionView();
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    searchView.setSubmitButtonEnabled(true);
    searchView.setOnQueryTextListener(this);
    setMenuTextColor(menu, R.id.displaySummary, R.string.show_summary);
    setMenuTextColor(menu, R.id.about, R.string.text_about);
    setMenuTextColor(menu, R.id.importExport, R.string.import_export);
    setMenuTextColor(menu, R.id.preferences, R.string.settings);
    return true;
}

private void setMenuTextColor(Menu menu, int menuResource, int menuTextResource) {
    MenuItem item = menu.findItem(menuResource);
    SpannableString s = new SpannableString(getString(menuTextResource));
    s.setSpan(new ForegroundColorSpan(Color.BLACK), 0, s.length(), 0);
    item.setTitle(s);
}

The hardcoded Color.BLACK could become an additional parameter to the setMenuTextColor method. Also, I only used this for menu items which were android:showAsAction="never".

Alternative for PHP_excel

For Writing Excel

  • PEAR's PHP_Excel_Writer (xls only)
  • php_writeexcel from Bettina Attack (xls only)
  • XLS File Generator commercial and xls only
  • Excel Writer for PHP from Sourceforge (spreadsheetML only)
  • Ilia Alshanetsky's Excel extension now on github (xls and xlsx, and requires commercial libXL component)
  • PHP's COM extension (requires a COM enabled spreadsheet program such as MS Excel or OpenOffice Calc running on the server)
  • The Open Office alternative to COM (PUNO) (requires Open Office installed on the server with Java support enabled)
  • PHP-Export-Data by Eli Dickinson (Writes SpreadsheetML - the Excel 2003 XML format, and CSV)
  • Oliver Schwarz's php-excel (SpreadsheetML)
  • Oliver Schwarz's original version of php-excel (SpreadsheetML)
  • excel_xml (SpreadsheetML, despite its name)... link reported as broken
  • The tiny-but-strong (tbs) project includes the OpenTBS tool for creating OfficeOpenXML documents (OpenDocument and OfficeOpenXML formats)
  • SimpleExcel Claims to read and write Microsoft Excel XML / CSV / TSV / HTML / JSON / etc formats
  • KoolGrid xls spreadsheets only, but also doc and pdf
  • PHP_XLSXWriter OfficeOpenXML
  • PHP_XLSXWriter_plus OfficeOpenXML, fork of PHP_XLSXWriter
  • php_writeexcel xls only (looks like it's based on PEAR SEW)
  • spout OfficeOpenXML (xlsx) and CSV
  • Slamdunk/php-excel (xls only) looks like an updated version of the old PEAR Spreadsheet Writer

For Reading Excel

A new C++ Excel extension for PHP, though you'll need to build it yourself, and the docs are pretty sparse when it comes to trying to find out what functionality (I can't even find out from the site what formats it supports, or whether it reads or writes or both.... I'm guessing both) it offers is phpexcellib from SIMITGROUP.

All claim to be faster than PHPExcel from codeplex or from github, but (with the exception of COM, PUNO Ilia's wrapper around libXl and spout) they don't offer both reading and writing, or both xls and xlsx; may no longer be supported; and (while I haven't tested Ilia's extension) only COM and PUNO offers the same degree of control over the created workbook.

C++ compile error: has initializer but incomplete type

` Please include either of these:

`#include<sstream>`

using std::istringstream; 

CSS: Hover one element, effect for multiple elements?

OR

.section:hover > div {
  background-color: #0CF;
}

NOTE Parent element state can only affect a child's element state so you can use:

.image:hover + .layer {
  background-color: #0CF;
}
.image:hover {
  background-color: #0CF;
}

but you can not use

.layer:hover + .image {
  background-color: #0CF;
}

To switch from vertical split to horizontal split fast in Vim

The following ex commands will (re-)split any number of windows:

  • To split vertically (e.g. make vertical dividers between windows), type :vertical ball
  • To split horizontally, type :ball

If there are hidden buffers, issuing these commands will also make the hidden buffers visible.

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

Problem solved! I'm using Ctrl + Alt + E to open Exception Window, and I checked all throw checkbox. So the debuger can stop at the exactly the error code.

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When indicating HTTP Basic Authentication we return something like:

WWW-Authenticate: Basic realm="myRealm"

Whereas Basic is the scheme and the remainder is very much dependent on that scheme. In this case realm just provides the browser a literal that can be displayed to the user when prompting for the user id and password.

You're obviously not using Basic however since there is no point having session expiry when Basic Auth is used. I assume you're using some form of Forms based authentication.

From recollection, Windows Challenge Response uses a different scheme and different arguments.

The trick is that it's up to the browser to determine what schemes it supports and how it responds to them.

My gut feel if you are using forms based authentication is to stay with the 200 + relogin page but add a custom header that the browser will ignore but your AJAX can identify.

For a really good User + AJAX experience, get the script to hang on to the AJAX request that found the session expired, fire off a relogin request via a popup, and on success, resubmit the original AJAX request and carry on as normal.

Avoid the cheat that just gets the script to hit the site every 5 mins to keep the session alive cause that just defeats the point of session expiry.

The other alternative is burn the AJAX request but that's a poor user experience.

How to draw circle by canvas in Android?

    private Paint green = new Paint();

    private int greenx , greeny;


 green.setColor(Color.GREEN);

        green.setAntiAlias(false);

        canvas.drawCircle(greenx,greeny,20,green);

How to read an external properties file in Maven

Using the suggested Maven properties plugin I was able to read in a buildNumber.properties file that I use to version my builds.

  <build>    
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>properties-maven-plugin</artifactId>
        <version>1.0-alpha-1</version>
        <executions>
          <execution>
            <phase>initialize</phase>
            <goals>
              <goal>read-project-properties</goal>
            </goals>
            <configuration>
              <files>
                <file>${basedir}/../project-parent/buildNumber.properties</file>
              </files>
            </configuration>
          </execution>
        </executions>
      </plugin>
   </plugins>

Aligning textviews on the left and right edges in Android layout

enter image description here

This Code will Divide the control into two equal sides.

    <LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linearLayout">
    <TextView
        android:text = "Left Side"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight = "1"
        android:id = "@+id/txtLeft"/>

    <TextView android:text = "Right Side"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight = "1"
        android:id = "@+id/txtRight"/>
    </LinearLayout>

Getting an element from a Set

Quick helper method that might address this situation:

<T> T onlyItem(Collection<T> items) {
    if (items.size() != 1)
        throw new IllegalArgumentException("Collection must have single item; instead it has " + items.size());

    return items.iterator().next();
}

Convert a number range to another range, maintaining ratio

Java Version

Always works no matter what you feed it!

I left everything expanded out so that it's easier to follow for learning. Rounding at the end, of course, is optional.

    private long remap(long p, long Amin, long Amax, long Bmin, long Bmax ) {

    double deltaA = Amax - Amin;
    double deltaB = Bmax - Bmin;
    double scale  = deltaB / deltaA;
    double negA   = -1 * Amin;
    double offset = (negA * scale) + Bmin;
    double q      = (p * scale) + offset;
    return Math.round(q);

}

Read url to string in few lines of java code

Now that some time has passed since the original answer was accepted, there's a better approach:

String out = new Scanner(new URL("http://www.google.com").openStream(), "UTF-8").useDelimiter("\\A").next();

If you want a slightly fuller implementation, which is not a single line, do this:

public static String readStringFromURL(String requestURL) throws IOException
{
    try (Scanner scanner = new Scanner(new URL(requestURL).openStream(),
            StandardCharsets.UTF_8.toString()))
    {
        scanner.useDelimiter("\\A");
        return scanner.hasNext() ? scanner.next() : "";
    }
}

How can I see the entire HTTP request that's being sent by my Python application?

The verbose configuration option might allow you to see what you want. There is an example in the documentation.

NOTE: Read the comments below: The verbose config options doesn't seem to be available anymore.

Disable LESS-CSS Overwriting calc()

Apart from using an escaped value as described in my other answer, it is also possible to fix this issue by enabling the Strict Math setting.

With strict math on, only maths that are inside unnecessary parentheses will be processed, so your code:

width: calc(100% - 200px);

Would work as expected with the strict math option enabled.

However, note that Strict Math is applied globally, not only inside calc(). That means, if you have:

font-size: 12px + 2px;

The math will no longer be processed by Less -- it will output font-size: 12px + 2px which is, obviously, invalid CSS. You'd have to wrap all maths that should be processed by Less in (previously unnecessary) parentheses:

font-size: (12px + 2px);

Strict Math is a nice option to consider when starting a new project, otherwise you'd possibly have to rewrite a good part of the code base. For the most common use cases, the escaped string approach described in the other answer is more suitable.

"Actual or formal argument lists differs in length"

The default constructor has no arguments. You need to specify a constructor:

    public Friends( String firstName, String age) { ... }

How to list branches that contain a given commit?

The answer for git branch -r --contains <commit> works well for normal remote branches, but if the commit is only in the hidden head namespace that GitHub creates for PRs, you'll need a few more steps.

Say, if PR #42 was from deleted branch and that PR thread has the only reference to the commit on the repo, git branch -r doesn't know about PR #42 because refs like refs/pull/42/head aren't listed as a remote branch by default.

In .git/config for the [remote "origin"] section add a new line:

fetch = +refs/pull/*/head:refs/remotes/origin/pr/*

(This gist has more context.)

Then when you git fetch you'll get all the PR branches, and when you run git branch -r --contains <commit> you'll see origin/pr/42 contains the commit.

What's the difference between a temp table and table variable in SQL Server?

  1. Temp table: A Temp table is easy to create and back up data.

    Table variable: But the table variable involves the effort when we usually create the normal tables.

  2. Temp table: Temp table result can be used by multiple users.

    Table variable: But the table variable can be used by the current user only. 

  3. Temp table: Temp table will be stored in the tempdb. It will make network traffic. When we have large data in the temp table then it has to work across the database. A Performance issue will exist.

    Table variable: But a table variable will store in the physical memory for some of the data, then later when the size increases it will be moved to the tempdb.

  4. Temp table: Temp table can do all the DDL operations. It allows creating the indexes, dropping, altering, etc..,

    Table variable: Whereas table variable won't allow doing the DDL operations. But the table variable allows us to create the clustered index only.

  5. Temp table: Temp table can be used for the current session or global. So that a multiple user session can utilize the results in the table.

    Table variable: But the table variable can be used up to that program. (Stored procedure)

  6. Temp table: Temp variable cannot use the transactions. When we do the DML operations with the temp table then it can be rollback or commit the transactions.

    Table variable: But we cannot do it for table variable.

  7. Temp table: Functions cannot use the temp variable. More over we cannot do the DML operation in the functions .

    Table variable: But the function allows us to use the table variable. But using the table variable we can do that.

  8. Temp table: The stored procedure will do the recompilation (can't use same execution plan) when we use the temp variable for every sub sequent calls.

    Table variable: Whereas the table variable won't do like that.

Where are include files stored - Ubuntu Linux, GCC

The \#include files of gcc are stored in /usr/include . The standard include files of g++ are stored in /usr/include/c++.

Stock ticker symbol lookup API

Google Finance does let you retrieve up to 100 stock quotes at once using the following URL:

www.google.com/finance/info?infotype=infoquoteall&q=[ticker1],[ticker2],...,[tickern]

For example:

www.google.com/finance/info?infotype=infoquoteall&q=C,JPM,AIG

Someone has deciphered the available fields here:

http://qsb-mac.googlecode.com/svn/trunk/Vermilion/Modules/StockQuoter/StockQuoter.py

The current price ("l") is real-time and the delay is on par with Yahoo Finance. There are a few quirks you should be aware of. A handful of stocks require an exchange prefix. For example, if you query "BTIM", you'll get a "Bad Request" error but "AMEX:BTIM" works. A few stocks don't work even with the exchange prefix. For example, querying "FTWRD" and "NASDAQ:FTWRD" both generate "Bad Request" errors even though Google Finance does have information for this NASDAQ stock.

The "el" field, if present, tells you the current pre-market or after-hours price.

Could not find main class HelloWorld

It looks that you had done all setup properly but there might be one area where it might be causing problem

Check the value of your "CLASSPATH" variable and make sure at the end you kept ;.

Note: ; is for end separator . is for including existing path at the end

How can I remove the first line of a text file using bash/sed script?

Could use vim to do this:

vim -u NONE +'1d' +'wq!' /tmp/test.txt

This should be faster, since vim won't read whole file when process.

How to append to the end of an empty list?

Note that you also can use insert in order to put number into the required position within list:

initList = [1,2,3,4,5]
initList.insert(2, 10) # insert(pos, val) => initList = [1,2,10,3,4,5]

And also note that in python you can always get a list length using method len()

How do I assign ls to an array in Linux Bash?

Whenever possible, you should avoid parsing the output of ls (see Greg's wiki on the subject). Basically, the output of ls will be ambiguous if there are funny characters in any of the filenames. It's also usually a waste of time. In this case, when you execute ls -d */, what happens is that the shell expands */ to a list of subdirectories (which is already exactly what you want), passes that list as arguments to ls -d, which looks at each one, says "yep, that's a directory all right" and prints it (in an inconsistent and sometimes ambiguous format). The ls command isn't doing anything useful!

Well, ok, it is doing one thing that's useful: if there are no subdirectories, */ will get left as is, ls will look for a subdirectory named "*", not find it, print an error message that it doesn't exist (to stderr), and not print the "*/" (to stdout).

The cleaner way to make an array of subdirectory names is to use the glob (*/) without passing it to ls. But in order to avoid putting "*/" in the array if there are no actual subdirectories, you should set nullglob first (again, see Greg's wiki):

shopt -s nullglob
array=(*/)
shopt -u nullglob # Turn off nullglob to make sure it doesn't interfere with anything later
echo "${array[@]}"  # Note double-quotes to avoid extra parsing of funny characters in filenames

If you want to print an error message if there are no subdirectories, you're better off doing it yourself:

if (( ${#array[@]} == 0 )); then
    echo "No subdirectories found" >&2
fi

Count unique values with pandas per groups

You need nunique:

df = df.groupby('domain')['ID'].nunique()

print (df)
domain
'facebook.com'    1
'google.com'      1
'twitter.com'     2
'vk.com'          3
Name: ID, dtype: int64

If you need to strip ' characters:

df = df.ID.groupby([df.domain.str.strip("'")]).nunique()
print (df)
domain
facebook.com    1
google.com      1
twitter.com     2
vk.com          3
Name: ID, dtype: int64

Or as Jon Clements commented:

df.groupby(df.domain.str.strip("'"))['ID'].nunique()

You can retain the column name like this:

df = df.groupby(by='domain', as_index=False).agg({'ID': pd.Series.nunique})
print(df)
    domain  ID
0       fb   1
1      ggl   1
2  twitter   2
3       vk   3

The difference is that nunique() returns a Series and agg() returns a DataFrame.

Get Month name from month number

This should return month text (January - December) from the month index (1-12)

int monthNumber = 1; //1-12  
string monthName = new DateTimeFormatInfo().GetMonthName(monthNumber);

CSS selector for "foo that contains bar"?

No, what you are looking for would be called a parent selector. CSS has none; they have been proposed multiple times but I know of no existing or forthcoming standard including them. You are correct that you would need to use something like jQuery or use additional class annotations to achieve the effect you want.

Here are some similar questions with similar results:

How to include files outside of Docker's build context?

If you read the discussion in the issue 2745 not only docker may never support symlinks they may never support adding files outside your context. Seems to be a design philosophy that files that go into docker build should explicitly be part of its context or be from a URL where it is presumably deployed too with a fixed version so that the build is repeatable with well known URLs or files shipped with the docker container.

I prefer to build from a version controlled source - ie docker build -t stuff http://my.git.org/repo - otherwise I'm building from some random place with random files.

fundamentally, no.... -- SvenDowideit, Docker Inc

Just my opinion but I think you should restructure to separate out the code and docker repositories. That way the containers can be generic and pull in any version of the code at run time rather than build time.

Alternatively, use docker as your fundamental code deployment artifact and then you put the dockerfile in the root of the code repository. if you go this route probably makes sense to have a parent docker container for more general system level details and a child container for setup specific to your code.

How do I convert NSInteger to NSString datatype?

Easy way to do:

NSInteger value = x;
NSString *string = [@(value) stringValue];

Here the @(value) converts the given NSInteger to an NSNumber object for which you can call the required function, stringValue.

How to show multiline text in a table cell

I added only <br> inside the <td> and it works good, break the line!

Rename all files in a folder with a prefix in a single command

Try the rename command in the folder with the files:

rename 's/^/Unix_/' *

The argument of rename (sed s command) indicates to replace the regex ^ with Unix_. The caret (^) is a special character that means start of the line.

MySQL LIMIT on DELETE statement

the delete query only allows for modifiers after the DELETE 'command' to tell the database what/how do handle things.

see this page

Why do we use __init__ in Python classes?

It seems like you need to use __init__ in Python if you want to correctly initialize mutable attributes of your instances.

See the following example:

>>> class EvilTest(object):
...     attr = []
... 
>>> evil_test1 = EvilTest()
>>> evil_test2 = EvilTest()
>>> evil_test1.attr.append('strange')
>>> 
>>> print "This is evil:", evil_test1.attr, evil_test2.attr
This is evil: ['strange'] ['strange']
>>> 
>>> 
>>> class GoodTest(object):
...     def __init__(self):
...         self.attr = []
... 
>>> good_test1 = GoodTest()
>>> good_test2 = GoodTest()
>>> good_test1.attr.append('strange')
>>> 
>>> print "This is good:", good_test1.attr, good_test2.attr
This is good: ['strange'] []

This is quite different in Java where each attribute is automatically initialized with a new value:

import java.util.ArrayList;
import java.lang.String;

class SimpleTest
{
    public ArrayList<String> attr = new ArrayList<String>();
}

class Main
{
    public static void main(String [] args)
    {
        SimpleTest t1 = new SimpleTest();
        SimpleTest t2 = new SimpleTest();

        t1.attr.add("strange");

        System.out.println(t1.attr + " " + t2.attr);
    }
}

produces an output we intuitively expect:

[strange] []

But if you declare attr as static, it will act like Python:

[strange] [strange]

Checking Bash exit status of several commands efficiently

Instead of creating runner functions or using set -e, use a trap:

trap 'echo "error"; do_cleanup failed; exit' ERR
trap 'echo "received signal to stop"; do_cleanup interrupted; exit' SIGQUIT SIGTERM SIGINT

do_cleanup () { rm tempfile; echo "$1 $(date)" >> script_log; }

command1
command2
command3

The trap even has access to the line number and the command line of the command that triggered it. The variables are $BASH_LINENO and $BASH_COMMAND.

View HTTP headers in Google Chrome?

For me, as of Google Chrome Version 46.0.2490.71 m, the Headers info area is a little hidden. To access:

  1. While the browser is open, press F12 to access Web Developer tools

  2. When opened, click the "Network" option

  3. Initially, it is possible the page data is not present/up to date. Refresh the page if necessary

  4. Observe the page information appears in the listing. (Also, make sure "All" is selected next to the "Hide data URLs" checkbox)

see screenshot

Matplotlib - global legend and title aside subplots

In addition to the orbeckst answer one might also want to shift the subplots down. Here's an MWE in OOP style:

import matplotlib.pyplot as plt

fig = plt.figure()
st = fig.suptitle("suptitle", fontsize="x-large")

ax1 = fig.add_subplot(311)
ax1.plot([1,2,3])
ax1.set_title("ax1")

ax2 = fig.add_subplot(312)
ax2.plot([1,2,3])
ax2.set_title("ax2")

ax3 = fig.add_subplot(313)
ax3.plot([1,2,3])
ax3.set_title("ax3")

fig.tight_layout()

# shift subplots down:
st.set_y(0.95)
fig.subplots_adjust(top=0.85)

fig.savefig("test.png")

gives:

enter image description here

How do I add a user when I'm using Alpine as a base image?

Alpine uses the command adduser and addgroup for creating users and groups (rather than useradd and usergroup).

FROM alpine:latest

# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Tell docker that all future commands should run as the appuser user
USER appuser

The flags for adduser are:

Usage: adduser [OPTIONS] USER [GROUP]

Create new user, or add USER to GROUP

        -h DIR          Home directory
        -g GECOS        GECOS field
        -s SHELL        Login shell
        -G GRP          Group
        -S              Create a system user
        -D              Don't assign a password
        -H              Don't create home directory
        -u UID          User id
        -k SKEL         Skeleton directory (/etc/skel)

Add new user official docs

Test for multiple cases in a switch, like an OR (||)

You need to make two case labels.

Control will fall through from the first label to the second, so they'll both execute the same code.

How to correctly catch change/focusOut event on text input in React.js?

You'd need to be careful as onBlur has some caveats in IE11 (How to use relatedTarget (or equivalent) in IE?, https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget).

There is, however, no way to use onFocusOut in React as far as I can tell. See the issue on their github https://github.com/facebook/react/issues/6410 if you need more information.

Loop through the rows of a particular DataTable

For Each row As DataRow In dtDataTable.Rows
    strDetail = row.Item("Detail")
Next row

There's also a shorthand:

For Each row As DataRow In dtDataTable.Rows
    strDetail = row("Detail")
Next row

Note that Microsoft's style guidelines for .Net now specifically recommend against using hungarian type prefixes for variables. Instead of "strDetail", for example, you should just use "Detail".

Twitter Bootstrap - add top space between rows

Bootstrap3

CSS (gutter only, without margins around):

.row.row-gutter {
  margin-bottom: -15px;
  overflow: hidden;
}
.row.row-gutter > *[class^="col"] {
  margin-bottom: 15px;
}

CSS (equal margins around, 15px/2):

.row.row-margins {
  padding-top: 7px; /* or margin-top: 7px; */
  padding-bottom: 7px; /* or margin-bottom: 7px; */
}
.row.row-margins > *[class^="col"] {
  margin-top: 8px;
  margin-bottom: 8px;
}

Usage:

<div class="row row-gutter">
    <div class="col col-sm-9">first</div>
    <div class="col col-sm-3">second</div>
    <div class="col col-sm-12">third</div>
</div>

(with SASS or LESS 15px could be a variable from bootstrap)

JQuery: detect change in input field

Same functionality i recently achieved using below function.

I wanted to enable SAVE button on edit.

  1. Change event is NOT advisable as it will ONLY be fired if after editing, mouse is clicked somewhere else on the page before clicking SAVE button.
  2. Key Press doesnt handle Backspace, Delete and Paste options.
  3. Key Up handles everything including tab, Shift key.

Hence i wrote below function combining keypress, keyup (for backspace, delete) and paste event for text fields.

Hope it helps you.

function checkAnyFormFieldEdited() {
    /*
     * If any field is edited,then only it will enable Save button
     */
    $(':text').keypress(function(e) { // text written
        enableSaveBtn();
    });

    $(':text').keyup(function(e) {
        if (e.keyCode == 8 || e.keyCode == 46) { //backspace and delete key
            enableSaveBtn();
        } else { // rest ignore
            e.preventDefault();
        }
    });
    $(':text').bind('paste', function(e) { // text pasted
        enableSaveBtn();
    });

    $('select').change(function(e) { // select element changed
        enableSaveBtn();
    });

    $(':radio').change(function(e) { // radio changed
        enableSaveBtn();
    });

    $(':password').keypress(function(e) { // password written
        enableSaveBtn();
    });
    $(':password').bind('paste', function(e) { // password pasted
        enableSaveBtn();
    });


}

How to force browser to download file?

Set content-type and other headers before you write the file out. For small files the content is buffered, and the browser gets the headers first. For big ones the data come first.

Host binding and Host listening

This is the simple example to use both of them:

import {
  Directive, HostListener, HostBinding
}
from '@angular/core';

@Directive({
  selector: '[Highlight]'
})
export class HighlightDirective {
  @HostListener('mouseenter') mouseover() {
    this.backgroundColor = 'green';
  };

  @HostListener('mouseleave') mouseleave() {
    this.backgroundColor = 'white';
  }

  @HostBinding('style.backgroundColor') get setColor() {
     return this.backgroundColor;
  };

  private backgroundColor = 'white';
  constructor() {}

}

Introduction:

  1. HostListener can bind an event to the element.

  2. HostBinding can bind a style to the element.

  3. this is directive, so we can use it for

    Some Text
  4. So according to the debug, we can find that this div has been binded style = "background-color:white"

    Some Text
  5. we also can find that EventListener of this div has two event: mouseenter and mouseleave. So when we move the mouse into the div, the colour will become green, mouse leave, the colour will become white.

HTML: How to make a submit button with text + image in it?

You're really close to the answer yourself

<button type="submit">
<img src="save.gif" alt="Save icon"/>
<br/>
Save
</button>

Or, you can just remove the type-attribute

<button>
<img src="save.gif" alt="Save icon"/>
<br/>
Save
</button>

System.Data.OracleClient requires Oracle client software version 8.1.7

I've run into this error dozens of times:

Cause

Security permissions were not properly set when the Oracle client was installed on Windows with NTFS. The result of this is that content of the ORACLE_HOME directory is not visible to Authenticated Users on the machine; this causes an error while the System.Data.OracleClient is communicating with the Oracle Connectivity software from ASP.NET using Authenticated User privileges.

Solution

To fix the problem you have to give the Authenticated Users group privilege to the Oracle Home directory.

  • Log on to Windows as a user with Administrator privileges.
  • Start Windows Explorer and navigate to the ORACLE_HOME folder.
  • Choose properties on the ORACLE_HOME folder.
  • Click the Security tab of the Properties window.
  • Click on Authenticated Users item in the Name list.
  • Un-check the Read and Execute box in the Permissions list under the Allow column.
  • Re-check the Read and Execute box under the Allow column.
  • Click the Advanced button and in the Permission Entries verify that Authenticated Users are listed with permission: Read & Execute, and Apply To: This folder, subfolders and files. If not, edit that line and make sure that Apply To drop-down box is set to This folder, subfolders and files. This should already be set properly but it is important that you verify it.
  • Click the OK button until you close out all of the security properties windows. The cursor may present the hour glass for a few seconds as it applies the permissions you just changed to all subfolders and files.
  • Reboot, to assure that the changes have taken effect.

Try your application again.

What are the differences between virtual memory and physical memory?

See here: Physical Vs Virtual Memory

Virtual memory is stored on the hard drive and is used when the RAM is filled. Physical memory is limited to the size of the RAM chips installed in the computer. Virtual memory is limited by the size of the hard drive, so virtual memory has the capability for more storage.

On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activities

It seems a rite of passage that a new Android programmer spends a day researching this issue and reading all of these StackOverflow threads. I am now newly initiated and I leave here trace of my humble experience to help a future pilgrim.

First, there is no obvious or immediate way to do this per my research (as of September 2012). You'd think you could simple startActivity(new Intent(this, LoginActivity.class), CLEAR_STACK) but no.

You CAN do startActivity(new Intent(this, LoginActivity.class)) with FLAG_ACTIVITY_CLEAR_TOP - and this will cause the framework to search down the stack, find your earlier original instance of LoginActivity, recreate it and clear the rest of the (upwards) stack. And since Login is presumably at the bottom of the stack, you now have an empty stack and the Back button just exits the application.

BUT - this only works if you previously left that original instance of LoginActivity alive at the base of your stack. If, like many programmers, you chose to finish() that LoginActivity once the user has successfully logged in, then it's no longer on the base of the stack and the FLAG_ACTIVITY_CLEAR_TOP semantics do not apply ... you end up creating a new LoginActivity on top of the existing stack. Which is almost certainly NOT what you want (weird behavior where the user can 'back' their way out of login into a previous screen).

So if you have previously finish()'d the LoginActivity, you need to pursue some mechanism for clearing your stack and then starting a new LoginActivity. It seems like the answer by @doreamon in this thread is the best solution (at least to my humble eye):

https://stackoverflow.com/a/9580057/614880

I strongly suspect that the tricky implications of whether you leave LoginActivity alive are causing a lot of this confusion.

Good Luck.

How can I add a column that doesn't allow nulls in a Postgresql database?

You either need to define a default, or do what Sean says and add it without the null constraint until you've filled it in on the existing rows.

How to create a folder with name as current date in batch (.bat) files

setlocal enableextensions 
set name="%DATE:/=_%"
mkdir %name%

to create only one folder like "Tue 01_28_2020"

How to play a local video with Swift?

PlayerView for swift 4.2

import AVFoundation
import UIKit

class PlayerView: UIView {

    var player: AVPlayer? {
        get {
            return playerLayer.player
        }
        set {
            playerLayer.player = newValue
        }
    }

    var playerLayer: AVPlayerLayer {
        return layer as! AVPlayerLayer
    }

    // Override UIView property
    override static var layerClass: AnyClass {
        return AVPlayerLayer.self
    }
}

How to show progress bar while loading, using ajax

_x000D_
_x000D_
$(document).ready(function () { _x000D_
 $(document).ajaxStart(function () {_x000D_
        $('#wait').show();_x000D_
    });_x000D_
    $(document).ajaxStop(function () {_x000D_
        $('#wait').hide();_x000D_
    });_x000D_
    $(document).ajaxError(function () {_x000D_
        $('#wait').hide();_x000D_
    });   _x000D_
});
_x000D_
<div id="wait" style="display: none; width: 100%; height: 100%; top: 100px; left: 0px; position: fixed; z-index: 10000; text-align: center;">_x000D_
            <img src="../images/loading_blue2.gif" width="45" height="45" alt="Loading..." style="position: fixed; top: 50%; left: 50%;" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Difference between Hashing a Password and Encrypting it

Hashing:

It is a one-way algorithm and once hashed can not rollback and this is its sweet point against encryption.

Encryption

If we perform encryption, there will a key to do this. If this key will be leaked all of your passwords could be decrypted easily.

On the other hand, even if your database will be hacked or your server admin took data from DB and you used hashed passwords, the hacker will not able to break these hashed passwords. This would actually practically impossible if we use hashing with proper salt and additional security with PBKDF2.

If you want to take a look at how should you write your hash functions, you can visit here.

There are many algorithms to perform hashing.

  1. MD5 - Uses the Message Digest Algorithm 5 (MD5) hash function. The output hash is 128 bits in length. The MD5 algorithm was designed by Ron Rivest in the early 1990s and is not a preferred option today.

  2. SHA1 - Uses Security Hash Algorithm (SHA1) hash published in 1995. The output hash is 160 bits in length. Although most widely used, this is not a preferred option today.

  3. HMACSHA256, HMACSHA384, HMACSHA512 - Use the functions SHA-256, SHA-384, and SHA-512 of the SHA-2 family. SHA-2 was published in 2001. The output hash lengths are 256, 384, and 512 bits, respectively,as the hash functions’ names indicate.

Disable clipboard prompt in Excel VBA on workbook close

I can offer two options

  1. Direct copy

Based on your description I'm guessing you are doing something like

Set wb2 = Application.Workbooks.Open("YourFile.xls")
wb2.Sheets("YourSheet").[<YourRange>].Copy
ThisWorkbook.Sheets("SomeSheet").Paste
wb2.close

If this is the case, you don't need to copy via the clipboard. This method copies from source to destination directly. No data in clipboard = no prompt

Set wb2 = Application.Workbooks.Open("YourFile.xls")
wb2.Sheets("YourSheet").[<YourRange>].Copy ThisWorkbook.Sheets("SomeSheet").Cells(<YourCell")
wb2.close
  1. Suppress prompt

You can prevent all alert pop-ups by setting

Application.DisplayAlerts = False

[Edit]

  1. To copy values only: don't use copy/paste at all

Dim rSrc As Range
Dim rDst As Range
Set rSrc = wb2.Sheets("YourSheet").Range("YourRange")
Set rDst = ThisWorkbook.Sheets("SomeSheet").Cells("YourCell").Resize(rSrc.Rows.Count, rSrc.Columns.Count)
rDst = rSrc.Value

How can I position my div at the bottom of its container?

Using the translateY and top property

Just set element child to position: relative and than move it top: 100% (that's the 100% height of the parent) and stick to bottom of parent by transform: translateY(-100%) (that's -100% of the height of the child).

BenefitS

  • you do not take the element from the page flow
  • it is dynamic

But still just workaround :(

.copyright{
   position: relative;
   top: 100%;
   transform: translateY(-100%);
}

Don't forget prefixes for the older browser.

SFTP file transfer using Java JSch

Below code works for me

   public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
  Session session = jsch.getSession(user, host);
  session.setPassword(password);
  session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

OR using StrictHostKeyChecking as "NO" (security consequences)

public static void sftpsript(String filepath) {

 try {
  String user ="demouser"; // username for remote host
  String password ="demo123"; // password of the remote host

   String host = "demo.net"; // remote host address
  JSch jsch = new JSch();
   Session session = jsch.getSession(user, host, 22);
   Properties config = new Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);;
   session.setPassword(password);
   System.out.println("user=="+user+"\n host=="+host);
   session.connect();

  ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
  sftpChannel.connect();

  sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
  sftpChannel.disconnect();
  session.disconnect();
 }catch(Exception ex){
     ex.printStackTrace();
 }
   }

Cannot find the declaration of element 'beans'

Try Using this- Spring 4.0. Working

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans                                               http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context.xsd"> 

How to hide 'Back' button on navigation bar on iPhone?

try this one - self.navigationController?.navigationItem.hidesBackButton = true

Get timezone from users browser using moment(timezone).js

Using Moment library, see their website -> https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/

i notice they also user their own library in their website, so you can have a try using the browser console before installing it

moment().tz(String);

The moment#tz mutator will change the time zone and update the offset.

moment("2013-11-18").tz("America/Toronto").format('Z'); // -05:00
moment("2013-11-18").tz("Europe/Berlin").format('Z');   // +01:00

This information is used consistently in other operations, like calculating the start of the day.

var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.format();                     // 2013-11-18T11:55:00-05:00
m.startOf("day").format();      // 2013-11-18T00:00:00-05:00
m.tz("Europe/Berlin").format(); // 2013-11-18T06:00:00+01:00
m.startOf("day").format();      // 2013-11-18T00:00:00+01:00

Without an argument, moment#tz returns:

    the time zone name assigned to the moment instance or
    undefined if a time zone has not been set.

var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.tz();  // America/Toronto
var m = moment.tz("2013-11-18 11:55");
m.tz() === undefined;  // true

mcrypt is deprecated, what is the alternative?

Pure-PHP implementation of Rijndael exists with phpseclib available as composer package and works on PHP 7.3 (tested by me).

There's a page on the phpseclib docs, which generates sample code after you input the basic variables (cipher, mode, key size, bit size). It outputs the following for Rijndael, ECB, 256, 256:

a code with mycrypt

$decoded = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, ENCRYPT_KEY, $term, MCRYPT_MODE_ECB);

works like this with the library

$rijndael = new \phpseclib\Crypt\Rijndael(\phpseclib\Crypt\Rijndael::MODE_ECB);
$rijndael->setKey(ENCRYPT_KEY);
$rijndael->setKeyLength(256);
$rijndael->disablePadding();
$rijndael->setBlockLength(256);

$decoded = $rijndael->decrypt($term);

* $term was base64_decoded

Create a shortcut on Desktop

For Windows Vista/7/8/10, you can create a symlink instead via mklink.

Process.Start("cmd.exe", $"/c mklink {linkName} {applicationPath}");

Alternatively, call CreateSymbolicLink via P/Invoke.

How do I scroll a row of a table into view (element.scrollintoView) using jQuery?

Same from above with little modification

_x000D_
_x000D_
function focusMe() {_x000D_
       var rowpos = $('#FocusME').position();_x000D_
        rowpos.top = rowpos.top - 30;_x000D_
        $('#container').scrollTop(rowpos.top);_x000D_
    }
_x000D_
<html>_x000D_
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>_x000D_
<body>_x000D_
    <input type="button" onclick="focusMe()" value="focus">_x000D_
    <div id="container" style="max-height:200px;overflow:scroll;">_x000D_
        <table>_x000D_
            <tr>_x000D_
                <td>1</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>2</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>3</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>4</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>5</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>6</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>7</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>8</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>9</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr id="FocusME">_x000D_
                <td>10</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>11</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>12</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>13</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>14</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>15</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>16</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>17</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>18</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>19</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <td>20</td>_x000D_
                <td></td>_x000D_
            </tr>_x000D_
        </table>_x000D_
    </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Convert HTML Character Back to Text Using Java Standard Library

As @jem suggested, it is possible to use jsoup.

With jSoup 1.8.3 it il possible to use the method Parser.unescapeEntities that retain the original html.

import org.jsoup.parser.Parser;
...
String html = Parser.unescapeEntities(original_html, false);

It seems that in some previous release this method is not present.

Timeout for python requests.get entire response

Well, I tried many solutions on this page and still faced instabilities, random hangs, poor connections performance.

I'm now using Curl and i'm really happy about it's "max time" functionnality and about the global performances, even with such a poor implementation :

content=commands.getoutput('curl -m6 -Ss "http://mywebsite.xyz"')

Here, I defined a 6 seconds max time parameter, englobing both connection and transfer time.

I'm sure Curl has a nice python binding, if you prefer to stick to the pythonic syntax :)

Python dictionary: are keys() and values() always the same order?

I wasn't satisfied with these answers since I wanted to ensure the exported values had the same ordering even when using different dicts.

Here you specify the key order upfront, the returned values will always have the same order even if the dict changes, or you use a different dict.

keys = dict1.keys()
ordered_keys1 = [dict1[cur_key] for cur_key in keys]
ordered_keys2 = [dict2[cur_key] for cur_key in keys]

Bootstrap 3 scrollable div for table

Well one way to do it is set the height of your body to the height that you want your page to be. In this example I did 600px.

Then set your wrapper height to a percentage of the body here I did 70% This will adjust your table so that it does not fill up the whole screen but in stead just takes up a percentage of the specified page height.

body {
   padding-top: 70px;
   border:1px solid black;
   height:600px;
}

.mygrid-wrapper-div {
   border: solid red 5px;
   overflow: scroll;
   height: 70%;
}

http://jsfiddle.net/4NB2N/7/

Update How about a jQuery approach.

$(function() {  
   var window_height = $(window).height(),
   content_height = window_height - 200;
   $('.mygrid-wrapper-div').height(content_height);
});

$( window ).resize(function() {
   var window_height = $(window).height(),
   content_height = window_height - 200;
   $('.mygrid-wrapper-div').height(content_height);
});

http://jsfiddle.net/4NB2N/11/

Pass a JavaScript function as parameter

Example 1:

funct("z", function (x) { return x; });

function funct(a, foo){
    foo(a) // this will return a
}

Example 2:

function foodemo(value){
    return 'hello '+value;
}

function funct(a, foo){
    alert(foo(a));
}

//call funct    
funct('world!',foodemo); //=> 'hello world!'

look at this

Is there a way to override class variables in Java?

If you are going to override it I don't see a valid reason to keep this static. I would suggest the use of abstraction (see example code). :

     public interface Person {
        public abstract String getName();
       //this will be different for each person, so no need to make it concrete
        public abstract void setName(String name);
    }

Now we can add the Dad:

public class Dad implements Person {

    private String name;

    public Dad(String name) {
        setName(name);
    }

    @Override
    public final String getName() {
    return name;
    }

    @Override
    public final void setName(String name) {
        this.name = name;
    }
}

the son:

public class Son implements Person {

    private String name;

    public Son(String name) {
        setName(name);
    }

    @Override
    public final String getName() {
        return name;
    }

    @Override
    public final void setName(String name) {
        this.name = name;
    }
}

and Dad met a nice lady:

public class StepMom implements Person {

    private String name;

    public StepMom(String name) {
        setName(name);
    }

    @Override
    public final String getName() {
        return name;
    }

    @Override
    public final void setName(String name) {
        this.name = name;
    }
}

Looks like we have a family, lets tell the world their names:

public class ConsoleGUI {

    public static void main(String[] args) {
        List<Person> family = new ArrayList<Person>();
        family.add(new Son("Tommy"));
        family.add(new StepMom("Nancy"));
        family.add(new Dad("Dad"));
        for (Person person : family) {
            //using the getName vs printName lets the caller, in this case the
            //ConsoleGUI determine versus being forced to output through the console. 
            System.out.print(person.getName() + " ");
            System.err.print(person.getName() + " ");
            JOptionPane.showMessageDialog(null, person.getName());
    }
}

}

System.out Output : Tommy Nancy Dad
System.err is the same as above(just has red font)
JOption Output:
Tommy then
Nancy then
Dad

How to get config parameters in Symfony2 Twig Templates

On newer versions of Symfony2 (using a parameters.yml instead of parameters.ini), you can store objects or arrays instead of key-value pairs, so you can manage your globals this way:

config.yml (edited only once):

# app/config/config.yml
twig:
  globals:
    project: %project%

parameters.yml:

# app/config/parameters.yml
project:
  name:       myproject.com
  version:    1.1.42

And then in a twig file, you can use {{ project.version }} or {{ project.name }}.

Note: I personally dislike adding things to app, just because that's the Symfony's variable and I don't know what will be stored there in the future.

How can I find out if an .EXE has Command-Line Options?

Invoke it from the shell, with an argument like /? or --help. Those are the usual help switches.

Determining image file size + dimensions via Javascript?

Getting the Original Dimensions of the Image

If you need to get the original image dimensions (not in the browser context), clientWidth and clientHeight properties do not work since they return incorrect values if the image is stretched/shrunk via css.

To get original image dimensions, use naturalHeight and naturalWidth properties.

var img = document.getElementById('imageId'); 

var width = img.naturalWidth;
var height = img.naturalHeight;

p.s. This does not answer the original question as the accepted answer does the job. This, instead, serves like addition to it.

How to sort a data frame by alphabetic order of a character variable in R?

This really belongs with @Ramnath's answer but I can't comment as I don't have enough reputation yet. You can also use the arrange function from the dplyr package in the same way as the plyr package.

library(dplyr)
arrange(DF, ID, desc(num))

Failed to load c++ bson extension

Followint @user1548357 I decided to change the module file itself. So as to avoid the problems pointed out by the valid comments below I included my changes in a postinstall script so that I can set it and forget it and be assured that it will run when my modules are installed.

// package.json
"scripts": {
    // other scripts
    "postinstall": "node ./bson.fix.js"
},

and the script is:

// bson.fix.js
var fs = require('fs');
var file = './node_modules/bson/ext/index.js'
fs.readFile(file, 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  var result = data.replace(/\.\.\/build\/Release\/bson/g, 'bson');
  fs.writeFile(file, result, 'utf8', function (err) {
     if (err) return console.log(err);
     console.log('Fixed bson module so as to use JS version');
  });
});

Find elements inside forms and iframe using Java and Selenium WebDriver

By using https://github.com/nick318/FindElementInFrames You can find webElement across all frames:

SearchByFramesFactory searchFactory = new SearchByFramesFactory(driver);
SearchByFrames searchInFrame = searchFactory.search(() -> driver.findElement(By.tagName("body")));
Optional<WebElement> elem = searchInFrame.getElem();

sorting a List of Map<String, String>

You need to create a comparator. I am not sure why each value needs its own map but here is what the comparator would look like:

class ListMapComparator implements Comparator {
    public int compare(Object obj1, Object obj2) {
         Map<String, String> test1 = (Map<String, String>) obj1;
         Map<String, String> test2 = (Map<String, String>) obj2;
         return test1.get("name").compareTo(test2.get("name"));
    }
}

You can see it working with your above example with this:

public class MapSort {
    public List<Map<String, String>> testMap() {
         List<Map<String, String>> list = new ArrayList<Map<String, String>>();
         Map<String, String> myMap1 = new HashMap<String, String>();
         myMap1.put("name", "Josh");
         Map<String, String> myMap2 = new HashMap<String, String>();
         myMap2.put("name", "Anna");

         Map<String, String> myMap3 = new HashMap<String, String>();
         myMap3.put("name", "Bernie");


         list.add(myMap1);
         list.add(myMap2);
         list.add(myMap3);

         return list;
    }

    public static void main(String[] args) {
         MapSort ms = new MapSort();
         List<Map<String, String>> testMap = ms.testMap();
         System.out.println("Before Sort: " + testMap);
         Collections.sort(testMap, new ListMapComparator());
         System.out.println("After Sort: " + testMap);
    }
}

You will have some type safe warnings because I did not worry about these. Hope that helps.

How to remove all elements in String array in java?

Reassign again. Like example = new String[(size)]

How to use greater than operator with date?

I have tried but above not working after research found below the solution.

SELECT * FROM my_table where DATE(start_date) > '2011-01-01';

Ref

How to export table data in MySql Workbench to csv?

U can use mysql dump or query to export data to csv file

SELECT *
INTO OUTFILE '/tmp/products.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM products

How to embed new Youtube's live video permanent URL?

Have you tried plugin called " Youtube Live Stream Auto Embed"

Its seems to be working. Check it once.

Completely remove MariaDB or MySQL from CentOS 7 or RHEL 7

These steps are working on CentOS 6.5 so they should work on CentOS 7 too:

(EDIT - exactly the same steps work for MariaDB 10.3 on CentOS 8)

  1. yum remove mariadb mariadb-server
  2. rm -rf /var/lib/mysql If your datadir in /etc/my.cnf points to a different directory, remove that directory instead of /var/lib/mysql
  3. rm /etc/my.cnf the file might have already been deleted at step 1
  4. Optional step: rm ~/.my.cnf
  5. yum install mariadb mariadb-server

[EDIT] - Update for MariaDB 10.1 on CentOS 7

The steps above worked for CentOS 6.5 and MariaDB 10.

I've just installed MariaDB 10.1 on CentOS 7 and some of the steps are slightly different.

Step 1 would become:

yum remove MariaDB-server MariaDB-client

Step 5 would become:

yum install MariaDB-server MariaDB-client

The other steps remain the same.

What is the use of adding a null key or value to a HashMap in Java?

One example would be for modeling trees. If you are using a HashMap to represent a tree structure, where the key is the parent and the value is list of children, then the values for the null key would be the root nodes.

How to input matrix (2D list) in Python?

a = []
b = []

m=input("enter no of rows: ")
n=input("enter no of coloumns: ")

for i in range(n):
     a = []
     for j in range(m):
         a.append(input())
     b.append(a)

Input : 1 2 3 4 5 6 7 8 9

Output : [ ['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9'] ]

Environ Function code samples for VBA

As alluded to by Eric, you can use environ with ComputerName argument like so:

MsgBox Environ("USERNAME")

Some additional information that might be helpful for you to know:

  1. The arguments are not case sensitive.
  2. There is a slightly faster performing string version of the Environ function. To invoke it, use a dollar sign. (Ex: Environ$("username")) This will net you a small performance gain.
  3. You can retrieve all System Environment Variables using this function. (Not just username.) A common use is to get the "ComputerName" value to see which computer the user is logging onto from.
  4. I don't recommend it for most situations, but it can be occasionally useful to know that you can also access the variables with an index. If you use this syntax the the name of argument and the value are returned. In this way you can enumerate all available variables. Valid values are 1 - 255.
    Sub EnumSEVars()
        Dim strVar As String
        Dim i As Long
        For i = 1 To 255
            strVar = Environ$(i)
            If LenB(strVar) = 0& Then Exit For
            Debug.Print strVar
        Next
    End Sub

How do I disable a Pylint warning?

To disable a warning locally in a block, add

# pylint: disable=C0321

to that block.

Slide div left/right using jQuery

_x000D_
_x000D_
$(document).ready(function(){_x000D_
$("#left").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#left').hide("slide", { direction: "left" }, 500, function () {_x000D_
            $('#right').show("slide", { direction: "right" }, 500);_x000D_
        });_x000D_
    });_x000D_
    $("#right").on('click', function (e) {_x000D_
        e.stopPropagation();_x000D_
        e.preventDefault();_x000D_
        $('#right').hide("slide", { direction: "right" }, 500, function () {_x000D_
            $('#left').show("slide", { direction: "left" }, 500);_x000D_
        });_x000D_
    });_x000D_
_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>_x000D_
_x000D_
<div style="height:100%;width:100%;background:cyan" id="left">_x000D_
<h1>Hello im going left to hide and will comeback from left to show</h1>_x000D_
</div>_x000D_
<div style="height:100%;width:100%;background:blue;display:none" id="right">_x000D_
<h1>Hello im coming from right to sho and will go back to right to hide</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

$("#btnOpenEditing").off('click');
$("#btnOpenEditing").on('click', function (e) {
    e.stopPropagation();
    e.preventDefault();
    $('#mappingModel').hide("slide", { direction: "right" }, 500, function () {
        $('#fsEditWindow').show("slide", { direction: "left" }, 500);
    });
});

It will work like charm take a look at the demo.

Regex expressions in Java, \\s vs. \\s+

The first one matches a single whitespace, whereas the second one matches one or many whitespaces. They're the so-called regular expression quantifiers, and they perform matches like this (taken from the documentation):

Greedy quantifiers
X?  X, once or not at all
X*  X, zero or more times
X+  X, one or more times
X{n}    X, exactly n times
X{n,}   X, at least n times
X{n,m}  X, at least n but not more than m times

Reluctant quantifiers
X?? X, once or not at all
X*? X, zero or more times
X+? X, one or more times
X{n}?   X, exactly n times
X{n,}?  X, at least n times
X{n,m}? X, at least n but not more than m times

Possessive quantifiers
X?+ X, once or not at all
X*+ X, zero or more times
X++ X, one or more times
X{n}+   X, exactly n times
X{n,}+  X, at least n times
X{n,m}+ X, at least n but not more than m times

OpenJDK availability for Windows OS

In case you are still looking for a Windows build of OpenJDK, Azul Systems launched the Zulu product line last fall. The Zulu distribution of OpenJDK is built and tested on Windows and Linux. We posted the OpenJDK 8 version this week, though OpenJDK 7 and 6 are both available too. The following URL leads to you free downloads, the Zulu community forum, and other details: http://www.azulsystems.com/products/zulu These are binary downloads, so you do not need to build OpenJDK from scratch to use them.

I can attest that building OpenJDK 6 for Windows was not a trivial exercise. Of the six different platforms we've built (OpenJDK6, OpenJDK7, and OpenJDK8, each for Windows and Linux) for x64 so far, the Windows OpenJDK6 build took by far the most effort to wring out items that didn't work on Windows, or would not pass the Technical Compatibility Kit test protocol for Java SE 6 "as is."

Disclaimer: I am the Product Manager for Zulu. You can review my Zulu release notices here: https://support.azulsystems.com/hc/communities/public/topics/200063190-Zulu-Releases I hope this helps.

How to find whether or not a variable is empty in Bash?

[ "$variable" ] || echo empty
: ${variable="value_to_set_if_unset"}

What does <> mean in excel?

It means "not equal to" (as in, the values in cells E37-N37 are not equal to "", or in other words, they are not empty.)

How to navigate a few folders up?

The following method searches a file beginning with the application startup path (*.exe folder). If the file is not found there, the parent folders are searched until either the file is found or the root folder has been reached. null is returned if the file was not found.

public static FileInfo FindApplicationFile(string fileName)
{
    string startPath = Path.Combine(Application.StartupPath, fileName);
    FileInfo file = new FileInfo(startPath);
    while (!file.Exists) {
        if (file.Directory.Parent == null) {
            return null;
        }
        DirectoryInfo parentDir = file.Directory.Parent;
        file = new FileInfo(Path.Combine(parentDir.FullName, file.Name));
    }
    return file;
}

Note: Application.StartupPath is usually used in WinForms applications, but it works in console applications as well; however, you will have to set a reference to the System.Windows.Forms assembly. You can replace Application.StartupPath by
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) if you prefer.

What is "loose coupling?" Please provide examples

You can read more about the generic concept of "loose coupling".

In short, it's a description of a relationship between two classes, where each class knows the very least about the other and each class could potentially continue to work just fine whether the other is present or not and without dependency on the particular implementation of the other class.

C# DateTime to "YYYYMMDDHHMMSS" format

DateTime.Now.ToString("MM/dd/yyyy") 05/29/2015
DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015
DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015 05:50
DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015 05:50 AM
DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015 5:50
DateTime.Now.ToString("dddd, dd MMMM yyyy") Friday, 29 May 2015 5:50 AM
DateTime.Now.ToString("dddd, dd MMMM yyyy HH:mm:ss")    Friday, 29 May 2015 05:50:06
DateTime.Now.ToString("MM/dd/yyyy HH:mm")   05/29/2015 05:50
DateTime.Now.ToString("MM/dd/yyyy hh:mm tt")    05/29/2015 05:50 AM
DateTime.Now.ToString("MM/dd/yyyy H:mm")    05/29/2015 5:50
DateTime.Now.ToString("MM/dd/yyyy h:mm tt") 05/29/2015 5:50 AM
DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")    05/29/2015 05:50:06
DateTime.Now.ToString("MMMM dd")    May 29
DateTime.Now.ToString("yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss.fffffffK") 2015-05-16T05:50:06.7199222-04:00
DateTime.Now.ToString("ddd, dd MMM yyy HH’:’mm’:’ss ‘GMT’") Fri, 16 May 2015 05:50:06 GMT
DateTime.Now.ToString("yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss")  2015-05-16T05:50:06
DateTime.Now.ToString("HH:mm")  05:50
DateTime.Now.ToString("hh:mm tt")   05:50 AM
DateTime.Now.ToString("H:mm")   5:50
DateTime.Now.ToString("h:mm tt")    5:50 AM
DateTime.Now.ToString("HH:mm:ss")   05:50:06
DateTime.Now.ToString("yyyy MMMM")  2015 May

Python regular expressions return true/false

Ignacio Vazquez-Abrams is correct. But to elaborate, re.match() will return either None, which evaluates to False, or a match object, which will always be True as he said. Only if you want information about the part(s) that matched your regular expression do you need to check out the contents of the match object.

JavaScript require() on client side

Some answers already - but I would like to point you to YUI3 and its on-demand module loading. It works on both server (node.js) and client, too - I have a demo website using the exact same JS code running on either client or server to build the pages, but that's another topic.

YUI3: http://developer.yahoo.com/yui/3/

Videos: http://developer.yahoo.com/yui/theater/

Example:

(precondition: the basic YUI3 functions in 7k yui.js have been loaded)

YUI({
    //configuration for the loader
}).use('node','io','own-app-module1', function (Y) {
    //sandboxed application code
    //...

    //If you already have a "Y" instance you can use that instead
    //of creating a new (sandbox) Y:
    //  Y.use('moduleX','moduleY', function (Y) {
    //  });
    //difference to YUI().use(): uses the existing "Y"-sandbox
}

This code loads the YUI3 modules "node" and "io", and the module "own-app-module1", and then the callback function is run. A new sandbox "Y" with all the YUI3 and own-app-module1 functions is created. Nothing appears in the global namespace. The loading of the modules (.js files) is handled by the YUI3 loader. It also uses (optional, not show here) configuration to select a -debug or -min(ified) version of the modules to load.

Make index.html default, but allow index.php to be visited if typed in

Hi,

Well, I have tried the methods mentioned above! it's working yes, but not exactly the way I wanted. I wanted to redirect the default page extension to the main domain with our further action.

Here how I do that...

# Accesible Index Page
<IfModule dir_module>
 DirectoryIndex index.php index.html
 RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.(html|htm|php|php3|php5|shtml|phtml) [NC]
 RewriteRule ^index\.html|htm|php|php3|php5|shtml|phtml$ / [R=301,L]
</IfModule>

The above code simply captures any index.* and redirect it to the main domain.

Thank you

How do I change the UUID of a virtual disk?

The correct command is the following one.

VBoxManage internalcommands sethduuid "/home/user/VirtualBox VMs/drupal/drupal.vhd"

The path for the virtual disk contains a space, so it must be enclosed in double quotes to avoid it is parsed as two parameters.

Can Windows Containers be hosted on linux?

Windows containers are not running on Linux and also You can't run Linux containers on Windows directly.

Is jQuery $.browser Deprecated?

From the documentation:

The $.browser property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery.

So, yes, it is deprecated, but your existing implementations will continue to work. If the functionality is removed, it will likely be easily accessible using a plugin.

As to whether there is an alternative... The answer is "yes, probably". It is far, far better to do feature detection using $.support rather than browser detection: detect the actual feature you need, not the browser that provides it. Most important features that vary from browser to browser are detected with that.


Update 16 February 2013: In jQuery 1.9, this feature was removed (docs). It is far better not to use it. If you really, really must use its functionality, you can restore it with the jQuery Migrate plugin.

how to download image from any web page in java

If you want to save the image and you know its URL you can do this:

try(InputStream in = new URL("http://example.com/image.jpg").openStream()){
    Files.copy(in, Paths.get("C:/File/To/Save/To/image.jpg"));
}

You will also need to handle the IOExceptions which may be thrown.

How to enable loglevel debug on Apache2 server

You need to use LogLevel rewrite:trace3 to your httpd.conf in newer version http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#logging

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

I checked all my settings according to this list: http://msdn.microsoft.com/en-us/library/ts7eyw4s.aspx#feedback . It is helpful to me and for my situation, I find out that Link Dependency of projects' properties has double-quote, which should not be there.

How to use Visual Studio C++ Compiler?

You may be forgetting something. Before #include <iostream>, write #include <stdafx.h> and maybe that will help. Then, when you are done writing, click test, than click output from build, then when it is done processing/compiling, press Ctrl+F5 to open the Command Prompt and it should have the output and "press any key to continue."

Android - drawable with rounded corners at the top only

Try giving these values:

 <corners android:topLeftRadius="6dp" android:topRightRadius="6dp"
         android:bottomLeftRadius="0.1dp" android:bottomRightRadius="0.1dp"/>

Note that I have changed 0dp to 0.1dp.

EDIT: See Aleks G comment below for a cleaner version

How to hide html source & disable right click and text copy?

You can use JavaScript to disable the context menu (right-click), but it's easily overwrittable. For example, in Firefox, go to Options -> Content and next to the "Enable JavaScript" check box, click Advanced. Uncheck the "Disable or replace context menus" option. Now you can right-click all you want.

A simple CTRL + U will view the source. That can never be disabled.

Need to get a string after a "word" in a string in c#

Simpler way (if your only keyword is "code" ) may be:

string ErrorCode = yourString.Split(new string[]{"code"}, StringSplitOptions.None).Last();

Java collections maintaining insertion order

Performance. If you want the original insertion order there are the LinkedXXX classes, which maintain an additional linked list in insertion order. Most of the time you don't care, so you use a HashXXX, or you want a natural order, so you use TreeXXX. In either of those cases why should you pay the extra cost of the linked list?

Sort divs in jQuery based on attribute 'data-sort'?

Use this function

   var result = $('div').sort(function (a, b) {

      var contentA =parseInt( $(a).data('sort'));
      var contentB =parseInt( $(b).data('sort'));
      return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
   });

   $('#mylist').html(result);

You can call this function just after adding new divs.

If you want to preserve javascript events within the divs, DO NOT USE html replace as in the above example. Instead use:

$(targetSelector).sort(function (a, b) {
    // ...
}).appendTo($container);

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

Late reaction, but I've struggled with this for a while so maybe I can save somebody some time by showing my solution.

My problem showed a bit different, but the cause might be the same.

In my situation, TortoiseSVN kept on trying to connect via a proxy server. I could access SVN via chrome, firefox and IE fine.

Turns out that there is a configuration file that has a different configuration than the GUI in TortoiseSVN shows.

Mine was located here: C:\Documents and Settings\[username]\Application Data\Subversion\, but you can also open the file via the TortoiseSVN gui.

TortoiseSVN

In my file, http-proxy-exceptions was empty. After I specified it, everything worked fine.

[global]
http-proxy-exceptions = 10.1.1.11
http-proxy-host = 197.132.0.223
http-proxy-port = 8080
http-proxy-username = defaultusername
http-proxy-password = defaultpassword
http-compression = no

How do you count the lines of code in a Visual Studio solution?

Try neptuner. It also gives you stuff like spaces, tabs, Lines of comments in addition to LoC. http://neptuner.googlecode.com/files/neptuner_0_30_windows.zip

Git pull a certain branch from GitHub

you may also do

git pull -r origin master

fix merge conflicts if any

git rebase --continue

-r is for rebase. This will make you branch structure from

        v  master       
o-o-o-o-o
     \o-o-o
          ^ other branch

to

        v  master       
o-o-o-o-o-o-o-o
              ^ other branch

This will lead to a cleaner history. Note: In case you have already pushed your other-branch to origin( or any other remote), you may have to force push your branch after rebase.

git push -f origin other-branch

How to to send mail using gmail in Laravel?

if you still could be able to send mail after setting all configs right and get forbidden or timeout errors you could set the allow less secure apps to access your account in gmail. you can follow how to here