Programs & Examples On #Bltoolkit

Business Logic Toolkit for .NET.

MySQL - SELECT WHERE field IN (subquery) - Extremely slow why?

I have reformatted your slow sql query with www.prettysql.net

SELECT *
FROM some_table
WHERE
 relevant_field in
 (
  SELECT relevant_field
  FROM some_table
  GROUP BY relevant_field
  HAVING COUNT ( * ) > 1
 );

When using a table in both the query and the subquery, you should always alias both, like this:

SELECT *
FROM some_table as t1
WHERE
 t1.relevant_field in
 (
  SELECT t2.relevant_field
  FROM some_table as t2
  GROUP BY t2.relevant_field
  HAVING COUNT ( t2.relevant_field ) > 1
 );

Does that help?

Simplest way to serve static data from outside the application server in a Java web application

I've seen some suggestions like having the image directory being a symbolic link pointing to a directory outside the web container, but will this approach work both on Windows and *nix environments?

If you adhere the *nix filesystem path rules (i.e. you use exclusively forward slashes as in /path/to/files), then it will work on Windows as well without the need to fiddle around with ugly File.separator string-concatenations. It would however only be scanned on the same working disk as from where this command is been invoked. So if Tomcat is for example installed on C: then the /path/to/files would actually point to C:\path\to\files.

If the files are all located outside the webapp, and you want to have Tomcat's DefaultServlet to handle them, then all you basically need to do in Tomcat is to add the following Context element to /conf/server.xml inside <Host> tag:

<Context docBase="/path/to/files" path="/files" />

This way they'll be accessible through http://example.com/files/.... For Tomcat-based servers such as JBoss EAP 6.x or older, the approach is basically the same, see also here. GlassFish/Payara configuration example can be found here and WildFly configuration example can be found here.

If you want to have control over reading/writing files yourself, then you need to create a Servlet for this which basically just gets an InputStream of the file in flavor of for example FileInputStream and writes it to the OutputStream of the HttpServletResponse.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Here's a basic example of such a servlet:

@WebServlet("/files/*")
public class FileServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        String filename = URLDecoder.decode(request.getPathInfo().substring(1), "UTF-8");
        File file = new File("/path/to/files", filename);
        response.setHeader("Content-Type", getServletContext().getMimeType(filename));
        response.setHeader("Content-Length", String.valueOf(file.length()));
        response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
        Files.copy(file.toPath(), response.getOutputStream());
    }

}

When mapped on an url-pattern of for example /files/*, then you can call it by http://example.com/files/image.png. This way you can have more control over the requests than the DefaultServlet does, such as providing a default image (i.e. if (!file.exists()) file = new File("/path/to/files", "404.gif") or so). Also using the request.getPathInfo() is preferred above request.getParameter() because it is more SEO friendly and otherwise IE won't pick the correct filename during Save As.

You can reuse the same logic for serving files from database. Simply replace new FileInputStream() by ResultSet#getInputStream().

Hope this helps.

See also:

crop text too long inside div

.crop { 
  overflow:hidden; 
  white-space:nowrap; 
  text-overflow:ellipsis; 
  width:100px; 
}?

http://jsfiddle.net/hT3YA/

SQL Server: IF EXISTS ; ELSE

Try this:

Update TableB Set
  Code = Coalesce(
    (Select Max(Value)
    From TableA 
    Where Id = b.Id), 123)
From TableB b

How can I add a key/value pair to a JavaScript object?

Year 2017 answer: Object.assign()

Object.assign(dest, src1, src2, ...) merges objects.

It overwrites dest with properties and values of (however many) source objects, then returns dest.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

Live example

_x000D_
_x000D_
var obj = {key1: "value1", key2: "value2"};
Object.assign(obj, {key3: "value3"});

document.body.innerHTML = JSON.stringify(obj);
_x000D_
_x000D_
_x000D_

Year 2018 answer: object spread operator {...}

obj = {...obj, ...pair};

From MDN:

It copies own enumerable properties from a provided object onto a new object.

Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign().

Note that Object.assign() triggers setters whereas spread syntax doesn’t.

Live example

It works in current Chrome and current Firefox. They say it doesn’t work in current Edge.

_x000D_
_x000D_
var obj = {key1: "value1", key2: "value2"};
var pair = {key3: "value3"};
obj = {...obj, ...pair};

document.body.innerHTML = JSON.stringify(obj);
_x000D_
_x000D_
_x000D_

Year 2019 answer

Object assignment operator +=:

obj += {key3: "value3"};

Oops... I got carried away. Smuggling information from the future is illegal. Duly obscured!

iOS: Compare two dates

NSDate actually represents a time interval in seconds since a reference date (1st Jan 2000 UTC I think). Internally, a double precision floating point number is used so two arbitrary dates are highly unlikely to compare equal even if they are on the same day. If you want to see if a particular date falls on a particular day, you probably need to use NSDateComponents. e.g.

NSDateComponents* dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear: 2011];
[dateComponents setMonth: 5];
[dateComponents setDay: 24];
/*
 *  Construct two dates that bracket the day you are checking.  
 *  Use the user's current calendar.  I think this takes care of things like daylight saving time.
 */
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* startOfDate = [calendar dateFromComponents: dateComponents];
NSDateComponents* oneDay = [[NSDateComponents alloc] init];
[oneDay setDay: 1];
NSDate* endOfDate = [calendar dateByAddingComponents: oneDay toDate: startOfDate options: 0];
/*
 *  Compare the date with the start of the day and the end of the day.
 */
NSComparisonResult startCompare = [startOfDate compare: myDate];
NSComparisonResult endCompare = [endOfDate compare: myDate];

if (startCompare != NSOrderedDescending && endCompare == NSOrderedDescending)
{
    // we are on the right date
} 

How can I parse JSON with C#?

I am assuming you are not using Json.NET (Newtonsoft.Json NuGet package). If this the case, then you should try it.

It has the following features:

  1. LINQ to JSON
  2. The JsonSerializer for quickly converting your .NET objects to JSON and back again
  3. Json.NET can optionally produce well formatted, indented JSON for debugging or display
  4. Attributes like JsonIgnore and JsonProperty can be added to a class to customize how a class is serialized
  5. Ability to convert JSON to and from XML
  6. Supports multiple platforms: .NET, Silverlight and the Compact Framework

Look at the example below. In this example, JsonConvert class is used to convert an object to and from JSON. It has two static methods for this purpose. They are SerializeObject(Object obj) and DeserializeObject<T>(String json):

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "Expiry": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

XML serialization in Java?

Usually I use jaxb or XMLBeans if I need to create objects serializable to XML. Now, I can see that XStream might be very useful as it's nonintrusive and has really simple api. I'll play with it soon and probably use it. The only drawback I noticed is that I can't create object's id on my own for cross referencing.

@Barak Schiller
Thanks for posting link to XStream!

How to output a comma delimited list in jinja python template?

And using the joiner from http://jinja.pocoo.org/docs/dev/templates/#joiner

{% set comma = joiner(",") %}
{% for user in userlist %}
    {{ comma() }}<a href="/profile/{{ user }}/">{{ user }}</a>
{% endfor %}  

It's made for this exact purpose. Normally a join or a check of forloop.last would suffice for a single list, but for multiple groups of things it's useful.

A more complex example on why you would use it.

{% set pipe = joiner("|") %}
{% if categories %} {{ pipe() }}
    Categories: {{ categories|join(", ") }}
{% endif %}
{% if author %} {{ pipe() }}
    Author: {{ author() }}
{% endif %}
{% if can_edit %} {{ pipe() }}
    <a href="?action=edit">Edit</a>
{% endif %}

Put content in HttpResponseMessage object?

For a string specifically, the quickest way is to use the StringContent constructor

response.Content = new StringContent("Your response text");

There are a number of additional HttpContent class descendants for other common scenarios.

How do I grant myself admin access to a local SQL Server instance?

I adopted a SQL 2012 database where I was not a sysadmin but was an administrator on the machine. I used SSMS with "Run as Administrator", added my NT account as a SQL login and set the server role to sysadmin. No problem.

How can I clear an HTML file input with JavaScript?

Try this easy and it works

let input = elem.querySelector('input[type="file"]');
input.outerHTML=input.outerHTML;

this will reset the input

How is a JavaScript hash map implemented?

Here is an easy and convenient way of using something similar to the Java map:

var map= {
    'map_name_1': map_value_1,
    'map_name_2': map_value_2,
    'map_name_3': map_value_3,
    'map_name_4': map_value_4
    }

And to get the value:

alert( map['map_name_1'] );    // fives the value of map_value_1

......  etc  .....

Read .doc file with python

One can use the textract library. It take care of both "doc" as well as "docx"

import textract
text = textract.process("path/to/file.extension")

You can even use 'antiword' (sudo apt-get install antiword) and then convert doc to first into docx and then read through docx2txt.

antiword filename.doc > filename.docx

Ultimately, textract in the backend is using antiword.

Error: "Could Not Find Installable ISAM"

Place single quotes around the Extended Properties:

OleDbConnection oconn = 
    new OleDbConnection(
        @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';");

Try it, it really works.

PHP and MySQL Select a Single Value

The mysql_* functions are deprecated and unsafe. The code in your question in vulnerable to injection attacks. It is highly recommended that you use the PDO extension instead, like so:

session_start();

$query = "SELECT 'id' FROM Users WHERE username = :name LIMIT 1";
$statement = $PDO->prepare($query);
$params = array(
    'name' => $_GET["username"]
);
$statement->execute($params);
$user_data = $statement->fetch();

$_SESSION['myid'] = $user_data['id'];

Where $PDO is your PDO object variable. See https://www.php.net/pdo_mysql for more information about PHP and PDO.

For extra help:

Here's a jumpstart on how to connect to your database using PDO:

$database_username = "YOUR_USERNAME";
$database_password = "YOUR_PASSWORD";
$database_info = "mysql:host=localhost;dbname=YOUR_DATABASE_NAME";
try
{
    $PDO = new PDO($database_info, $database_username, $database_password);
}
catch(PDOException $e)
{
    // Handle error here
}

How can I change the user on Git Bash?

Check what git remote -v returns: the account used to push to an http url is usually embedded into the remote url itself.

https://[email protected]/...

If that is the case, put an url which will force Git to ask for the account to use when pushing:

git remote set-url origin https://github.com/<user>/<repo>

Or one to use the Fre1234 account:

git remote set-url origin https://[email protected]/<user>/<repo>

Also check if you installed your Git For Windows with or without a credential helper as in this question.


The OP Fre1234 adds in the comments:

I finally found the solution.
Go to: Control Panel -> User Accounts -> Manage your credentials -> Windows Credentials

Under Generic Credentials there are some credentials related to Github,
Click on them and click "Remove".

That is because the default installation for Git for Windows set a Git-Credential-Manager-for-Windows.
See git config --global credential.helper output (it should be manager)

@selector() in Swift?

Here's a quick example on how to use the Selector class on Swift:

override func viewDidLoad() {
    super.viewDidLoad()

    var rightButton = UIBarButtonItem(title: "Title", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("method"))
    self.navigationItem.rightBarButtonItem = rightButton
}

func method() {
    // Something cool here   
}

Note that if the method passed as a string doesn't work, it will fail at runtime, not compile time, and crash your app. Be careful

Upload video files via PHP and save them in appropriate folder and have a database entry

sample code:

<em><b>
<h2>Upload,Save and Download video </h2>
<form method="POST" action="" enctype="multipart/form-data">
<input type="file" name="video"/>
<input type="submit" name="submit" value="Upload"/></b>
</form></em>

<?php>
include("connect.php");
$errors=1;
//Targeting Folder
$target="videos/";
if(isset($_POST['submit'])){
//Targeting Folder 
$target=$target.basename($_FILES['video']['name']);
//Getting Selected video Type
$type=pathinfo($target,PATHINFO_EXTENSION);
 //Allow Certain File Format To Upload
 if($type!='mp4' && $type!='3gp' && $type!='avi'){
  echo "Only mp4,3gp,avi file format are allowed to Upload";
  $errors=0;
 }
 //checking for Exsisting video Files
  if(file_exists($target)){
   echo "File Exist";
   $errors=0;
   }
  $filesize=$_FILES['video']['size'];
  if($filesize>250*2000000){
  echo 'You Can not Upload Large File(more than 500MB) by Default ini setting..<a     href="http://www.codenair.com/2018/03/how-to-upload-large-file-in-php.html">How to   upload large file in php</a>'; 
    $errors=0;
    }
   if($errors == 0){
   echo ' Your File Not Uploaded';
    }else{
 //Moving The video file to Desired Directory
  $uplaod_success=move_uploaded_file($_FILES['video']['tmp_name'],$target);
  if($uplaod_success){
  //Getting Selected video Information
    $name=$_FILES['video']['name'];
    $size=$_FILES['video']['size'];
    $result=mysqli_query($con,"INSERT INTO VIdeos           (name,size,type)VALUES('".$name."','".$size."','".$type."')");
    if($result==TRUE){
    echo "Your video '$name' Successfully Upload and Information Saved Our  Database";
    }
   }
  }
  }
 ?>

Convert generic List/Enumerable to DataTable?

List<YourModel> data = new List<YourModel>();
DataTable dataTable = Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>(Newtonsoft.Json.JsonConvert.SerializeObject(data));

Difference between core and processor

I have read all answers, but this link was more clear explanation for me about difference between CPU(Processor) and Core. So I'm leaving here some notes from there.

The main difference between CPU and Core is that the CPU is an electronic circuit inside the computer that carries out instruction to perform arithmetic, logical, control and input/output operations while the core is an execution unit inside the CPU that receives and executes instructions.

enter image description here

What's the difference between SCSS and Sass?

SASS is Syntactically Awesome Style Sheets and is an extension of CSS which provides the features of nested rules, inheritance, Mixins whereas SCSS is Sassy Cascaded Style Sheets which is similar to that of CSS and fills the gaps and incompatibilities between CSS and SASS. It was licensed under the MIT license. This article has more about the differences:https://www.educba.com/sass-vs-scss/

How to run VBScript from command line without Cscript/Wscript

I'll break this down in to several distinct parts, as each part can be done individually. (I see the similar answer, but I'm going to give a more detailed explanation here..)

First part, in order to avoid typing "CScript" (or "WScript"), you need to tell Windows how to launch a * .vbs script file. In My Windows 8 (I cannot be sure all these commands work exactly as shown here in older Windows, but the process is the same, even if you have to change the commands slightly), launch a console window (aka "command prompt", or aka [incorrectly] "dos prompt") and type "assoc .vbs". That should result in a response such as:

C:\Windows\System32>assoc .vbs
.vbs=VBSFile

Using that, you then type "ftype VBSFile", which should result in a response of:

C:\Windows\System32>ftype VBSFile
vbsfile="%SystemRoot%\System32\WScript.exe" "%1" %*

-OR-

C:\Windows\System32>ftype VBSFile
vbsfile="%SystemRoot%\System32\CScript.exe" "%1" %*

If these two are already defined as above, your Windows' is already set up to know how to launch a * .vbs file. (BTW, WScript and CScript are the same program, using different names. WScript launches the script as if it were a GUI program, and CScript launches it as if it were a command line program. See other sites and/or documentation for these details and caveats.)

If either of the commands did not respond as above (or similar responses, if the file type reported by assoc and/or the command executed as reported by ftype have different names or locations), you can enter them yourself:

C:\Windows\System32>assoc .vbs=VBSFile

-and/or-

C:\Windows\System32>ftype vbsfile="%SystemRoot%\System32\WScript.exe" "%1" %*

You can also type "help assoc" or "help ftype" for additional information on these commands, which are often handy when you want to automatically run certain programs by simply typing a filename with a specific extension. (Be careful though, as some file extensions are specially set up by Windows or programs you may have installed so they operate correctly. Always check the currently assigned values reported by assoc/ftype and save them in a text file somewhere in case you have to restore them.)

Second part, avoiding typing the file extension when typing the command from the console window.. Understanding how Windows (and the CMD.EXE program) finds commands you type is useful for this (and the next) part. When you type a command, let's use "querty" as an example command, the system will first try to find the command in it's internal list of commands (via settings in the Windows' registry for the system itself, or programmed in in the case of CMD.EXE). Since there is no such command, it will then try to find the command in the current %PATH% environment variable. In older versions of DOS/Windows, CMD.EXE (and/or COMMAND.COM) would automatically add the file extensions ".bat", ".exe", ".com" and possibly ".cmd" to the command name you typed, unless you explicitly typed an extension (such as "querty.bat" to avoid running "querty.exe" by mistake). In more modern Windows, it will try the extensions listed in the %PATHEXT% environment variable. So all you have to do is add .vbs to %PATHEXT%. For example, here's my %PATHEXT%:

C:\Windows\System32>set pathext
PATHEXT=.PLX;.PLW;.PL;.BAT;.CMD;.VBS;.COM;.EXE;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY

Notice that the extensions MUST include the ".", are separated by ";", and that .VBS is listed AFTER .CMD, but BEFORE .COM. This means that if the command processor (CMD.EXE) finds more than one match, it'll use the first one listed. That is, if I have query.cmd, querty.vbs and querty.com, it'll use querty.cmd.

Now, if you want to do this all the time without having to keep setting %PATHEXT%, you'll have to modify the system environment. Typing it in a console window only changes it for that console window session. I'll leave this process as an exercise for the reader. :-P

Third part, getting the script to run without always typing the full path. This part, in relation to the second part, has been around since the days of DOS. Simply make sure the file is in one of the directories (folders, for you Windows' folk!) listed in the %PATH% environment variable. My suggestion is to make your own directory to store various files and programs you create or use often from the console window/command prompt (that is, don't worry about doing this for programs you run from the start menu or any other method.. only the console window. Don't mess with programs that are installed by Windows or an automated installer unless you know what you're doing).

Personally, I always create a "C:\sys\bat" directory for batch files, a "C:\sys\bin" directory for * .exe and * .com files (for example, if you download something like "md5sum", a MD5 checksum utility), a "C:\sys\wsh" directory for VBScripts (and JScripts, named "wsh" because both are executed using the "Windows Scripting Host", or "wsh" program), and so on. I then add these to my system %PATH% variable (Control Panel -> Advanced System Settings -> Advanced tab -> Environment Variables button), so Windows can always find them when I type them.

Combining all three parts will result in configuring your Windows system so that anywhere you can type in a command-line command, you can launch your VBScript by just typing it's base file name. You can do the same for just about any file type/extension; As you probably saw in my %PATHEXT% output, my system is set up to run Perl scripts (.PLX;.PLW;.PL) and Python (.PY) scripts as well. (I also put "C:\sys\bat;C:\sys\scripts;C:\sys\wsh;C:\sys\bin" at the front of my %PATH%, and put various batch files, script files, et cetera, in these directories, so Windows can always find them. This is also handy if you want to "override" some commands: Putting the * .bat files first in the path makes the system find them before the * .exe files, for example, and then the * .bat file can launch the actual program by giving the full path to the actual *. exe file. Check out the various sites on "batch file programming" for details and other examples of the power of the command line.. It isn't dead yet!)

One final note: DO check out some of the other sites for various warnings and caveats. This question posed a script named "converter.vbs", which is dangerously close to the command "convert.exe", which is a Windows program to convert your hard drive from a FAT file system to a NTFS file system.. Something that can clobber your hard drive if you make a typing mistake!

On the other hand, using the above techniques you can insulate yourself from such mistakes, too. Using CONVERT.EXE as an example.. Rename it to something like "REAL_CONVERT.EXE", then create a file like "C:\sys\bat\convert.bat" which contains:

@ECHO OFF
ECHO !DANGER! !DANGER! !DANGER! !DANGER, WILL ROBINSON!

ECHO This command will convert your hard drive to NTFS! DO YOU REALLY WANT TO DO THIS?!
ECHO PRESS CONTROL-C TO ABORT, otherwise..

REM "PAUSE" will pause the batch file with the message "Press any key to continue...",
REM and also allow the user to press CONTROL-C which will prompt the user to abort or
REM continue running the batch file.
PAUSE

ECHO Okay, if you're really determined to do this, type this command:
ECHO.    %SystemRoot%\SYSTEM32\REAL_CONVERT.EXE
ECHO to run the real CONVERT.EXE program. Have a nice day!

You can also use CHOICE.EXE in modern Windows to make the user type "y" or "n" if they really want to continue, and so on.. Again, the power of batch (and scripting) files!

Here's some links to some good resources on how to use all this power:

http://ss64.com/

http://www.computerhope.com/batch.htm

http://commandwindows.com/batch.htm

http://www.robvanderwoude.com/batchfiles.php

Most of these sites are geared towards batch files, but most of the information in them applies to running any kind of batch (* .bat) file, command (* .cmd) file, and scripting (* .vbs, * .js, * .pl, * .py, and so on) files.

Check if string is upper, lower, or mixed case in Python

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

Navigation drawer: How do I set the selected item at startup?

on your activity(behind the drawer):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar,
               R.string.navigation_drawer_open,
               R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    navigationView.setCheckedItem(R.id.nav_portfolio);
    onNavigationItemSelected(navigationView.getMenu().getItem(0));
}

and

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    Fragment fragment = null;

    if (id == R.id.nav_test1) {
        fragment = new Test1Fragment();
        displaySelectedFragment(fragment);
    } else if (id == R.id.nav_test2) {
        fragment = new Test2Fragment();
        displaySelectedFragment(fragment);
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

and in your menu:

<group android:checkableBehavior="single">

    <item
        android:id="@+id/nav_test1"
        android:title="@string/test1" />

    <item
        android:id="@+id/nav_test2"
        android:title="@string/test2" />

  </group>

so first menu is highlight and show as default menu.

How do I find the stack trace in Visual Studio?

The default shortcut key is Ctrl-Alt-C.

Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#

There is no standard format for the readable 8601 format. You can use a custom format:

theDate.ToString("yyyy-MM-dd HH':'mm':'ss")

(The standard format "s" will give you a "T" between the date and the time, not a space.)

Programmatically change the height and width of a UIImageView Xcode Swift

u can use this code

var imageView = UIImageView(image: UIImage(name:"imageName"));
imageView.frame = CGrectMake(x,y imageView.frame.width*0.2,50);

or

var imageView = UIImageView(frame:CGrectMake(x,y, self.view.frame.size.width *0.2, 50)

Spring MVC: How to perform validation?

If you have same error handling logic for different method handlers, then you would end up with lots of handlers with following code pattern:

if (validation.hasErrors()) {
  // do error handling
}
else {
  // do the actual business logic
}

Suppose you're creating RESTful services and want to return 400 Bad Request along with error messages for every validation error case. Then, the error handling part would be same for every single REST endpoint that requires validation. Repeating that very same logic in every single handler is not so DRYish!

One way to solve this problem is to drop the immediate BindingResult after each To-Be-Validated bean. Now, your handler would be like this:

@RequestMapping(...)
public Something doStuff(@Valid Somebean bean) { 
    // do the actual business logic
    // Just the else part!
}

This way, if the bound bean was not valid, a MethodArgumentNotValidException will be thrown by Spring. You can define a ControllerAdvice that handles this exception with that same error handling logic:

@ControllerAdvice
public class ErrorHandlingControllerAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public SomeErrorBean handleValidationError(MethodArgumentNotValidException ex) {
        // do error handling
        // Just the if part!
    }
}

You still can examine the underlying BindingResult using getBindingResult method of MethodArgumentNotValidException.

Reading a key from the Web.Config using ConfigurationManager

I found this solution to be quite helpful. It uses C# 4.0 DynamicObject to wrap the ConfigurationManager. So instead of accessing values like this:

 WebConfigurationManager.AppSettings["PFUserName"]

you access them as a property:

dynamic appSettings = new AppSettingsWrapper();
Console.WriteLine(appSettings.PFUserName);  

EDIT: Adding code snippet in case link becomes stale:

public class AppSettingsWrapper : DynamicObject
{
     private NameValueCollection _items;

    public AppSettingsWrapper()
    {
        _items = ConfigurationManager.AppSettings;
    }

     public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = _items[binder.Name];
        return result != null;
    }
}

Using the value in a cell as a cell reference in a formula?

Use INDIRECT()

=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

Has anyone ever got a remote JMX JConsole to work?

Getting JMX through the Firewall is really hard. The Problem is that standard RMI uses a second random assigned port (beside the RMI registry).

We have three solution that work, but every case needs a different one:

  1. JMX over SSH Tunnel with Socks proxy, uses standard RMI with SSH magic http://simplygenius.com/2010/08/jconsole-via-socks-ssh-tunnel.html

  2. JMX MP (alternative to standard RMI), uses only one fixed port, but needs a special jar on server and client http://meteatamel.wordpress.com/2012/02/13/jmx-rmi-vs-jmxmp/

  3. Start JMX Server form code, there it is possible to use standard RMI and use a fixed second port: https://issues.apache.org/bugzilla/show_bug.cgi?id=39055

What is the difference between an annotated and unannotated tag?

TL;DR

The difference between the commands is that one provides you with a tag message while the other doesn't. An annotated tag has a message that can be displayed with git-show(1), while a tag without annotations is just a named pointer to a commit.

More About Lightweight Tags

According to the documentation: "To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name". There are also some different options to write a message on annotated tags:

  • When you use git tag <tagname>, Git will create a tag at the current revision but will not prompt you for an annotation. It will be tagged without a message (this is a lightweight tag).
  • When you use git tag -a <tagname>, Git will prompt you for an annotation unless you have also used the -m flag to provide a message.
  • When you use git tag -a -m <msg> <tagname>, Git will tag the commit and annotate it with the provided message.
  • When you use git tag -m <msg> <tagname>, Git will behave as if you passed the -a flag for annotation and use the provided message.

Basically, it just amounts to whether you want the tag to have an annotation and some other information associated with it or not.

Why can't Python find shared objects that are in directories in sys.path?

As a supplement to above answers - I'm just bumping into a similar problem, and working completely of the default installed python.

When I call the example of the shared object library I'm looking for with LD_LIBRARY_PATH, I get something like this:

$ LD_LIBRARY_PATH=/path/to/mysodir:$LD_LIBRARY_PATH python example-so-user.py
python: can't open file 'example-so-user.py': [Errno 2] No such file or directory

Notably, it doesn't even complain about the import - it complains about the source file!

But if I force loading of the object using LD_PRELOAD:

$ LD_PRELOAD=/path/to/mysodir/mypyobj.so python example-so-user.py
python: error while loading shared libraries: libtiff.so.5: cannot open shared object file: No such file or directory

... I immediately get a more meaningful error message - about a missing dependency!

Just thought I'd jot this down here - cheers!

Check if selected dropdown value is empty using jQuery

You can try this also-

if( !$('#EventStartTimeMin').val() ) {
// do something
}

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

@mohammed, this is usually attributed to the authentication plugin that your mysql database is using.

By default and for some reason, mysql 8 default plugin is auth_socket. Applications will most times expect to log in to your database using a password.

If you have not yet already changed your mysql default authentication plugin, you can do so by:
1. Log in as root to mysql
2. Run this sql command:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password
BY 'password';  

Replace 'password' with your root password. In case your application does not log in to your database with the root user, replace the 'root' user in the above command with the user that your application uses.

Digital ocean expounds some more on this here Installing Mysql

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

Your query ($myQuery) is failing and therefore not producing a query resource, but instead producing FALSE.

To reveal what your dynamically generated query looks like and reveal the errors, try this:

$result2 = mysql_query($myQuery) or die($myQuery."<br/><br/>".mysql_error());

The error message will guide you to the solution, which from your comment below is related to using ORDER BY on a field that doesn't exist in the table you're SELECTing from.

CSS values using HTML5 data attribute

As of today, you can read some values from HTML5 data attributes in CSS3 declarations. In CaioToOn's fiddle the CSS code can use the data properties for setting the content.

Unfortunately it is not working for the width and height (tested in Google Chrome 35, Mozilla Firefox 30 & Internet Explorer 11).

But there is a CSS3 attr() Polyfill from Fabrice Weinberg which provides support for data-width and data-height. You can find the GitHub repo to it here: cssattr.js.

Get specific ArrayList item

I have been using the ArrayListAdapter to dynamically put in the entries into the respective fields ; This can be useful , for future queries

 AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();

And then , you can fetch any arraylist item as below :

arrayListName(info.position);

int *array = new int[n]; what is this function actually doing?

It allocates space on the heap equal to an integer array of size N, and returns a pointer to it, which is assigned to int* type pointer called "array"

Why does corrcoef return a matrix?

The function Correlate of numpy works with 2 1D arrays that you want to correlate and returns one correlation value.

combining two data frames of different lengths

I think I have come up with a quite shorter solution.. Hope it helps someone.

cbind.na<-function(df1, df2){

  #Collect all unique rownames
  total.rownames<-union(x = rownames(x = df1),y = rownames(x=df2))

  #Create a new dataframe with rownames
  df<-data.frame(row.names = total.rownames)

  #Get absent rownames for both of the dataframe
  absent.names.1<-setdiff(x = rownames(df1),y = rownames(df))
  absent.names.2<-setdiff(x = rownames(df2),y = rownames(df))

  #Fill absents with NAs
  df1.fixed<-data.frame(row.names = absent.names.1,matrix(data = NA,nrow = length(absent.names.1),ncol=ncol(df1)))
  colnames(df1.fixed)<-colnames(df1)
  df1<-rbind(df1,df1.fixed)

  df2.fixed<-data.frame(row.names = absent.names.2,matrix(data = NA,nrow = length(absent.names.2),ncol=ncol(df2)))
  colnames(df2.fixed)<-colnames(df2)
  df2<-rbind(df2,df2.fixed)

  #Finally cbind into new dataframe
  df<-cbind(df,df1[rownames(df),],df2[rownames(df),])
  return(df)

}

Maven Java EE Configuration Marker with Java Server Faces 1.2

The below steps should be the simple fix to your problem

  1. Project->Properties->ProjectFacet-->Uncheck jsf apply and OK.
  2. Project->Maven->UpdateProject-->This will solve the issue.

Here while on Updating Project Maven will automatically chooses the Dynamic web module

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

I had the same problem in my grails project. The Bug was, that i overwrite the getter method of a collection field. This returned always a new version of the collection in other thread.

class Entity {
    List collection

    List getCollection() {
        return collection.unique()
    }
}

The solution was to rename the getter method:

class Entity {
    List collection

    List getUniqueCollection() {
        return collection.unique()
    }
}

Remote branch is not showing up in "git branch -r"

If you clone with the --depth parameter, it sets .git/config not to fetch all branches, but only master.

You can simply omit the parameter or update the configuration file from

fetch = +refs/heads/master:refs/remotes/origin/master

to

fetch = +refs/heads/*:refs/remotes/origin/*

how to check if List<T> element contains an item with a Particular Property Value

You don't actually need LINQ for this because List<T> provides a method that does exactly what you want: Find.

Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire List<T>.

Example code:

PricePublicModel result = pricePublicList.Find(x => x.Size == 200);

how to display full stored procedure code?

\ef <function_name> in psql. It will give the whole function with editable text.

How to use multiple databases in Laravel

In Laravel 5.1, you specify the connection:

$users = DB::connection('foo')->select(...);

Default, Laravel uses the default connection. It is simple, isn't it?

Read more here: http://laravel.com/docs/5.1/database#accessing-connections

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

I tested the statement:

$cfg['Servers'][$i]['AllowNoPasswordRoot'] = true; 

It did not work out for me.

Instead

$cfg['Servers'][$i]['AllowNoPassword'] = true; 

worked.

Thanks!

How do I select text nodes with jQuery?

if you want to strip all tags, then try this

function:

String.prototype.stripTags=function(){
var rtag=/<.*?[^>]>/g;
return this.replace(rtag,'');
}

usage:

var newText=$('selector').html().stripTags();

Random strings in Python

Generating strings from (for example) lowercase characters:

import random, string

def randomword(length):
   letters = string.ascii_lowercase
   return ''.join(random.choice(letters) for i in range(length))

Results:

>>> randomword(10)
'vxnxikmhdc'
>>> randomword(10)
'ytqhdohksy'

ADB Shell Input Events

By adb shell input keyevent, either an event_code or a string will be sent to the device.

usage: input [text|keyevent]
  input text <string>
  input keyevent <event_code>

Some possible values for event_code are:

0 -->  "KEYCODE_UNKNOWN" 
1 -->  "KEYCODE_MENU" 
2 -->  "KEYCODE_SOFT_RIGHT" 
3 -->  "KEYCODE_HOME" 
4 -->  "KEYCODE_BACK" 
5 -->  "KEYCODE_CALL" 
6 -->  "KEYCODE_ENDCALL" 
7 -->  "KEYCODE_0" 
8 -->  "KEYCODE_1" 
9 -->  "KEYCODE_2" 
10 -->  "KEYCODE_3" 
11 -->  "KEYCODE_4" 
12 -->  "KEYCODE_5" 
13 -->  "KEYCODE_6" 
14 -->  "KEYCODE_7" 
15 -->  "KEYCODE_8" 
16 -->  "KEYCODE_9" 
17 -->  "KEYCODE_STAR" 
18 -->  "KEYCODE_POUND" 
19 -->  "KEYCODE_DPAD_UP" 
20 -->  "KEYCODE_DPAD_DOWN" 
21 -->  "KEYCODE_DPAD_LEFT" 
22 -->  "KEYCODE_DPAD_RIGHT" 
23 -->  "KEYCODE_DPAD_CENTER" 
24 -->  "KEYCODE_VOLUME_UP" 
25 -->  "KEYCODE_VOLUME_DOWN" 
26 -->  "KEYCODE_POWER" 
27 -->  "KEYCODE_CAMERA" 
28 -->  "KEYCODE_CLEAR" 
29 -->  "KEYCODE_A" 
30 -->  "KEYCODE_B" 
31 -->  "KEYCODE_C" 
32 -->  "KEYCODE_D" 
33 -->  "KEYCODE_E" 
34 -->  "KEYCODE_F" 
35 -->  "KEYCODE_G" 
36 -->  "KEYCODE_H" 
37 -->  "KEYCODE_I" 
38 -->  "KEYCODE_J" 
39 -->  "KEYCODE_K" 
40 -->  "KEYCODE_L" 
41 -->  "KEYCODE_M" 
42 -->  "KEYCODE_N" 
43 -->  "KEYCODE_O" 
44 -->  "KEYCODE_P" 
45 -->  "KEYCODE_Q" 
46 -->  "KEYCODE_R" 
47 -->  "KEYCODE_S" 
48 -->  "KEYCODE_T" 
49 -->  "KEYCODE_U" 
50 -->  "KEYCODE_V" 
51 -->  "KEYCODE_W" 
52 -->  "KEYCODE_X" 
53 -->  "KEYCODE_Y" 
54 -->  "KEYCODE_Z" 
55 -->  "KEYCODE_COMMA" 
56 -->  "KEYCODE_PERIOD" 
57 -->  "KEYCODE_ALT_LEFT" 
58 -->  "KEYCODE_ALT_RIGHT" 
59 -->  "KEYCODE_SHIFT_LEFT" 
60 -->  "KEYCODE_SHIFT_RIGHT" 
61 -->  "KEYCODE_TAB" 
62 -->  "KEYCODE_SPACE" 
63 -->  "KEYCODE_SYM" 
64 -->  "KEYCODE_EXPLORER" 
65 -->  "KEYCODE_ENVELOPE" 
66 -->  "KEYCODE_ENTER" 
67 -->  "KEYCODE_DEL" 
68 -->  "KEYCODE_GRAVE" 
69 -->  "KEYCODE_MINUS" 
70 -->  "KEYCODE_EQUALS" 
71 -->  "KEYCODE_LEFT_BRACKET" 
72 -->  "KEYCODE_RIGHT_BRACKET" 
73 -->  "KEYCODE_BACKSLASH" 
74 -->  "KEYCODE_SEMICOLON" 
75 -->  "KEYCODE_APOSTROPHE" 
76 -->  "KEYCODE_SLASH" 
77 -->  "KEYCODE_AT" 
78 -->  "KEYCODE_NUM" 
79 -->  "KEYCODE_HEADSETHOOK" 
80 -->  "KEYCODE_FOCUS" 
81 -->  "KEYCODE_PLUS" 
82 -->  "KEYCODE_MENU" 
83 -->  "KEYCODE_NOTIFICATION" 
84 -->  "KEYCODE_SEARCH" 
85 -->  "TAG_LAST_KEYCODE"

The sendevent utility sends touch or keyboard events, as well as other events for simulating the hardware events. Refer to this article for details: Android, low level shell click on screen.

Center-align a HTML table

For your design, it is common practice to use divs rather than a table. This way, your layout will be more maintainable and changeable through proper styling. It does take some getting used to, but it will help you a ton in the long run and you will learn a lot about how styling works. However, I will provide you with a solution to the problem at hand.

In your stylesheets you have margins and padding set to 0 pixels. This overrides your align="center" attribute. I would recommend taking these settings out of your CSS as you don't normally want all of your elements to be affected in this manner. If you already know what's going on in the CSS, and you want to keep it that way, then you have to apply a style to your table to override the previous sets. You could either give the table a class or you can put the style inline with the HTML. Here are the two options:

  1. With a class:

    <table class="centerTable"></table>

In your style.css file you would have something like this:

.centerTable { margin: 0px auto; }
  1. Inline with your HTML:

    <table style="margin: 0px auto;"></table>

If you decide to wipe out the margins and padding being set to 0px, then you can keep align="center" on your <td> tags for whatever column you wish to align.

java.net.SocketTimeoutException: Read timed out under Tomcat

Server is trying to read data from the request, but its taking longer than the timeout value for the data to arrive from the client. Timeout here would typically be tomcat connector -> connectionTimeout attribute.

Correct.

Client has a read timeout set, and server is taking longer than that to respond.

No. That would cause a timeout at the client.

One of the threads i went through, said this can happen with high concurrency and if the keepalive is enabled.

That is obviously guesswork, and completely incorrect. It happens if and only if no data arrives within the timeout. Period. Load and keepalive and concurrency have nothing to do with it whatsoever.

It just means the client isn't sending. You don't need to worry about it. Browser clients come and go in all sorts of strange ways.

Listing contents of a bucket with boto3

It can also be done as follows:

csv_files = s3.list_objects_v2(s3_bucket_path)
    for obj in csv_files['Contents']:
        key = obj['Key']

How do I create a master branch in a bare Git repository?

A bare repository is pretty much something you only push to and fetch from. You cannot do much directly "in it": you cannot check stuff out, create references (branches, tags), run git status, etc.

If you want to create a new branch in a bare Git repository, you can push a branch from a clone to your bare repo:

# initialize your bare repo
$ git init --bare test-repo.git

# clone it and cd to the clone's root directory
$ git clone test-repo.git/ test-clone
Cloning into 'test-clone'...
warning: You appear to have cloned an empty repository.
done.
$ cd test-clone

# make an initial commit in the clone
$ touch README.md
$ git add . 
$ git commit -m "add README"
[master (root-commit) 65aab0e] add README
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 README.md

# push to origin (i.e. your bare repo)
$ git push origin master
Counting objects: 3, done.
Writing objects: 100% (3/3), 219 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To /Users/jubobs/test-repo.git/
 * [new branch]      master -> master

Manually highlight selected text in Notepad++

To highlight a block of code in Notepad++, please do the following steps

  1. Select the required text.
  2. Right click to display the context menu
  3. Choose Style token and select any of the five choices available ( styles from Using 1st style to using 5th style). Each is of different colors.If you want yellow color choose using 3rd style.

If you want to create your own style you can use Style Configurator under Settings menu.

Laravel assets url

You have to put all your assets in app/public folder, and to access them from your views you can use asset() helper method.

Ex. you can retrieve assets/images/image.png in your view as following:

<img src="{{asset('assets/images/image.png')}}">

Does Python have an argc argument?

In python a list knows its length, so you can just do len(sys.argv) to get the number of elements in argv.

"Unable to launch the IIS Express Web server" error

I had the same issue, but with a different cause that may help others.

Use a commandprompt in admin mode for this: - TYPE: netsh http show iplisten If there are any IP entries: - TYPE: netsh http delete iplisten Repeat until the list is empty. Check if IIS Express starts now.

Hope this helps, Niels

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

import org.junit.Assert
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test

class FeatureTest {
    companion object {
        private lateinit var heavyFeature: HeavyFeature
        @BeforeClass
        @JvmStatic
        fun beforeHeavy() {
            heavyFeature = HeavyFeature()
        }
    }

    private lateinit var feature: Feature

    @Before
    fun before() {
        feature = Feature()
    }

    @Test
    fun testCool() {
        Assert.assertTrue(heavyFeature.cool())
        Assert.assertTrue(feature.cool())
    }

    @Test
    fun testWow() {
        Assert.assertTrue(heavyFeature.wow())
        Assert.assertTrue(feature.wow())
    }
}

Same as

import org.junit.Assert
import org.junit.Test

 class FeatureTest {
    companion object {
        private val heavyFeature = HeavyFeature()
    }

    private val feature = Feature()

    @Test
    fun testCool() {
        Assert.assertTrue(heavyFeature.cool())
        Assert.assertTrue(feature.cool())
    }

    @Test
    fun testWow() {
        Assert.assertTrue(heavyFeature.wow())
        Assert.assertTrue(feature.wow())
    }
}

how to use a like with a join in sql?

Using conditional criteria in a join is definitely different than the Where clause. The cardinality between the tables can create differences between Joins and Where clauses.

For example, using a Like condition in an Outer Join will keep all records in the first table listed in the join. Using the same condition in the Where clause will implicitly change the join to an Inner join. The record has to generally be present in both tables to accomplish the conditional comparison in the Where clause.

I generally use the style given in one of the prior answers.

tbl_A as ta
    LEFT OUTER JOIN tbl_B AS tb
            ON ta.[Desc] LIKE '%' + tb.[Desc] + '%'

This way I can control the join type.

Android: Vertical alignment for multi line EditText (Text area)

I think you can use layout:weight = 5 instead android:lines = 5 because when you port your app to smaller device - it does it nicely.. well, both attributes will accomplish your job..

Get WooCommerce product categories from WordPress

You could also use wp_list_categories();

wp_list_categories( array('taxonomy' => 'product_cat', 'title_li'  => '') );

What is the difference between dynamic programming and greedy approach?

the major difference between greedy method and dynamic programming is in greedy method only one optimal decision sequence is ever generated and in dynamic programming more than one optimal decision sequence may be generated.

How do I use CMake?

Cmake from Windows terminal:

mkdir build
cd build/
cmake ..
cmake --build . --config Release
./Release/main.exe

Docker error cannot delete docker container, conflict: unable to remove repository reference

If you want to cleanup docker images and containers

CAUTION: this will flush everything

stop all containers

docker stop $(docker ps -a -q)

remove all containers

docker rm $(docker ps -a -q)

remove all images

docker rmi -f $(docker images -a -q)

Automatically open Chrome developer tools when new tab/new window is opened

On opening the developer tools, with the developer tools window in focus, press F1. This will open a settings page. Check the "Auto-open DevTools for popups".

This worked for me.

Screenshot

How to get query string parameter from MVC Razor markup?

It was suggested to post this as an answer, because some other answers are giving errors like 'The name Context does not exist in the current context'.

Just using the following works:

Request.Query["queryparm1"]

Sample usage:

<a href="@Url.Action("Query",new {parm1=Request.Query["queryparm1"]})">GO</a>

Build a basic Python iterator

This question is about iterable objects, not about iterators. In Python, sequences are iterable too so one way to make an iterable class is to make it behave like a sequence, i.e. give it __getitem__ and __len__ methods. I have tested this on Python 2 and 3.

class CustomRange:

    def __init__(self, low, high):
        self.low = low
        self.high = high

    def __getitem__(self, item):
        if item >= len(self):
            raise IndexError("CustomRange index out of range")
        return self.low + item

    def __len__(self):
        return self.high - self.low


cr = CustomRange(0, 10)
for i in cr:
    print(i)

How to fill a datatable with List<T>

Just in case you have a nullable property in your class object:

private static DataTable ConvertToDatatable<T>(List<T> data)
{
    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for (int i = 0; i < props.Count; i++)
    {
        PropertyDescriptor prop = props[i];
        if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
            table.Columns.Add(prop.Name, prop.PropertyType.GetGenericArguments()[0]); 
        else
            table.Columns.Add(prop.Name, prop.PropertyType);
    }

    object[] values = new object[props.Count];
    foreach (T item in data)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        table.Rows.Add(values);
    }
    return table;
 }

How to echo JSON in PHP

Native JSON support has been included in PHP since 5.2 in the form of methods json_encode() and json_decode(). You would use the first to output a PHP variable in JSON.

How do I compare two columns for equality in SQL Server?

CASE WHEN is the better option

SELECT 
  CASE WHEN COLUMN1 = COLUMN2 
    THEN '1' 
    ELSE '0' 
  END 
  AS MyDesiredResult
FROM Table1
INNER JOIN Table2 ON Table1.PrimaryKey = Table2.ForeignKey

XDocument or XmlDocument

As mentioned elsewhere, undoubtedly, Linq to Xml makes creation and alteration of xml documents a breeze in comparison to XmlDocument, and the XNamespace ns + "elementName" syntax makes for pleasurable reading when dealing with namespaces.

One thing worth mentioning for xsl and xpath die hards to note is that it IS possible to still execute arbitrary xpath 1.0 expressions on Linq 2 Xml XNodes by including:

using System.Xml.XPath;

and then we can navigate and project data using xpath via these extension methods:

For instance, given the Xml document:

<xml>
    <foo>
        <baz id="1">10</baz>
        <bar id="2" special="1">baa baa</bar>
        <baz id="3">20</baz>
        <bar id="4" />
        <bar id="5" />
    </foo>
    <foo id="123">Text 1<moo />Text 2
    </foo>
</xml>

We can evaluate:

var node = xele.XPathSelectElement("/xml/foo[@id='123']");
var nodes = xele.XPathSelectElements(
"//moo/ancestor::xml/descendant::baz[@id='1']/following-sibling::bar[not(@special='1')]");
var sum = xele.XPathEvaluate("sum(//foo[not(moo)]/baz)");

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

Based on Dirk Stöcker's answer, here's a neat wrapper function for Python 3's print function. Use it just like you would use print.

As an added bonus, compared to the other answers, this won't print your text as a bytearray ('b"content"'), but as normal strings ('content'), because of the last decode step.

def uprint(*objects, sep=' ', end='\n', file=sys.stdout):
    enc = file.encoding
    if enc == 'UTF-8':
        print(*objects, sep=sep, end=end, file=file)
    else:
        f = lambda obj: str(obj).encode(enc, errors='backslashreplace').decode(enc)
        print(*map(f, objects), sep=sep, end=end, file=file)

uprint('foo')
uprint(u'Antonín Dvorák')
uprint('foo', 'bar', u'Antonín Dvorák')

How to check for an active Internet connection on iOS or macOS?

Alamofire

I know the question is asking for Coca Touch solution, but I want to provide a solution for people who searched check internet connection on iOS and will have one more option here.

If you are already using Alamofire, here is what you can benifit from that.

You can add following class to your app, and call MNNetworkUtils.main.isConnected() to get a boolean on whether its connected or not.

#import Alamofire

class MNNetworkUtils {
  static let main = MNNetworkUtils()
  init() {
    manager = NetworkReachabilityManager(host: "google.com")
    listenForReachability()
  }

  private let manager: NetworkReachabilityManager?
  private var reachable: Bool = false
  private func listenForReachability() {
    self.manager?.listener = { [unowned self] status in
      switch status {
      case .notReachable:
        self.reachable = false
      case .reachable(_), .unknown:
        self.reachable = true
      }
    }
    self.manager?.startListening()
  }

  func isConnected() -> Bool {
    return reachable
  }
}

This is a singleton class. Every time, when user connect or disconnect the network, it will override self.reachable to true/false correctly, because we start listening for the NetworkReachabilityManager on singleton initialization.

Also in order to monitor reachability, you need to provide a host, currently I am using google.com feel free to change to any other hosts or one of yours if needed. Change the class name and file name to anything matching your project.

No Application Encryption Key Has Been Specified

I actually had to add a .env file to my project and then copy the contents of .env.example so that the key:generate would work. Not sure why a .env file was not created when I started the project.

When are static variables initialized?

The static variable can be intialize in the following three ways as follow choose any one you like

  1. you can intialize it at the time of declaration
  2. or you can do by making static block eg:

    static {
            // whatever code is needed for initialization goes here
        }
    
  3. There is an alternative to static blocks — you can write a private static method

    class name {
        public static varType myVar = initializeVar();
    
        private static varType initializeVar() {
            // initialization code goes here
        }
    }
    

Dynamically Changing log4j log level

For log4j 2 API , you can use

Logger logger = LogManager.getRootLogger();
Configurator.setAllLevels(logger.getName(), Level.getLevel(level));

appending array to FormData and send via AJAX

Typescript version:

export class Utility {      
    public static convertModelToFormData(model: any, form: FormData = null, namespace = ''): FormData {
        let formData = form || new FormData();
        let formKey;

        for (let propertyName in model) {
            if (!model.hasOwnProperty(propertyName) || !model[propertyName]) continue;
            let formKey = namespace ? `${namespace}[${propertyName}]` : propertyName;
            if (model[propertyName] instanceof Date)
                formData.append(formKey, model[propertyName].toISOString());
            else if (model[propertyName] instanceof Array) {
                model[propertyName].forEach((element, index) => {
                    const tempFormKey = `${formKey}[${index}]`;
                    this.convertModelToFormData(element, formData, tempFormKey);
                });
            }
            else if (typeof model[propertyName] === 'object' && !(model[propertyName] instanceof File))
                this.convertModelToFormData(model[propertyName], formData, formKey);
            else
                formData.append(formKey, model[propertyName].toString());
        }
        return formData;
    }
}

Using:

let formData = Utility.convertModelToFormData(model);

Calling a class function inside of __init__

How about:

class MyClass(object):
    def __init__(self, filename):
        self.filename = filename 
        self.stats = parse_file(filename)

def parse_file(filename):
    #do some parsing
    return results_from_parse

By the way, if you have variables named stat1, stat2, etc., the situation is begging for a tuple: stats = (...).

So let parse_file return a tuple, and store the tuple in self.stats.

Then, for example, you can access what used to be called stat3 with self.stats[2].

Proper way of checking if row exists in table in PL/SQL block

IMO code with a stand-alone SELECT used to check to see if a row exists in a table is not taking proper advantage of the database. In your example you've got a hard-coded ID value but that's not how apps work in "the real world" (at least not in my world - yours may be different :-). In a typical app you're going to use a cursor to find data - so let's say you've got an app that's looking at invoice data, and needs to know if the customer exists. The main body of the app might be something like

FOR aRow IN (SELECT * FROM INVOICES WHERE DUE_DATE < TRUNC(SYSDATE)-60)
LOOP
  -- do something here
END LOOP;

and in the -- do something here you want to find if the customer exists, and if not print an error message.

One way to do this would be to put in some kind of singleton SELECT, as in

-- Check to see if the customer exists in PERSON

BEGIN
  SELECT 'TRUE'
    INTO strCustomer_exists
    FROM PERSON
    WHERE PERSON_ID = aRow.CUSTOMER_ID;
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    strCustomer_exists := 'FALSE';
END;

IF strCustomer_exists = 'FALSE' THEN
  DBMS_OUTPUT.PUT_LINE('Customer does not exist!');
END IF;

but IMO this is relatively slow and error-prone. IMO a Better Way (tm) to do this is to incorporate it in the main cursor:

FOR aRow IN (SELECT i.*, p.ID AS PERSON_ID
               FROM INVOICES i
               LEFT OUTER JOIN PERSON p
                 ON (p.ID = i.CUSTOMER_PERSON_ID)
               WHERE DUE_DATA < TRUNC(SYSDATE)-60)
LOOP
  -- Check to see if the customer exists in PERSON

  IF aRow.PERSON_ID IS NULL THEN
    DBMS_OUTPUT.PUT_LINE('Customer does not exist!');
  END IF;
END LOOP;

This code counts on PERSON.ID being declared as the PRIMARY KEY on PERSON (or at least as being NOT NULL); the logic is that if the PERSON table is outer-joined to the query, and the PERSON_ID comes up as NULL, it means no row was found in PERSON for the given CUSTOMER_ID because PERSON.ID must have a value (i.e. is at least NOT NULL).

Share and enjoy.

make div's height expand with its content

Very simple way

On parent DIV:

height: 100%;

This work for me every time

How to remove symbols from a string with Python?

One way, using regular expressions:

>>> s = "how much for the maple syrup? $20.99? That's ridiculous!!!"
>>> re.sub(r'[^\w]', ' ', s)
'how much for the maple syrup   20 99  That s ridiculous   '
  • \w will match alphanumeric characters and underscores

  • [^\w] will match anything that's not alphanumeric or underscore

Tomcat in Intellij Idea Community Edition

Tomcat (Headless) can be integrated with IntelliJ Idea - Community edition.

Step-by-step instructions are as below:

  1. Add tomcatX-maven-plugin to pom.xml

    <build>
        <plugins>
            <plugin>
                 <groupId>org.apache.tomcat.maven</groupId>
                 <artifactId>tomcat7-maven-plugin</artifactId>
                 <version>2.2</version>
                 <configuration>
                     <path>SampleProject</path>
                 </configuration>
            </plugin>
        </plugins>
    </build>
    
  2. Add new run configuration as below:

    Run >> Edit Configurations >> + >> Maven
    
    Parameters tab ...
    Name :: Tomcat
    Working Directory :: Project Root Directory
    Command Line :: tomcat7:run
    
    Runner tab ...
    VM Options :: <user needed options>
    JRE :: <project needed>
    
  3. Invoke Tomcat in Run/Debug mode directly from IntelliJ Run >> Run/Debug menu

NOTE: Though this is considered a hacking of using using Tomcat integration features of IntelliJ - Enterprise version features, but I would consider this a programmatic way integrating tomcat to the IntelliJ Idea - community edition.

How do I use Bash on Windows from the Visual Studio Code integrated terminal?

I happen to be consulting for a Fortune 500 company and it's sadly Windows 7 and no administrator privileges. Thus Node.js, Npm, Visual Studio Code, etc.. were pushed to my machine - I cannot change a lot, etc...

For this computer running Windows 7:

Below are my new settings. The one not working is commented out.

{
    "update.channel": "none",
    "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe"
    //"terminal.integrated.shell.windows": "C:\\Windows\\sysnative\\bash.exe"
}

angular 2 sort and filter

A pipe takes in data as input and transforms it to a desired output. Add this pipe file:orderby.ts inside your /app folder .

orderby.ts

//The pipe class implements the PipeTransform interface's transform method that accepts an input value and an optional array of parameters and returns the transformed value.

import { Pipe,PipeTransform } from "angular2/core";

//We tell Angular that this is a pipe by applying the @Pipe decorator which we import from the core Angular library.

@Pipe({

  //The @Pipe decorator takes an object with a name property whose value is the pipe name that we'll use within a template expression. It must be a valid JavaScript identifier. Our pipe's name is orderby.

  name: "orderby"
})

export class OrderByPipe implements PipeTransform {
  transform(array:Array<any>, args?) {

    // Check if array exists, in this case array contains articles and args is an array that has 1 element : !id

    if(array) {

      // get the first element

      let orderByValue = args[0]
      let byVal = 1

      // check if exclamation point 

      if(orderByValue.charAt(0) == "!") {

        // reverse the array

        byVal = -1
        orderByValue = orderByValue.substring(1)
      }
      console.log("byVal",byVal);
      console.log("orderByValue",orderByValue);

      array.sort((a: any, b: any) => {
        if(a[orderByValue] < b[orderByValue]) {
          return -1*byVal;
        } else if (a[orderByValue] > b[orderByValue]) {
          return 1*byVal;
        } else {
          return 0;
        }
      });
      return array;
    }
    //
  }
}

In your component file (app.component.ts) import the pipe that you just added using: import {OrderByPipe} from './orderby';

Then, add *ngFor="#article of articles | orderby:'id'" inside your template if you want to sort your articles by id in ascending order or orderby:'!id'" in descending order.

We add parameters to a pipe by following the pipe name with a colon ( : ) and then the parameter value

We must list our pipe in the pipes array of the @Component decorator. pipes: [ OrderByPipe ] .

app.component.ts

import {Component, OnInit} from 'angular2/core';
import {OrderByPipe} from './orderby';

@Component({
    selector: 'my-app',
    template: `
      <h2>orderby-pipe by N2B</h2>
      <p *ngFor="#article of articles | orderby:'id'">
        Article title : {{article.title}}
      </p>
    `,
    pipes: [ OrderByPipe ]

})
export class AppComponent{
    articles:Array<any>
    ngOnInit(){
        this.articles = [
        {
            id: 1,
            title: "title1"
        },{
            id: 2,
            title: "title2",
        }]  
    }

}

More info here on my github and this post on my website

Get the second highest value in a MySQL table

create table svalue (
name varchar(5),
value int
) engine = myisam;

insert into svalue value ('aaa',30),('bbb',10),('ccc',30),('ddd',20);

select * from svalue where value = (
select value 
from svalue
group by value
order by  value desc limit 1,1)

How do I sort a two-dimensional (rectangular) array in C#?

This code should do what you are after, I haven't generalised it for n by n, but that is straight forward. That said - I agree with MusiGenesis, using another object that is a little better suited to this (especially if you intend to do any sort of binding)

(I found the code here)

string[][] array = new string[3][];

array[0] = new string[3] { "apple", "apple", "apple" };
array[1] = new string[3] { "banana", "banana", "dog" };
array[2] = new string[3] { "cat", "hippo", "cat" };         

for (int i = 0; i < 3; i++)
{
   Console.WriteLine(String.Format("{0} {1} {2}", array[i][0], array[i][1], array[i][2]));
}

int j = 2;

Array.Sort(array, delegate(object[] x, object[] y)
  {
    return (x[j] as IComparable).CompareTo(y[ j ]);
  }
);

for (int i = 0; i < 3; i++)
{
  Console.WriteLine(String.Format("{0} {1} {2}", array[i][0], array[i][1], array[i][2]));
}

How to get a string after a specific substring?

s1 = "hello python world , i'm a beginner "
s2 = "world"

print s1[s1.index(s2) + len(s2):]

If you want to deal with the case where s2 is not present in s1, then use s1.find(s2) as opposed to index. If the return value of that call is -1, then s2 is not in s1.

(.text+0x20): undefined reference to `main' and undefined reference to function

This rule

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o

is wrong. It says to create a file named producer.o (with -o producer.o), but you want to create a file named main. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o

As Shahbaz rightly points out, the gmake professionals would also use $^ which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ $^

How to get first N number of elements from an array

With LInQer you can do:

Enumerable.from(list).take(3).toArray();

Unable to connect PostgreSQL to remote database using pgAdmin

I didn't have to change my prostgresql.conf file but, i did have to do the following based on my psql via command line was connecting and pgAdmin not connecting on RDS with AWS.

I did have my RDS set to Publicly Accessible. I made sure my ACL and security groups were wide open and still problem so, I did the following: sudo find . -name *.conf then sudo nano ./data/pg_hba.conf then added to top of directives in pg_hba.conf file host all all 0.0.0.0/0 md5 and pgAdmin automatically logged me in.

This also worked in pg_hba.conf file host all all md5 without any IP address and this also worked with my IP address host all all <myip>/32 md5

As a side note, my RDS was in my default VPC. I had an identical RDS instance in my non-default VPC with identical security group, ACL and security group settings to my default VPC and I could not get it to work. Not sure why but, that's for another day.

Create table with jQuery - append

This line:

$('#here_table').append( '<tr><td>' + 'result' +  i + '</td></tr>' );

Appends to the div#here_table not the new table.

There are several approaches:

/* Note that the whole content variable is just a string */
var content = "<table>"
for(i=0; i<3; i++){
    content += '<tr><td>' + 'result ' +  i + '</td></tr>';
}
content += "</table>"

$('#here_table').append(content);

But, with the above approach it is less manageable to add styles and do stuff dynamically with <table>.

But how about this one, it does what you expect nearly great:

var table = $('<table>').addClass('foo');
for(i=0; i<3; i++){
    var row = $('<tr>').addClass('bar').text('result ' + i);
    table.append(row);
}

$('#here_table').append(table);

Hope this would help.

How can I create and style a div using JavaScript?

create div with id name

var divCreator=function (id){
newElement=document.createElement("div");
newNode=document.body.appendChild(newElement);
newNode.setAttribute("id",id);
}

add text to div

var textAdder = function(id, text) {
target = document.getElementById(id)
target.appendChild(document.createTextNode(text));
}

test code

divCreator("div1");
textAdder("div1", "this is paragraph 1");

output

this is paragraph 1

How to measure the a time-span in seconds using System.currentTimeMillis()?

TimeUnit.SECONDS.convert(start6, TimeUnit.MILLISECONDS);

How To Format A Block of Code Within a Presentation?

http://www.tohtml.com/ created syntax highlighted HTML code for lots of languages. It might be what you're looking for.

How do I create directory if it doesn't exist to create a file?

To Create

(new FileInfo(filePath)).Directory.Create() Before writing to the file.

....Or, If it exists, then create (else do nothing)

System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create(); // If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, content);

React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH

It is located on the Android Studio folder itself, on where you installed it.

enter image description here

Iterate over each line in a string in PHP

It's overly-complicated and ugly but in my opinion this is the way to go:

$fp = fopen("php://memory", 'r+');
fputs($fp, $data);
rewind($fp);
while($line = fgets($fp)){
  // deal with $line
}
fclose($fp);

EXC_BAD_ACCESS signal received

Just to add another situation where this can happen:

I had the code:

NSMutableString *string;
[string   appendWithFormat:@"foo"];

Obviously I had forgotten to allocate memory for the string:

NSMutableString *string = [[NSMutableString alloc] init];
[string   appendWithFormat:@"foo"];

fixes the problem.

How do you do a deep copy of an object in .NET?

I have a simpler idea. Use LINQ with a new selection.

public class Fruit
{
  public string Name {get; set;}
  public int SeedCount {get; set;}
}

void SomeMethod()
{
  List<Fruit> originalFruits = new List<Fruit>();
  originalFruits.Add(new Fruit {Name="Apple", SeedCount=10});
  originalFruits.Add(new Fruit {Name="Banana", SeedCount=0});

  //Deep Copy
  List<Fruit> deepCopiedFruits = from f in originalFruits
              select new Fruit {Name=f.Name, SeedCount=f.SeedCount};
}

Change tab bar tint color on iOS 7

After trying out all the suggested solutions, I couldn't find any very helpful.

I finally tried the following:

[self.tabBar setTintColor:[UIColor orangeColor]];

which worked out perfectly.

I only provided one image for every TabBarItem. Didn't even need a selectedImage.

I even used it inside the Child-ViewControllers to set different TintColors:

UIColor *theColorYouWish = ...;
if ([[self.parentViewController class] isSubclassOfClass:[UITabBarController class]]){
    UITabBarController *tbc = (UITabBarController *) self.parentViewController;
    [tbc.tabBar setTintColor:theColorYouWish];
}

Python function as a function argument?

  1. Yes, it's allowed.
  2. You use the function as you would any other: anotherfunc(*extraArgs)

Powershell: Get FQDN Hostname

"$env:computername.$env:userdnsdomain" 

will work if separated out like this

"$env:computername"+"$env:userdnsdomain"

Difference between text and varchar (character varying)

A good explanation from http://www.sqlines.com/postgresql/datatypes/text:

The only difference between TEXT and VARCHAR(n) is that you can limit the maximum length of a VARCHAR column, for example, VARCHAR(255) does not allow inserting a string more than 255 characters long.

Both TEXT and VARCHAR have the upper limit at 1 Gb, and there is no performance difference among them (according to the PostgreSQL documentation).

What is the correct way to start a mongod service on linux / OS X?

After installing mongodb through brew, run this to get it up and running:

mongod --dbpath /usr/local/var/mongodb

How to subtract/add days from/to a date?

The answer probably depends on what format your date is in, but here is an example using the Date class:

dt <- as.Date("2010/02/10")
new.dt <- dt - as.difftime(2, unit="days")

You can even play with different units like weeks.

Xcode doesn't see my iOS device but iTunes does

My app worked on all simulators but not on my device. I tried just about all the steps from each comment and didn't have any luck. I went to my device settings and switched my "Personal Hotspot" from off to on. Then it was all good!

Meaning of "referencing" and "dereferencing" in C

For a start, you have them backwards: & is reference and * is dereference.

Referencing a variable means accessing the memory address of the variable:

int i = 5;
int * p;
p = &i; //&i returns the memory address of the variable i.

Dereferencing a variable means accessing the variable stored at a memory address:

int i = 5;
int * p;
p = &i;
*p = 7; //*p returns the variable stored at the memory address stored in p, which is i.
//i is now 7

What can MATLAB do that R cannot do?

In my experience moving from MATLAB to Python is an easier transition - Python with numpy/scipy is closer to MATLAB in terms of style and features than R. There are also open source direct MATLAB clones Octave and Scilab.

There is certainly much that MATLAB can do that R can't - in my area MATLAB is used a lot for real time data aquisition - most hardware companies include MATLAB interfaces. While this may be possible with R I imagine it would be a lot more involved. Also Simulink provides a whole area of functionality which I think is missing from R. I'm sure there is more but I'm not so familiar with R.

no such file to load -- rubygems (LoadError)

I had a similar problem on Ubuntu due to having multiple copies of ruby installed. (1.8 and 1.9.1) Unfortunately I need both of them. The solution is to use:

$ sudo update-alternatives --config ruby
There are 2 choices for the alternative ruby (providing /usr/bin/ruby).

  Selection    Path                Priority   Status
------------------------------------------------------------
* 0            /usr/bin/ruby1.8     50        auto mode
  1            /usr/bin/ruby1.8     50        manual mode
  2            /usr/bin/ruby1.9.1   10        manual mode

Press enter to keep the current choice[*], or type selection number: 2
update-alternatives: using /usr/bin/ruby1.9.1 to provide /usr/bin/ruby (ruby) in manual mode.

After doing that bundle install succeeded.

Find files and tar them (with spaces)

Would add a comment to @Steve Kehlet post but need 50 rep (RIP).

For anyone that has found this post through numerous googling, I found a way to not only find specific files given a time range, but also NOT include the relative paths OR whitespaces that would cause tarring errors. (THANK YOU SO MUCH STEVE.)

find . -name "*.pdf" -type f -mtime 0 -printf "%f\0" | tar -czvf /dir/zip.tar.gz --null -T -
  1. . relative directory

  2. -name "*.pdf" look for pdfs (or any file type)

  3. -type f type to look for is a file

  4. -mtime 0 look for files created in last 24 hours

  5. -printf "%f\0" Regular -print0 OR -printf "%f" did NOT work for me. From man pages:

This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use '\0' as a terminator than to use newline, as file names can contain white space and newline characters.

  1. -czvf create archive, filter the archive through gzip , verbosely list files processed, archive name

Edit 2019-08-14: I would like to add, that I was also able to use essentially use the same command in my comment, just using tar itself:

tar -czvf /archiveDir/test.tar.gz --newer-mtime=0 --ignore-failed-read *.pdf

Needed --ignore-failed-read in-case there were no new PDFs for today.

check if array is empty (vba excel)

Adding into this: it depends on what your array is defined as. Consider:

dim a() as integer
dim b() as string
dim c() as variant

'these doesn't work
if isempty(a) then msgbox "integer arrays can be empty"
if isempty(b) then msgbox "string arrays can be empty"

'this is because isempty can only be tested on classes which have an .empty property

'this do work
if isempty(c) then msgbox "variants can be empty"

So, what can we do? In VBA, we can see if we can trigger an error and somehow handle it, for example

dim a() as integer
dim bEmpty as boolean

bempty=false

on error resume next
bempty=not isnumeric(ubound(a))
on error goto 0

But this is really clumsy... A nicer solution is to declare a boolean variable (a public or module level is best). When the array is first initialised, then set this variable. Because it's a variable declared at the same time, if it loses it's value, then you know that you need to reinitialise your array. However, if it is initialised, then all you're doing is checking the value of a boolean, which is low cost. It depends on whether being low cost matters, and if you're going to be needing to check it often.

option explicit

'declared at module level
dim a() as integer
dim aInitialised as boolean

sub DoSomethingWithA()
if not aInitialised then InitialiseA
'you can now proceed confident that a() is intialised
end sub

sub InitialiseA()
'insert code to do whatever is required to initialise A
'e.g. 
redim a(10)
a(1)=123
'...
aInitialised=true
end sub

The last thing you can do is create a function; which in this case will need to be dependent on the clumsy on error method.

function isInitialised(byref a() as variant) as boolean
isInitialised=false
on error resume next
isinitialised=isnumeric(ubound(a))
end function

Pip freeze vs. pip list

When you are using a virtualenv, you can specify a requirements.txt file to install all the dependencies.

A typical usage:

$ pip install -r requirements.txt

The packages need to be in a specific format for pip to understand, which is

feedparser==5.1.3
wsgiref==0.1.2
django==1.4.2
...

That is the "requirements format".

Here, django==1.4.2 implies install django version 1.4.2 (even though the latest is 1.6.x). If you do not specify ==1.4.2, the latest version available would be installed.

You can read more in "Virtualenv and pip Basics", and the official "Requirements File Format" documentation.

Session 'app': Error Installing APK

Make sure that project name doesn't contain special character.

React / JSX Dynamic Component Name

Assume we have a flag, no different from the state or props:

import ComponentOne from './ComponentOne';
import ComponentTwo from './ComponentTwo';

~~~

const Compo = flag ? ComponentOne : ComponentTwo;

~~~

<Compo someProp={someValue} />

With flag Compo fill with one of ComponentOne or ComponentTwo and then the Compo can act like a React Component.

HttpClient won't import in Android Studio

HttpClient is not supported any more in sdk 23. Android 6.0 (API Level 23) release removes support for the Apache HTTP client. You have to use

android {
    useLibrary 'org.apache.http.legacy'
    .
    .
    .

and also add below code snippet in your dependency :

//http final solution for web-service (including file uploading)

compile('org.apache.httpcomponents:httpmime:4.3.6') {
        exclude module: 'httpclient'
}
 compile 'org.apache.httpcomponents:httpclient-android:4.3.5'

It will also help you while you use Use MultipartEntity for File upload.

How to convert a Collection to List?

I believe you can write it as such:

coll.stream().collect(Collectors.toList())

When to use Comparable and Comparator

If you need natural order sorting -- User Comparable IF you need Custom Order Sorting - Use Comparator

Example:

Class Employee{
private int id;
private String name;
private String department;
}

Natural order Sorting would be based on id because it would be unique and custom order sortin g would be name and department.

Refrences:
When should a class be Comparable and/or Comparator? http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html

How to detect when an @Input() value changes in Angular?

@Input() set categoryId(categoryId: number) {
      console.log(categoryId)
}

please try using this method. Hope this helps

How to enable authentication on MongoDB through Docker?

I have hard time when trying to

  • Create other db than admin
  • Add new users and enable authentication to the db above

So I made 2020 answer here

My directory looks like this

+-- docker-compose.yml
+-- mongo-entrypoint
    +-- entrypoint.js

My docker-compose.yml looks like this

version: '3.4'
services:
  mongo-container:
    # If you need to connect to your db from outside this container 
    network_mode: host
    image: mongo:4.2
    environment:
        - MONGO_INITDB_ROOT_USERNAME=admin
        - MONGO_INITDB_ROOT_PASSWORD=pass
    ports:
      - "27017:27017"
    volumes:
      - "$PWD/mongo-entrypoint/:/docker-entrypoint-initdb.d/"
    command: mongod

Please change admin and pass with your need.

Inside mongo-entrypoint, I have entrypoint.js file with this content:

var db = connect("mongodb://admin:pass@localhost:27017/admin");

db = db.getSiblingDB('new_db'); // we can not use "use" statement here to switch db

db.createUser(
    {
        user: "user",
        pwd: "pass",
        roles: [ { role: "readWrite", db: "new_db"} ],
        passwordDigestor: "server",
    }
)

Here again you need to change admin:pass to your root mongo credentials in your docker-compose.yml that you stated before. In additional you need to change new_db, user, pass to your new database name and credentials that you need.

Now you can:

docker-compose up -d

And connect to this db from localhost, please note that I already have mongo cli, you can install it or you can exec to the container above to use mongo command:

mongo new_db -u user -p pass

Or you can connect from other computer

mongo host:27017/new_db -u user -p pass

My git repository: https://github.com/sexydevops/docker-compose-mongo

Hope it can help someone, I lost my afternoon for this ;)

Changing line colors with ggplot()

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

Disable/Enable button in Excel/VBA

I'm using excel 2010 and below VBA code worked fine for a Form Button. It removes the assigned macro from the button and assign in next command.

To disable:

ActiveSheet.Shapes("Button Name").OnAction = Empty
ActiveSheet.Shapes("Button Name").DrawingObject.Font.ColorIndex = 16

To enable:

ActiveSheet.Shapes("Button Name").OnAction = ActiveWorkbook.Name & "!Macro function Name with _Click"
ActiveSheet.Shapes("Button Name").DrawingObject.Font.ColorIndex = 1

Pls note "ActiveWorkbook.Name" stays as it is. Do not insert workbook name instead of "Name".

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I found a solution for this problem. The issue I described in my question occured basically due to the incompatibility of the Microsoft.Jet.OLEDB.4.0 driver in 64 bit OS.

So if we are using Microsoft.Jet.OLEDB.4.0 driver in a 64 bit server, we have to force our application to build in in 32 bit mode (This is the answer I found when I did an extensive search for this known issue) and that causes other part of my code to break.

Fortunately, now Microsoft has released a 64 bit compatible 2010 Office System Driver which can be used as replacement for the traditional Microsoft.Jet.OLEDB.4.0 driver. It works both in 32 bit as well as 64 bit servers. I have used it for Excel file manipulation and it worked fine for me in both the environments. But this driver is in BETA.

You can download this driver from Microsoft Access Database Engine 2010 Redistributable

How to display table data more clearly in oracle sqlplus

If you mean you want to see them like this:

WORKPLACEID NAME       ADDRESS        TELEPHONE
----------- ---------- -------------- ---------
          1 HSBC       Nugegoda Road      43434
          2 HNB Bank   Colombo Road      223423

then in SQL Plus you can set the column widths like this (for example):

column name format a10
column address format a20
column telephone format 999999999

You can also specify the line size and page size if necessary like this:

set linesize 100 pagesize 50

You do this by typing those commands into SQL Plus before running the query. Or you can put these commands and the query into a script file e.g. myscript.sql and run that. For example:

column name format a10
column address format a20
column telephone format 999999999

select name, address, telephone
from mytable;

Get path to execution directory of Windows Forms application

System.Windows.Forms.Application.StartupPath will solve your problem, I think

"Untrusted App Developer" message when installing enterprise iOS Application

In iOS 9.3.1 and up: Settings > General > Device Management

Changing .gitconfig location on Windows

Look in the FILES and ENVIRONMENT section of git help config.

Convert String to Date in MS Access Query

cdate(Format([Datum im Format DDMMYYYY],'##/##/####') ) 

converts string without punctuation characters into date

Executing Javascript from Python

One more solution as PyV8 seems to be unmaintained and dependent on the old version of libv8.

PyMiniRacer It's a wrapper around the v8 engine and it works with the new version and is actively maintained.

pip install py-mini-racer

from py_mini_racer import py_mini_racer
ctx = py_mini_racer.MiniRacer()
ctx.eval("""
function escramble_758(){
    var a,b,c
    a='+1 '
    b='84-'
    a+='425-'
    b+='7450'
    c='9'
    return a+c+b;
}
""")
ctx.call("escramble_758")

And yes, you have to replace document.write with return as others suggested

How to create an alert message in jsp page after submit process is complete

You can also create a new jsp file sayng that form is submited and in your main action file just write its file name

Eg. Your form is submited is in a file succes.jsp Then your action file will have

Request.sendRedirect("success.jsp")

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Java does not support multiple inheritance because of two reasons:

  1. In java, every class is a child of Object class. When it inherits from more than one super class, sub class gets the ambiguity to acquire the property of Object class..
  2. In java every class has a constructor, if we write it explicitly or not at all. The first statement is calling super() to invoke the supper class constructor. If the class has more than one super class, it gets confused.

So when one class extends from more than one super class, we get compile time error.

JVM heap parameters

The JVM resizes the heap adaptively, meaning it will attempt to find the best heap size for your application. -Xms and -Xmx simply specifies the range in which the JVM can operate and resize the heap. If -Xms and -Xmx are the same value, then the JVM's heap size will stay constant at that value.

It's typically best to just set -Xmx and let the JVM find the best heap size, unless there's a specific reason why you need to give the JVM a big heap at JVM launch.

As far as when the JVM actually requests the memory from the OS, I believe it depends on the platform and implementation of the JVM. I imagine that it wouldn't request the memory until your app actually needs it. -Xmx and -Xms just reserves the memory.

What's the meaning of exception code "EXC_I386_GPFLT"?

If the error is thrown inside a closure that defines self as unowned, you may be limited in what you can access and will get this error code in certain situations. Especially while debugging. If this is the case for you try changing [unowned self] to [weak self]

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

You need to add the command 'go' after you set the identity insert. Example:

SET IDENTITY_INSERT sometableWithIdentity ON
go

INSERT sometableWithIdentity (IdentityColumn, col2, col3, ...)
VALUES (AnIdentityValue, col2value, col3value, ...)

SET IDENTITY_INSERT sometableWithIdentity OFF
go

How to work on UAC when installing XAMPP

Just go to start > type search box uac press enter > you will see 'Change user account control settings' > down the you will see never notify. Click on OK. And you are done.

How to dynamically add and remove form fields in Angular 2

add and remove text input element dynamically any one can use this this will work Type of Contact Balance Fund Equity Fund Allocation Allocation % is required! Remove Add Contact

userForm: FormGroup;
  public contactList: FormArray;
  // returns all form groups under contacts
  get contactFormGroup() {
    return this.userForm.get('funds') as FormArray;
  }
  ngOnInit() {
    this.submitUser();
  }
  constructor(public fb: FormBuilder,private router: Router,private ngZone: NgZone,private userApi: ApiService) { }
  // contact formgroup
  createContact(): FormGroup {
    return this.fb.group({
      fundName: ['', Validators.compose([Validators.required])], // i.e Email, Phone
      allocation: [null, Validators.compose([Validators.required])]
    });
  }


  // triggered to change validation of value field type
  changedFieldType(index) {
    let validators = null;

    validators = Validators.compose([
      Validators.required,
      Validators.pattern(new RegExp('^\\+[0-9]?()[0-9](\\d[0-9]{9})$')) // pattern for validating international phone number
    ]);

    this.getContactsFormGroup(index).controls['allocation'].setValidators(
      validators
    );

    this.getContactsFormGroup(index).controls['allocation'].updateValueAndValidity();
  }

  // get the formgroup under contacts form array
  getContactsFormGroup(index): FormGroup {
    // this.contactList = this.form.get('contacts') as FormArray;
    const formGroup = this.contactList.controls[index] as FormGroup;
    return formGroup;
  }

  submitUser() {
    this.userForm = this.fb.group({
      first_name: ['', [Validators.required]],
      last_name: [''],
      email: ['', [Validators.required]],
      company_name: ['', [Validators.required]],
      license_start_date: ['', [Validators.required]],
      license_end_date: ['', [Validators.required]],
      gender: ['Male'],
      funds: this.fb.array([this.createContact()])
    })
    this.contactList = this.userForm.get('funds') as FormArray;
  }
  addContact() {
    this.contactList.push(this.createContact());
  }
  removeContact(index) {
    this.contactList.removeAt(index);
  }

How to increase memory limit for PHP over 2GB?

I had the same problem with commandline php even when ini_set("memory_limit", "-1"); was set, so the limit is in php not from apache.

You should check if you are using the 64bit version of php.

Look at this question about Checking if code is running on 64-bit PHP to find out what php you are using.

I think your php is compiled in 32 bit.

How to upgrade all Python packages with pip

Windows version after consulting the excellent documentation for FOR by Rob van der Woude:

for /F "delims===" %i in ('pip freeze -l') do pip install -U %i

Convert Date format into DD/MMM/YYYY format in SQL Server

Anyone trying to manually enter the date to sql server 'date type' variable use this format while entering :

'yyyy-mm-dd'

Is there an "exists" function for jQuery?

Yes The best method of doing this :

By JQuery :

if($("selector").length){
   //code in the case
}

selector can be Element ID OR Element Class

OR

If you don't want to use jQuery Library then you can achieve this by using Core JavaScript :

By JavaScript :

if(document.getElementById("ElementID")) {
    //Do something...
}

Python spacing and aligning strings

@IronMensan's format method answer is the way to go. But in the interest of answering your question about ljust:

>>> def printit():
...     print 'Location: 10-10-10-10'.ljust(40) + 'Revision: 1'
...     print 'District: Tower'.ljust(40) + 'Date: May 16, 2012'
...     print 'User: LOD'.ljust(40) + 'Time: 10:15'
...
>>> printit()
Location: 10-10-10-10                   Revision: 1
District: Tower                         Date: May 16, 2012
User: LOD                               Time: 10:15

Edit to note this method doesn't require you to know how long your strings are. .format() may also, but I'm not familiar enough with it to say.

>>> uname='LOD'
>>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15'
'User: LOD                               Time: 10:15'
>>> uname='Tiddlywinks'
>>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15'
'User: Tiddlywinks                       Time: 10:15'

Running AMP (apache mysql php) on Android

Here is the App Bit Web Server (PHP,MySQL,PMA)

It can run a variety of CMS like Wordpress, Joomla, Drupal, Prestashop, etc. Besides CMS can also run PHP frameworks like Code Igniter, YII, CakePHP, etc. It is the same as WAMP or LAMP or XAMPP on your computer or laptop, but this is for android devices with lighttpd instead of apache.

How do I style (css) radio buttons and labels?

For any CSS3-enabled browser you can use an adjacent sibling selector for styling your labels

input:checked + label {
    color: white;
}  

MDN's browser compatibility table says essentially all of the current, popular browsers (Chrome, IE, Firefox, Safari), on both desktop and mobile, are compatible.

Regex pattern for checking if a string starts with a certain substring?

I really recommend using the String.StartsWith method over the Regex.IsMatch if you only plan to check the beginning of a string.

  • Firstly, the regular expression in C# is a language in a language with does not help understanding and code maintenance. Regular expression is a kind of DSL.
  • Secondly, many developers does not understand regular expressions: it is something which is not understandable for many humans.
  • Thirdly, the StartsWith method brings you features to enable culture dependant comparison which regular expressions are not aware of.

In your case you should use regular expressions only if you plan implementing more complex string comparison in the future.

How to compare two colors for similarity/difference

The best way is deltaE. DeltaE is a number that shows the difference of the colors. If deltae < 1 then the difference can't recognize by human eyes. I wrote a code in canvas and js for converting rgb to lab and then calculating delta e. On this example the code is recognising pixels which have different color with a base color that I saved as LAB1. and then if it is different makes those pixels red. You can increase or reduce the sensitivity of the color difference with increae or decrease the acceptable range of delta e. In this example I assigned 10 for deltaE in the line that I wrote (deltae <= 10):

<script>   
  var constants = {
    canvasWidth: 700, // In pixels.
    canvasHeight: 600, // In pixels.
    colorMap: new Array() 
          };



  // -----------------------------------------------------------------------------------------------------

  function fillcolormap(imageObj1) {


    function rgbtoxyz(red1,green1,blue1){ // a converter for converting rgb model to xyz model
 var red2 = red1/255;
 var green2 = green1/255;
 var blue2 = blue1/255;
 if(red2>0.04045){
      red2 = (red2+0.055)/1.055;
      red2 = Math.pow(red2,2.4);
 }
 else{
      red2 = red2/12.92;
 }
 if(green2>0.04045){
      green2 = (green2+0.055)/1.055;
      green2 = Math.pow(green2,2.4);    
 }
 else{
      green2 = green2/12.92;
 }
 if(blue2>0.04045){
      blue2 = (blue2+0.055)/1.055;
      blue2 = Math.pow(blue2,2.4);    
 }
 else{
      blue2 = blue2/12.92;
 }
 red2 = (red2*100);
 green2 = (green2*100);
 blue2 = (blue2*100);
 var x = (red2 * 0.4124) + (green2 * 0.3576) + (blue2 * 0.1805);
 var y = (red2 * 0.2126) + (green2 * 0.7152) + (blue2 * 0.0722);
 var z = (red2 * 0.0193) + (green2 * 0.1192) + (blue2 * 0.9505);
 var xyzresult = new Array();
 xyzresult[0] = x;
 xyzresult[1] = y;
 xyzresult[2] = z;
 return(xyzresult);
} //end of rgb_to_xyz function
function xyztolab(xyz){ //a convertor from xyz to lab model
 var x = xyz[0];
 var y = xyz[1];
 var z = xyz[2];
 var x2 = x/95.047;
 var y2 = y/100;
 var z2 = z/108.883;
 if(x2>0.008856){
      x2 = Math.pow(x2,1/3);
 }
 else{
      x2 = (7.787*x2) + (16/116);
 }
 if(y2>0.008856){
      y2 = Math.pow(y2,1/3);
 }
 else{
      y2 = (7.787*y2) + (16/116);
 }
 if(z2>0.008856){
      z2 = Math.pow(z2,1/3);
 }
 else{
      z2 = (7.787*z2) + (16/116);
 }
 var l= 116*y2 - 16;
 var a= 500*(x2-y2);
 var b= 200*(y2-z2);
 var labresult = new Array();
 labresult[0] = l;
 labresult[1] = a;
 labresult[2] = b;
 return(labresult);

}

    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    var imageX = 0;
    var imageY = 0;

    context.drawImage(imageObj1, imageX, imageY, 240, 140);
    var imageData = context.getImageData(0, 0, 240, 140);
    var data = imageData.data;
    var n = data.length;
   // iterate over all pixels

    var m = 0;
    for (var i = 0; i < n; i += 4) {
      var red = data[i];
      var green = data[i + 1];
      var blue = data[i + 2];
    var xyzcolor = new Array();
    xyzcolor = rgbtoxyz(red,green,blue);
    var lab = new Array();
    lab = xyztolab(xyzcolor);
    constants.colorMap.push(lab); //fill up the colormap array with lab colors.         
      } 

  }

// -----------------------------------------------------------------------------------------------------

    function colorize(pixqty) {

         function deltae94(lab1,lab2){    //calculating Delta E 1994

         var c1 = Math.sqrt((lab1[1]*lab1[1])+(lab1[2]*lab1[2]));
         var c2 =  Math.sqrt((lab2[1]*lab2[1])+(lab2[2]*lab2[2]));
         var dc = c1-c2;
         var dl = lab1[0]-lab2[0];
         var da = lab1[1]-lab2[1];
         var db = lab1[2]-lab2[2];
         var dh = Math.sqrt((da*da)+(db*db)-(dc*dc));
         var first = dl;
         var second = dc/(1+(0.045*c1));
         var third = dh/(1+(0.015*c1));
         var deresult = Math.sqrt((first*first)+(second*second)+(third*third));
         return(deresult);
          } // end of deltae94 function
    var lab11 =  new Array("80","-4","21");
    var lab12 = new Array();
    var k2=0;
    var canvas = document.getElementById('myCanvas');
                                        var context = canvas.getContext('2d');
                                        var imageData = context.getImageData(0, 0, 240, 140);
                                        var data = imageData.data;

    for (var i=0; i<pixqty; i++) {

    lab12 = constants.colorMap[i];

    var deltae = deltae94(lab11,lab12);     
                                        if (deltae <= 10) {

                                        data[i*4] = 255;
                                        data[(i*4)+1] = 0;
                                        data[(i*4)+2] = 0;  
                                        k2++;
                                        } // end of if 
                                } //end of for loop
    context.clearRect(0,0,240,140);
    alert(k2);
    context.putImageData(imageData,0,0);
} 
// -----------------------------------------------------------------------------------------------------

$(window).load(function () {    
  var imageObj = new Image();
  imageObj.onload = function() {
  fillcolormap(imageObj);    
  }
  imageObj.src = './mixcolor.png';
});

// ---------------------------------------------------------------------------------------------------
 var pixno2 = 240*140; 
 </script>

How can I send an email through the UNIX mailx command?

From the man page:

Sending mail

To send a message to one or more people, mailx can be invoked with arguments which are the names of people to whom the mail will be sent. The user is then expected to type in his message, followed by an ‘control-D’ at the beginning of a line.

In other words, mailx reads the content to send from standard input and can be redirected to like normal. E.g.:

ls -l $HOME | mailx -s "The content of my home directory" [email protected]

How to wait for the 'end' of 'resize' event and only then perform an action?

You can store a reference id to any setInterval or setTimeout. Like this:

var loop = setInterval(func, 30);

// some time later clear the interval
clearInterval(loop);

To do this without a "global" variable you can add a local variable to the function itself. Ex:

$(window).resize(function() {
    clearTimeout(this.id);
    this.id = setTimeout(doneResizing, 500);
});

function doneResizing(){
  $("body").append("<br/>done!");   
}

javascript regex for special characters

function nameInput(limitField)
{
//LimitFile here is a text input and this function is passed to the text 
onInput
var inputString = limitField.value;
// here we capture all illegal chars by adding a ^ inside the class,
// And overwrite them with "".
var newStr = inputString.replace(/[^a-zA-Z-\-\']/g, "");
limitField.value = newStr;
}

This function only allows alphabets, both lower case and upper case and - and ' characters. May help you build yours.

Do I need to pass the full path of a file in another directory to open()?

Here's a snippet that will walk the file tree for you:

indir = '/home/des/test'
for root, dirs, filenames in os.walk(indir):
    for f in filenames:
        print(f)
        log = open(indir + f, 'r')

Share application "link" in Android

finally, this code is worked for me to open the email client from android device. try this snippet.

Intent testIntent = new Intent(Intent.ACTION_VIEW);
                    Uri data = Uri.parse("mailto:?subject=" + "Feedback" + "&body=" + "Write Feedback here....." + "&to=" + "[email protected]");
                    testIntent.setData(data);
                    startActivity(testIntent);

Step-by-step debugging with IPython

What about ipdb.set_trace() ? In your code :

import ipdb; ipdb.set_trace()

update: now in Python 3.7, we can write breakpoint(). It works the same, but it also obeys to the PYTHONBREAKPOINT environment variable. This feature comes from this PEP.

This allows for full inspection of your code, and you have access to commands such as c (continue), n (execute next line), s (step into the method at point) and so on.

See the ipdb repo and a list of commands. IPython is now called (edit: part of) Jupyter.


ps: note that an ipdb command takes precedence over python code. So in order to write list(foo) you'd need print(list(foo)), or !list(foo) .

Also, if you like the ipython prompt (its emacs and vim modes, history, completions,…) it's easy to get the same for your project since it's based on the python prompt toolkit.

favicon.png vs favicon.ico - why should I use PNG instead of ICO?

Answer replaced (and turned Community Wiki) due to numerous updates and notes from various others in this thread:

  • ICOs and PNGs both allow full alpha channel based transparency
  • ICO allows for backwards compatibility to older browsers (e.g. IE6)
  • PNG probably has broader tooling support for transparency, but you can find tools to create alpha-channel ICOs as well, such as the Dynamic Drive tool and Photoshop plugin mentioned by @mercator.

Feel free to consult the other answers here for more details.

Change the color of a bullet in a html list?

<ul>
<li style="color:#ddd;"><span style="color:#000;">List Item</span></li>
</ul>

JavaScript Array Push key value

You have to use bracket notation:

var obj = {};
obj[a[i]] = 0;
x.push(obj);

The result will be:

x = [{left: 0}, {top: 0}];

Maybe instead of an array of objects, you just want one object with two properties:

var x = {};

and

x[a[i]] = 0;

This will result in x = {left: 0, top: 0}.

How can I check if a string is null or empty in PowerShell?

An extension of the answer from Keith Hill (to account for whitespace):

$str = "     "
if ($str -and $version.Trim()) { Write-Host "Not Empty" } else { Write-Host "Empty" }

This returns "Empty" for nulls, empty strings, and strings with whitespace, and "Not Empty" for everything else.

Working with dictionaries/lists in R

I'll just comment you can get a lot of mileage out of table when trying to "fake" a dictionary also, e.g.

> x <- c("a","a","b","b","b","c")
> (t <- table(x))
x
a b c 
2 3 1 
> names(t)
[1] "a" "b" "c"
> o <- order(as.numeric(t))
> names(t[o])
[1] "c" "a" "b"

etc.

Twitter Bootstrap: Print content of modal window

I was facing two issues Issue 1: all fields were coming one after other and Issue 2 white space at the bottom of the page when used to print from popup.

I Resolved this by

making display none to all body * elements most of them go for visibility hidden which creates space so avoid visibility hidden

    @media print {
        body * {
           display:none;
        width:auto;
        height:auto;
        margin:0px;padding:0px; 
        }
        #printSection, #printSection * {
            display:inline-block!important;
        }
        #printSection {
            position:absolute;
            left:0;
            top:0;  
            margin:0px; 
            page-break-before: none;
            page-break-after: none;
            page-break-inside: avoid;      
        }
#printSection .form-group{

      width:100%!important;
      float:left!important;
      page-break-after: avoid;
    }
#printSection label{
        float:left!important;
        width:200px!important;
        display:inline-block!important;
      }

#printSection .form-control.search-input{
        float:left!important;
        width:200px!important;
        display: inline-block!important;
      }
}

Pass variables by reference in JavaScript

JavaScript can modify array items inside a function (it is passed as a reference to the object/array).

function makeAllPretty(items) {
   for (var x = 0; x < myArray.length; x++){
      // Do stuff to the array
      items[x] = makePretty(items[x]);
   }
}

myArray = new Array(var1, var2, var3);
makeAllPretty(myArray);

Here's another example:

function inc(items) {
  for (let i=0; i < items.length; i++) {
    items[i]++;
  }
}

let values = [1,2,3];
inc(values);
console.log(values);
// Prints [2,3,4]

How to speed up insertion performance in PostgreSQL

In addition to excellent Craig Ringer's post and depesz's blog post, if you would like to speed up your inserts through ODBC (psqlodbc) interface by using prepared-statement inserts inside a transaction, there are a few extra things you need to do to make it work fast:

  1. Set the level-of-rollback-on-errors to "Transaction" by specifying Protocol=-1 in the connection string. By default psqlodbc uses "Statement" level, which creates a SAVEPOINT for each statement rather than an entire transaction, making inserts slower.
  2. Use server-side prepared statements by specifying UseServerSidePrepare=1 in the connection string. Without this option the client sends the entire insert statement along with each row being inserted.
  3. Disable auto-commit on each statement using SQLSetConnectAttr(conn, SQL_ATTR_AUTOCOMMIT, reinterpret_cast<SQLPOINTER>(SQL_AUTOCOMMIT_OFF), 0);
  4. Once all rows have been inserted, commit the transaction using SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);. There is no need to explicitly open a transaction.

Unfortunately, psqlodbc "implements" SQLBulkOperations by issuing a series of unprepared insert statements, so that to achieve the fastest insert one needs to code up the above steps manually.

How can I do factory reset using adb in android?

You can send intent MASTER_CLEAR in adb:

adb shell am broadcast -a android.intent.action.MASTER_CLEAR

or as root

adb shell  "su -c 'am broadcast -a android.intent.action.MASTER_CLEAR'"

How to get last items of a list in Python?

Here are several options for getting the "tail" items of an iterable:

Given

n = 9
iterable = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Desired Output

[2, 3, 4, 5, 6, 7, 8, 9, 10]

Code

We get the latter output using any of the following options:

from collections import deque
import itertools

import more_itertools


# A: Slicing
iterable[-n:]


# B: Implement an itertools recipe
def tail(n, iterable):
    """Return an iterator over the last *n* items of *iterable*.

        >>> t = tail(3, 'ABCDEFG')
        >>> list(t)
        ['E', 'F', 'G']

    """
    return iter(deque(iterable, maxlen=n))
list(tail(n, iterable))


# C: Use an implemented recipe, via more_itertools
list(more_itertools.tail(n, iterable))


# D: islice, via itertools
list(itertools.islice(iterable, len(iterable)-n, None))


# E: Negative islice, via more_itertools
list(more_itertools.islice_extended(iterable, -n, None))

Details

  • A. Traditional Python slicing is inherent to the language. This option works with sequences such as strings, lists and tuples. However, this kind of slicing does not work on iterators, e.g. iter(iterable).
  • B. An itertools recipe. It is generalized to work on any iterable and resolves the iterator issue in the last solution. This recipe must be implemented manually as it is not officially included in the itertools module.
  • C. Many recipes, including the latter tool (B), have been conveniently implemented in third party packages. Installing and importing these these libraries obviates manual implementation. One of these libraries is called more_itertools (install via > pip install more-itertools); see more_itertools.tail.
  • D. A member of the itertools library. Note, itertools.islice does not support negative slicing.
  • E. Another tool is implemented in more_itertools that generalizes itertools.islice to support negative slicing; see more_itertools.islice_extended.

Which one do I use?

It depends. In most cases, slicing (option A, as mentioned in other answers) is most simple option as it built into the language and supports most iterable types. For more general iterators, use any of the remaining options. Note, options C and E require installing a third-party library, which some users may find useful.

Check if process returns 0 with batch file

How to write a compound statement with if?

You can write a compound statement in an if block using parenthesis. The first parenthesis must come on the line with the if and the second on a line by itself.

if %ERRORLEVEL% == 0 (
    echo ErrorLevel is zero
    echo A second statement
) else if %ERRORLEVEL% == 1 (
    echo ErrorLevel is one
    echo A second statement
) else (
   echo ErrorLevel is > 1
   echo A second statement
)

JSF(Primefaces) ajax update of several elements by ID's

If the to-be-updated component is not inside the same NamingContainer component (ui:repeat, h:form, h:dataTable, etc), then you need to specify the "absolute" client ID. Prefix with : (the default NamingContainer separator character) to start from root.

<p:ajax process="@this" update="count :subTotal"/>

To be sure, check the client ID of the subTotal component in the generated HTML for the actual value. If it's inside for example a h:form as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.

<p:ajax process="@this" update="count :formId:subTotal"/>

Space separation of IDs is more recommended as <f:ajax> doesn't support comma separation and starters would otherwise get confused.

using jquery $.ajax to call a PHP function

Use $.ajax to call a server context (or URL, or whatever) to invoke a particular 'action'. What you want is something like:

$.ajax({ url: '/my/site',
         data: {action: 'test'},
         type: 'post',
         success: function(output) {
                      alert(output);
                  }
});

On the server side, the action POST parameter should be read and the corresponding value should point to the method to invoke, e.g.:

if(isset($_POST['action']) && !empty($_POST['action'])) {
    $action = $_POST['action'];
    switch($action) {
        case 'test' : test();break;
        case 'blah' : blah();break;
        // ...etc...
    }
}

I believe that's a simple incarnation of the Command pattern.

Generate class from database table

If you have access to SQL Server 2016, you can use the FOR JSON (with INCLUDE_NULL_VALUES) option to get JSON output from a select statement. Copy the output, then in Visual Studio, paste special -> paste JSON as class.

Kind of a budget solution, but might save some time.

How do I get the current username in .NET using C#?

The documentation for Environment.UserName seems to be a bit conflicting:

Environment.UserName Property

On the same page it says:

Gets the user name of the person who is currently logged on to the Windows operating system.

AND

displays the user name of the person who started the current thread

If you test Environment.UserName using RunAs, it will give you the RunAs user account name, not the user originally logged on to Windows.

count number of rows in a data frame in R based on group

The count() function in plyr does what you want:

library(plyr)

count(mydf, "MONTH-YEAR")

Padding characters in printf

Simple Console Span/Fill/Pad/Padding with automatic scaling/resizing Method and Example.

function create-console-spanner() {
    # 1: left-side-text, 2: right-side-text
    local spanner="";
    eval printf -v spanner \'"%0.1s"\' "-"{1..$[$(tput cols)- 2 - ${#1} - ${#2}]}
    printf "%s %s %s" "$1" "$spanner" "$2";
}

Example: create-console-spanner "loading graphics module" "[success]"

Now here is a full-featured-color-character-terminal-suite that does everything in regards to printing a color and style formatted string with a spanner.

# Author: Triston J. Taylor <[email protected]>
# Date: Friday, October 19th, 2018
# License: OPEN-SOURCE/ANY (NO-PRODUCT-LIABILITY OR WARRANTIES)
# Title: paint.sh
# Description: color character terminal driver/controller/suite

declare -A PAINT=([none]=`tput sgr0` [bold]=`tput bold` [black]=`tput setaf 0` [red]=`tput setaf 1` [green]=`tput setaf 2` [yellow]=`tput setaf 3` [blue]=`tput setaf 4` [magenta]=`tput setaf 5` [cyan]=`tput setaf 6` [white]=`tput setaf 7`);

declare -i PAINT_ACTIVE=1;

function paint-replace() {
    local contents=$(cat)
    echo "${contents//$1/$2}"
}

source <(cat <<EOF
function paint-activate() {
    echo "\$@" | $(for k in ${!PAINT[@]}; do echo -n paint-replace \"\&$k\;\" \"\${PAINT[$k]}\" \|; done) cat;
}
EOF
)

source <(cat <<EOF
function paint-deactivate(){
    echo "\$@" | $(for k in ${!PAINT[@]}; do echo -n paint-replace \"\&$k\;\" \"\" \|; done) cat;    
}
EOF
)

function paint-get-spanner() {
    (( $# == 0 )) && set -- - 0;
    declare -i l=$(( `tput cols` - ${2}))
    eval printf \'"%0.1s"\' "${1:0:1}"{1..$l}
}

function paint-span() {
    local left_format=$1 right_format=$3
    local left_length=$(paint-format -l "$left_format") right_length=$(paint-format -l "$right_format")
    paint-format "$left_format";
    paint-get-spanner "$2" $(( left_length + right_length));
    paint-format "$right_format";
}

function paint-format() {
    local VAR="" OPTIONS='';
    local -i MODE=0 PRINT_FILE=0 PRINT_VAR=1 PRINT_SIZE=2;
    while [[ "${1:0:2}" =~ ^-[vl]$ ]]; do
        if [[ "$1" == "-v" ]]; then OPTIONS=" -v $2"; MODE=$PRINT_VAR; shift 2; continue; fi;
        if [[ "$1" == "-l" ]]; then OPTIONS=" -v VAR"; MODE=$PRINT_SIZE; shift 1; continue; fi;
    done;
    OPTIONS+=" --"
    local format="$1"; shift;
    if (( MODE != PRINT_SIZE && PAINT_ACTIVE )); then
        format=$(paint-activate "$format&none;")
    else
        format=$(paint-deactivate "$format")
    fi
    printf $OPTIONS "${format}" "$@";
    (( MODE == PRINT_SIZE )) && printf "%i\n" "${#VAR}" || true;
}

function paint-show-pallette() {
    local -i PAINT_ACTIVE=1
    paint-format "Normal: &red;red &green;green &blue;blue &magenta;magenta &yellow;yellow &cyan;cyan &white;white &black;black\n";
    paint-format "  Bold: &bold;&red;red &green;green &blue;blue &magenta;magenta &yellow;yellow &cyan;cyan &white;white &black;black\n";
}

To print a color, that's simple enough: paint-format "&red;This is %s\n" red And you might want to get bold later on: paint-format "&bold;%s!\n" WOW

The -l option to the paint-format function measures the text so you can do console font metrics operations.

The -v option to the paint-format function works the same as printf but cannot be supplied with -l

Now for the spanning!

paint-span "hello " . " &blue;world" [note: we didn't add newline terminal sequence, but the text fills the terminal, so the next line only appears to be a newline terminal sequence]

and the output of that is:

hello ............................. world

How can I get (query string) parameters from the URL in Next.js?

  • Get it by using the below code in the about.js page:

    Enter image description here

_x000D_
_x000D_
// pages/about.js
import Link from 'next/link'
export default ({ url: { query: { name } } }) => (
  <p>Welcome to About! { name }</p>
)
_x000D_
_x000D_
_x000D_

Shrinking navigation bar when scrolling down (bootstrap3)

For those not willing to use jQuery here is a Vanilla Javascript way of doing the same using classList:

function runOnScroll() {
    var element = document.getElementsByTagName('nav')  ;
    if(document.body.scrollTop >= 50) {
        element[0].classList.add('shrink')
    } else {
        element[0].classList.remove('shrink')
    }
    console.log(topMenu[0].classList)

};

There might be a nicer way of doing it using toggle, but the above works fine in Chrome

How to convert signed to unsigned integer in python

Since version 3.2 :

def toSigned(n, byte_count): 
  return int.from_bytes(n.to_bytes(byte_count, 'little'), 'little', signed=True)

output :

In [8]: toSigned(5, 1)                                                                                                                                                                                                                                                                                                     
Out[8]: 5

In [9]: toSigned(0xff, 1)                                                                                                                                                                                                                                                                                                  
Out[9]: -1

how to get html content from a webview?

I would suggest instead of trying to extract the HTML from the WebView, you extract the HTML from the URL. By this, I mean using a third party library such as JSoup to traverse the HTML for you. The following code will get the HTML from a specific URL for you

public static String getHtml(String url) throws ClientProtocolException, IOException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet, localContext);
        String result = "";

        BufferedReader reader = new BufferedReader(
            new InputStreamReader(
                response.getEntity().getContent()
            )
        );

        String line = null;
        while ((line = reader.readLine()) != null){
            result += line + "\n";
        }
        return result;
    }

how to insert datetime into the SQL Database table?

if you got actuall time in mind GETDATE() would be the function what you looking for

Warning: mysqli_error() expects exactly 1 parameter, 0 given error

mysqli_error function requires $myConnection as parameters, that's why you get the warning

How can I turn a DataTable to a CSV?

StringBuilder sb = new StringBuilder();
        SaveFileDialog fileSave = new SaveFileDialog();
        IEnumerable<string> columnNames = tbCifSil.Columns.Cast<DataColumn>().
                                          Select(column => column.ColumnName);
        sb.AppendLine(string.Join(",", columnNames));

        foreach (DataRow row in tbCifSil.Rows)
        {
            IEnumerable<string> fields = row.ItemArray.Select(field =>string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
            sb.AppendLine(string.Join(",", fields));
        }

        fileSave.ShowDialog();
        File.WriteAllText(fileSave.FileName, sb.ToString());

how to replace characters in hive?

select translate(description,'\\t','') from myTable;

Translates the input string by replacing the characters present in the from string with the corresponding characters in the to string. This is similar to the translate function in PostgreSQL. If any of the parameters to this UDF are NULL, the result is NULL as well. (Available as of Hive 0.10.0, for string types)

Char/varchar support added as of Hive 0.14.0

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

If you want n bits specific then you could first create a bitmask and then AND it with your number to take the desired bits.

Simple function to create mask from bit a to bit b.

unsigned createMask(unsigned a, unsigned b)
{
   unsigned r = 0;
   for (unsigned i=a; i<=b; i++)
       r |= 1 << i;

   return r;
}

You should check that a<=b.

If you want bits 12 to 16 call the function and then simply & (logical AND) r with your number N

r = createMask(12,16);
unsigned result = r & N;

If you want you can shift the result. Hope this helps

slf4j: how to log formatted message, object array, exception

In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using

<encoder>
    <pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern> 
</encoder>

the %ex in pattern is what makes the difference

How to get height of entire document with JavaScript?

Full Document height calculation:

To be more generic and find the height of any document you could just find the highest DOM Node on current page with a simple recursion:

;(function() {
    var pageHeight = 0;

    function findHighestNode(nodesList) {
        for (var i = nodesList.length - 1; i >= 0; i--) {
            if (nodesList[i].scrollHeight && nodesList[i].clientHeight) {
                var elHeight = Math.max(nodesList[i].scrollHeight, nodesList[i].clientHeight);
                pageHeight = Math.max(elHeight, pageHeight);
            }
            if (nodesList[i].childNodes.length) findHighestNode(nodesList[i].childNodes);
        }
    }

    findHighestNode(document.documentElement.childNodes);

    // The entire page height is found
    console.log('Page height is', pageHeight);
})();

You can Test it on your sample sites (http://fandango.com/ or http://paperbackswap.com/) with pasting this script to a DevTools Console.

NOTE: it is working with Iframes.

Enjoy!

number several equations with only one number

How about something like:

\documentclass{article}

\usepackage{amssymb,amsmath}

\begin{document}

\begin{equation}\label{A_Label}
  \begin{split}
    w^T x_i + b \geqslant 1-\xi_i \text{ if } y_i &= 1, \\
    w^T x_i + b \leqslant -1+\xi_i \text{ if } y_i &= -1
  \end{split}
\end{equation}

\end{document}

which produces:

enter image description here

extract column value based on another column pandas dataframe

Use df[df['B']==3]['A'].values if you just want item itself without the brackets

How to add a button dynamically using jquery

Your append line must be in your test() function

EDIT:

Here are two versions:

Version 1: jQuery listener

$(function(){
    $('button').on('click',function(){
        var r= $('<input type="button" value="new button"/>');
        $("body").append(r);
    });
});

DEMO HERE

Version 2: With a function (like your example)

function createInput(){
    var $input = $('<input type="button" value="new button" />');
    $input.appendTo($("body"));
}

DEMO HERE

Note: This one can be done with either .appendTo or with .append.

R Markdown - changing font size and font type in html output

To change the font size, you don't need to know a lot of html for this. Open the html output with notepad ++. Control F search for "font-size". You should see a section with font sizes for the headers (h1, h2, h3,...).

Add the following somewhere in this section.

body {
  font-size: 16px;
}

The font size above is 16 pt font. You can change the number to whatever you want.

Debugging PHP Mail() and/or PHPMailer

It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.

I've always used phpMailer's SMTP feature:

$mail->IsSMTP();
$mail->Host = "localhost";

And if you need debug info:

$mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only

How can I format date by locale in Java?

Yes, using DateFormat.getDateInstance(int style, Locale aLocale) This displays the current date in a locale-specific way.

So, for example:

DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, yourLocale);
String formattedDate = df.format(yourDate);

See the docs for the exact meaning of the style parameter (SHORT, MEDIUM, etc)

Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

Hi I had the same issue,

what I've done to solve it. is to turn on the less secure app. after connecting to my gmail account. I entered this link: https://www.google.com/settings/security/lesssecureapps

Then I turn on the secure app and, and the it worked. it has been said also above

JSHint and jQuery: '$' is not defined

If you're using an IntelliJ editor, under

  • Preferences/Settings
    • Javascript
      • Code Quality Tools
        • JSHint
          • Predefined (at bottom), click Set

You can type in anything, for instance console:false, and it will add that to the list (.jshintrc) as well - as a global.

npm install errors with Error: ENOENT, chmod

I got this error while trying to install a grunt plugin. i found i had an outdated version of npm and the error went away after updating npm to the latest version

npm install -g npm

Optional args in MATLAB functions

A simple way of doing this is via nargin (N arguments in). The downside is you have to make sure that your argument list and the nargin checks match.

It is worth remembering that all inputs are optional, but the functions will exit with an error if it calls a variable which is not set. The following example sets defaults for b and c. Will exit if a is not present.

function [ output_args ] = input_example( a, b, c )
if nargin < 1
  error('input_example :  a is a required input')
end

if nargin < 2
  b = 20
end

if nargin < 3
  c = 30
end
end

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

This type of issue is cropping up again using the Windows 8 / IE 11 combination with the new version of Java (1.8.0_31). The installation seems to work, but after installing Java via the Java Control Panel Update tab, every time you run a Java applet you are told your version of Java is outdated, but when you follow the prompts to again update, you are told your version of Java is newer than the one on the web.

As with a previous iteration of such problems, what worked for me was, after installation, unchecking "Internet Options | Security | Enable Protected Mode", running a Java applet and then re-checking it and everything is fine.

Do people at Oracle not test on Windows 8 with IE or does this only happen for people with particular extensions enabled?

As before, this problem didn't happen on Windows 7, but there I noticed that the SSLv3 changes now prevent you from running a local applet in Internet Explorer unless you remove that line from the java.security file. But this problem doesn't happen on Windows 8, so it is not clear what is actually happening.

If Oracle doesn't make the update process less rocky, people won't update. I've seen many people lately using 2009 versions of JRE 1.6. That is the sort of situation that often doesn't end well.

How to convert a GUID to a string in C#?

In Visual Basic, you can call a parameterless method without the braces (()). In C#, they're mandatory. So you should write:

String guid = System.Guid.NewGuid().ToString();

Without the braces, you're assigning the method itself (instead of its result) to the variable guid, and obviously the method cannot be converted to a String, hence the error.

Bootstrap NavBar with left, center or right aligned items

The simplest solution:

Just divide the navbar into columns: for instance, if you have 24 columns over all, 12 are going to be empty and 12 are going to contrain the navbar:

<nav class="navbar navbar-default">
    <div class="row">
       <div class="col-sm-4"></div>
       <div class="col-sm-4"></div>
       <div class="col-sm-4"></div>

       <div class="col-sm-12">
           <ul class="nav navbar-nav" align="center">
              <li><a href="#">Home</a></li>
              <li><a href="#">First Link</a></li>
              <li><a href="#">Second Link</a></li>
              <li><a href="#">Third Link</a></li>
              <li><a href="#">Fourth Link</a></li>
           </ul>
       </div>
    </div>
</nav>

Git log to get commits only for a specific branch

The following shell command should do what you want:

git log --all --not $(git rev-list --no-walk --exclude=refs/heads/mybranch --all)

Caveats

If you have mybranch checked out, the above command won't work. That's because the commits on mybranch are also reachable by HEAD, so Git doesn't consider the commits to be unique to mybranch. To get it to work when mybranch is checked out, you must also add an exclude for HEAD:

git log --all --not $(git rev-list --no-walk \
    --exclude=refs/heads/mybranch \
    --exclude=HEAD \
    --all)

However, you should not exclude HEAD unless the mybranch is checked out, otherwise you risk showing commits that are not exclusive to mybranch.

Similarly, if you have a remote branch named origin/mybranch that corresponds to the local mybranch branch, you'll have to exclude it:

git log --all --not $(git rev-list --no-walk \
    --exclude=refs/heads/mybranch \
    --exclude=refs/remotes/origin/mybranch \
    --all)

And if the remote branch is the default branch for the remote repository (usually only true for origin/master), you'll have to exclude origin/HEAD as well:

git log --all --not $(git rev-list --no-walk \
    --exclude=refs/heads/mybranch \
    --exclude=refs/remotes/origin/mybranch \
    --exclude=refs/remotes/origin/HEAD \
    --all)

If you have the branch checked out, and there's a remote branch, and the remote branch is the default for the remote repository, then you end up excluding a lot:

git log --all --not $(git rev-list --no-walk \
    --exclude=refs/heads/mybranch \
    --exclude=HEAD
    --exclude=refs/remotes/origin/mybranch \
    --exclude=refs/remotes/origin/HEAD \
    --all)

Explanation

The git rev-list command is a low-level (plumbing) command that walks the given revisions and dumps the SHA1 identifiers encountered. Think of it as equivalent to git log except it only shows the SHA1—no log message, no author name, no timestamp, none of that "fancy" stuff.

The --no-walk option, as the name implies, prevents git rev-list from walking the ancestry chain. So if you type git rev-list --no-walk mybranch it will only print one SHA1 identifier: the identifier of the tip commit of the mybranch branch.

The --exclude=refs/heads/mybranch --all arguments tell git rev-list to start from each reference except for refs/heads/mybranch.

So, when you run git rev-list --no-walk --exclude=refs/heads/mybranch --all, Git prints the SHA1 identifier of the tip commit of each ref except for refs/heads/mybranch. These commits and their ancestors are the commits you are not interested in—these are the commits you do not want to see.

The other commits are the ones you want to see, so we collect the output of git rev-list --no-walk --exclude=refs/heads/mybranch --all and tell Git to show everything but those commits and their ancestors.

The --no-walk argument is necessary for large repositories (and is an optimization for small repositories): Without it, Git would have to print, and the shell would have to collect (and store in memory) many more commit identifiers than necessary. With a large repository, the number of collected commits could easily exceed the shell's command-line argument limit.

Git bug?

I would have expected the following to work:

git log --all --not --exclude=refs/heads/mybranch --all

but it does not. I'm guessing this is a bug in Git, but maybe it's intentional.

List all virtualenv

Silly question. Found that there's a

lsvirtualenv

command which lists all existing virtualenv.