Programs & Examples On #Mozilla

DO NOT USE THIS TAG, it is going to be removed. The Mozilla Foundation is a non-profit organization that exists to support and provide leadership for the open source Mozilla project.

Convert web page to image

Awesome : http://wkhtmltopdf.org/

wkhtmltopdf and wkhtmltoimage are open source (LGPLv3) command line tools to render HTML into PDF and various image formats using the QT Webkit rendering engine.

Way to create multiline comments in Bash?

Use : ' to open and ' to close.

For example:

: '
This is a
very neat comment
in bash
'

Python virtualenv questions

Normally virtualenv creates environments in the current directory. Unless you're intending to create virtual environments in C:\Windows\system32 for some reason, I would use a different directory for environments.

You shouldn't need to mess with paths: use the activate script (in <env>\Scripts) to ensure that the Python executable and path are environment-specific. Once you've done this, the command prompt changes to indicate the environment. You can then just invoke easy_install and whatever you install this way will be installed into this environment. Use deactivate to set everything back to how it was before activation.

Example:

c:\Temp>virtualenv myenv
New python executable in myenv\Scripts\python.exe
Installing setuptools..................done.
c:\Temp>myenv\Scripts\activate
(myenv) C:\Temp>deactivate
C:\Temp>

Notice how I didn't need to specify a path for deactivate - activate does that for you, so that when activated "Python" will run the Python in the virtualenv, not your system Python. (Try it - do an import sys; sys.prefix and it should print the root of your environment.)

You can just activate a new environment to switch between environments/projects, but you'll need to specify the whole path for activate so it knows which environment to activate. You shouldn't ever need to mess with PATH or PYTHONPATH explicitly.

If you use Windows Powershell then you can take advantage of a wrapper. On Linux, the virtualenvwrapper (the link points to a port of this to Powershell) makes life with virtualenv even easier.

Update: Not incorrect, exactly, but perhaps not quite in the spirit of virtualenv. You could take a different tack: for example, if you install Django and anything else you need for your site in your virtualenv, then you could work in your project directory (where you're developing your site) with the virtualenv activated. Because it was activated, your Python would find Django and anything else you'd easy_installed into the virtual environment: and because you're working in your project directory, your project files would be visible to Python, too.

Further update: You should be able to use pip, distribute instead of setuptools, and just plain python setup.py install with virtualenv. Just ensure you've activated an environment before installing something into it.

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

The marked answer is the correct one. However, Pricey, you should follow up on this with your AD and desktop admin groups. They are misusing the IE11 Enterprise Mode site list. Microsoft does NOT intend it to be used for all intranet sites within an organization at all. That would be propagating the existing "render all intranet sites in compatibility mode" setting that is the bane of corporate website advancement the world over.

It's meant to implemented as a "Black list", with the handful of sites that actually require a legacy browser mode listed in the Enterprise Mode list with their rendering requirements specified. All other sites in your organization are then freed up to use Edge. The people in your organization who implemented it with all intranet sites included to start with have completely misunderstood how Enterprise Mode is meant to be implemented.

Not showing placeholder for input type="date" field

I used this in my css:

input[type="date"]:before{
    color:lightgray;
    content:attr(placeholder);
}

input[type="date"].full:before {
    color:black;
    content:""!important;
}

and put somenthing like this into javascript:

$("#myel").on("input",function(){
    if($(this).val().length>0){
    $(this).addClass("full");
}
else{
   $(this).removeClass("full");
   }
 });

it works for me for mobile devices (Ios8 and android). But I used jquery inputmask for desktop with input text type. This solution it's a nice way if your code run on ie8.

Check if a list contains an item in Ansible

You do not need {{}} in when conditions. What you are searching for is:

- fail: msg="unsupported version"
  when: version not in acceptable_versions

if statements matching multiple values

How about:

if (new[] {1, 2}.Contains(value))

It's a hack though :)

Or if you don't mind creating your own extension method, you can create the following:

public static bool In<T>(this T obj, params T[] args)
{
    return args.Contains(obj);
}

And you can use it like this:

if (1.In(1, 2))

:)

Preventing console window from closing on Visual Studio C/C++ Console application

Use Console.ReadLine() at the end of the program. This will keep the window open until you press the Enter key. See https://docs.microsoft.com/en-us/dotnet/api/system.console.readline for details.

IF EXIST C:\directory\ goto a else goto b problems windows XP batch files

From the help (if /?):

The ELSE clause must occur on the same line as the command after the IF.  For
example:

    IF EXIST filename. (
        del filename.
    ) ELSE (
        echo filename. missing.
    )

The following would NOT work because the del command needs to be terminated
by a newline:

    IF EXIST filename. del filename. ELSE echo filename. missing

Nor would the following work, since the ELSE command must be on the same line
as the end of the IF command:

    IF EXIST filename. del filename.
    ELSE echo filename. missing

Should a function have only one return statement?

Single exit point - all other things equal - makes code significantly more readable. But there's a catch: popular construction

resulttype res;
if if if...
return res;

is a fake, "res=" is not much better than "return". It has single return statement, but multiple points where function actually ends.

If you have function with multiple returns (or "res="s), it's often a good idea to break it into several smaller functions with single exit point.

"elseif" syntax in JavaScript

Actually, technically when indented properly, it would be:

if (condition) {
    ...
} else {
    if (condition) {
        ...
    } else {
        ...
    }
}

There is no else if, strictly speaking.

(Update: Of course, as pointed out, the above is not considered good style.)

Mongoose.js: Find user by username LIKE value

The following query will find the documents with required string case insensitively and with global occurrence also

var name = 'Peter';
    db.User.find({name:{
                         $regex: new RegExp(name, "ig")
                     }
                },function(err, doc) {
                                     //Your code here...
              });

Google Forms file upload complete example

As of October 2016, Google has added a file upload question type in native Google Forms, no Google Apps Script needed. See documentation.

How to determine whether a given Linux is 32 bit or 64 bit?

Try uname -m. Which is short of uname --machine and it outputs:

x86_64 ==> 64-bit kernel
i686   ==> 32-bit kernel

Otherwise, not for the Linux kernel, but for the CPU, you type:

cat /proc/cpuinfo

or:

grep flags /proc/cpuinfo

Under "flags" parameter, you will see various values: see "What do the flags in /proc/cpuinfo mean?" Among them, one is named lm: Long Mode (x86-64: amd64, also known as Intel 64, i.e. 64-bit capable)

lm ==> 64-bit processor

Or using lshw (as mentioned below by Rolf of Saxony), without sudo (just for grepping the cpu width):

lshw -class cpu|grep "^       width"|uniq|awk '{print $2}'

Note: you can have a 64-bit CPU with a 32-bit kernel installed.
(as ysdx mentions in his/her own answer, "Nowadays, a system can be multiarch so it does not make sense anyway. You might want to find the default target of the compiler")

Why does this CSS margin-top style not work?

I guess setting the position property of the #inner div to relative may also help achieve the effect. But anyways I tried the original code pasted in the Question on IE9 and latest Google Chrome and they already give the desirable effect without any modifications.

How do I search an SQL Server database for a string?

If I want to find where anything I want to search is, I use this:

DECLARE @search_string    varchar(200)
    SET @search_string = '%myString%'

    SELECT DISTINCT
           o.name AS Object_Name,
           o.type_desc,
           m.definition
      FROM sys.sql_modules m
           INNER JOIN
           sys.objects o
             ON m.object_id = o.object_id
     WHERE m.definition Like @search_string;

Accessing localhost:port from Android emulator

if you are using some 3rd party package like node express or angular-cli you will need to find the IP of your machine, and attach your host to that IP within the server startup config (instead of localhost). Then launch it from the emulator using the IP. For example, I had to use: ng serve -H 10.149.212.104 to use the angular-cli. Then from the emulator I used: http://10.149.212.104:4200

MySQL Check if username and password matches in Database

//set vars
$user = $_POST['user'];
$pass = md5($_POST['pass']);

if ($user&&$pass) 
{
//connect to db
$connect = mysql_connect("$server","$username","$password") or die("not connecting");
mysql_select_db("users") or die("no db :'(");
$query = mysql_query("SELECT * FROM $tablename WHERE username='$user'");

$numrows = mysql_num_rows($query);


if ($numrows!=0)
{
//while loop
  while ($row = mysql_fetch_assoc($query))
  {
    $dbusername = $row['username'];
    $dbpassword = $row['password'];
  }
  else
      die("incorrect username/password!");
}
else
  echo "user does not exist!";
} 
else
    die("please enter a username and password!");

How can I check whether Google Maps is fully loaded?

I'm creating html5 mobile apps and I noticed that the idle, bounds_changed and tilesloaded events fire when the map object is created and rendered (even if it is not visible).

To make my map run code when it is shown for the first time I did the following:

google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
    //this part runs when the mapobject is created and rendered
    google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
        //this part runs when the mapobject shown for the first time
    });
});

error: the details of the application error from being viewed remotely

In my case I got this message because there's a special char (&) in my connectionstring, remove it then everything's good.

Cheers

How do I get and set Environment variables in C#?

If the purpose of reading environment variable is to override the values in the appsetting.json or any other config file, you can archive it through EnvironmentVariablesExtensions.

var builder = new ConfigurationBuilder()
                .AddJsonFile("appSettings.json")
                .AddEnvironmentVariables(prefix: "ABC_")

var config = builder.Build();

enter image description here

According to this example, Url for the environment is read from the appsettings.json. but when the AddEnvironmentVariables(prefix: "ABC_") line is added to the ConfigurationBuilder the value appsettings.json will be override by in the environement varibale value.

Query to list number of records in each table in a database

sp_MSForEachTable 'DECLARE @t AS VARCHAR(MAX); 
SELECT @t = CAST(COUNT(1) as VARCHAR(MAX)) 
+ CHAR(9) + CHAR(9) + ''?'' FROM ? ; PRINT @t'

Output:

enter image description here

How to close a JavaFX application on window close?

Try

 System.exit(0);

this should terminate thread main and end the main program

Change the "No file chosen":

using label with label text changed

<input type="file" id="files" name="files" class="hidden"/>
<label for="files" id="lable_file">Select file</label>

add jquery

<script>
     $("#files").change(function(){
        $("#lable_file").html($(this).val().split("\\").splice(-1,1)[0] || "Select file");     
     });
</script>

Representing EOF in C code?

I have been researching a lot about the EOF signal. In the book on Programming in C by Dennis Ritchie it is first encountered while introducing putchar() and getchar() commands. It basically marks the end of the character string input.

For eg. Let us write a program that seeks two numerical inputs and prints their sum. You'll notice after each numerical input you press Enter to mark the signal that you have completed the iput action. But while working with character strings Enter is read as just another character ['\n': newline character]. To mark the termination of input you enter ^Z(Ctrl + Z on keyboard) in a completely new line and then enter. That signals the next lines of command to get executed.

#include <stdio.h>

int main()
{
char c;
int i = 0;
printf("INPUT:\t");
c = getchar();

while (c != EOF)
{
   ++i;
   c = getchar();
   
};

printf("NUMBER OF CHARACTERS %d.", i);

return 0;}

The above is the code to count number of characters including '\n'(newline) and '\t'( space) characters. If you don't wanna count the newline characters do this :

#include <stdio.h>

int main()
{
char c;
int i = 0;
printf("INPUT:\t");
c = getchar();

while (c != EOF)
{
    if (c != '\n')
    {
        ++i;
    }

    c = getchar();
    };

printf("NUMBER OF CHARACTERS %d.", i);

return 0;}. 

NOW THE MAIN THINK HOOW TO GIVE INPUT. IT'S SIMPLE: Write all the story you want then go in a new line and enter ^Z and then enter again.

spring PropertyPlaceholderConfigurer and context:property-placeholder

First, you don't need to define both of those locations. Just use classpath:config/properties/database.properties. In a WAR, WEB-INF/classes is a classpath entry, so it will work just fine.

After that, I think what you mean is you want to use Spring's schema-based configuration to create a configurer. That would go like this:

<context:property-placeholder location="classpath:config/properties/database.properties"/>

Note that you don't need to "ignoreResourceNotFound" anymore. If you need to define the properties separately using util:properties:

<context:property-placeholder properties-ref="jdbcProperties" ignore-resource-not-found="true"/>

There's usually not any reason to define them separately, though.

Explain ExtJS 4 event handling

Let's start by describing DOM elements' event handling.

DOM node event handling

First of all you wouldn't want to work with DOM node directly. Instead you probably would want to utilize Ext.Element interface. For the purpose of assigning event handlers, Element.addListener and Element.on (these are equivalent) were created. So, for example, if we have html:

<div id="test_node"></div>

and we want add click event handler.
Let's retrieve Element:

var el = Ext.get('test_node');

Now let's check docs for click event. It's handler may have three parameters:

click( Ext.EventObject e, HTMLElement t, Object eOpts )

Knowing all this stuff we can assign handler:

//       event name      event handler
el.on(    'click'        , function(e, t, eOpts){
  // handling event here
});

Widgets event handling

Widgets event handling is pretty much similar to DOM nodes event handling.

First of all, widgets event handling is realized by utilizing Ext.util.Observable mixin. In order to handle events properly your widget must containg Ext.util.Observable as a mixin. All built-in widgets (like Panel, Form, Tree, Grid, ...) has Ext.util.Observable as a mixin by default.

For widgets there are two ways of assigning handlers. The first one - is to use on method (or addListener). Let's for example create Button widget and assign click event to it. First of all you should check event's docs for handler's arguments:

click( Ext.button.Button this, Event e, Object eOpts )

Now let's use on:

var myButton = Ext.create('Ext.button.Button', {
  text: 'Test button'
});
myButton.on('click', function(btn, e, eOpts) {
  // event handling here
  console.log(btn, e, eOpts);
});

The second way is to use widget's listeners config:

var myButton = Ext.create('Ext.button.Button', {
  text: 'Test button',
  listeners : {
    click: function(btn, e, eOpts) {
      // event handling here
      console.log(btn, e, eOpts);
    }
  }
});

Notice that Button widget is a special kind of widgets. Click event can be assigned to this widget by using handler config:

var myButton = Ext.create('Ext.button.Button', {
  text: 'Test button',
  handler : function(btn, e, eOpts) {
    // event handling here
    console.log(btn, e, eOpts);
  }
});

Custom events firing

First of all you need to register an event using addEvents method:

myButton.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);

Using the addEvents method is optional. As comments to this method say there is no need to use this method but it provides place for events documentation.

To fire your event use fireEvent method:

myButton.fireEvent('myspecialevent1', arg1, arg2, arg3, /* ... */);

arg1, arg2, arg3, /* ... */ will be passed into handler. Now we can handle your event:

myButton.on('myspecialevent1', function(arg1, arg2, arg3, /* ... */) {
  // event handling here
  console.log(arg1, arg2, arg3, /* ... */);
});

It's worth mentioning that the best place for inserting addEvents method call is widget's initComponent method when you are defining new widget:

Ext.define('MyCustomButton', {
  extend: 'Ext.button.Button',
  // ... other configs,
  initComponent: function(){
    this.addEvents('myspecialevent1', 'myspecialevent2', 'myspecialevent3', /* ... */);
    // ...
    this.callParent(arguments);
  }
});
var myButton = Ext.create('MyCustomButton', { /* configs */ });

Preventing event bubbling

To prevent bubbling you can return false or use Ext.EventObject.preventDefault(). In order to prevent browser's default action use Ext.EventObject.stopPropagation().

For example let's assign click event handler to our button. And if not left button was clicked prevent default browser action:

myButton.on('click', function(btn, e){
  if (e.button !== 0)
    e.preventDefault();
});

'Operation is not valid due to the current state of the object' error during postback

If your stack trace looks like following then you are sending a huge load of json objects to server

Operation is not valid due to the current state of the object. 
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
    at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
    at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
    at System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input)
    at Failing.Page_Load(Object sender, EventArgs e) 
    at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
    at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
    at System.Web.UI.Control.OnLoad(EventArgs e)
    at System.Web.UI.Control.LoadRecursive()
    at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

For resolution, please update your web config with following key. If you are not able to get the stack trace then please use fiddler. If it still does not help then please try increasing the number to 10000 or something

<configuration>
<appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="1000" />
</appSettings>
</configuration>

For more details, please read this Microsoft kb article

Android, How to create option Menu

Replace return super.onCreateOptionsMenu(menu); with return true; in your onCreateOptionsMenu method This will help

And you should also have the onCreate method in your activity

What is the difference between “int” and “uint” / “long” and “ulong”?

The primitive data types prefixed with "u" are unsigned versions with the same bit sizes. Effectively, this means they cannot store negative numbers, but on the other hand they can store positive numbers twice as large as their signed counterparts. The signed counterparts do not have "u" prefixed.

The limits for int (32 bit) are:

int: –2147483648 to 2147483647 
uint: 0 to 4294967295 

And for long (64 bit):

long: -9223372036854775808 to 9223372036854775807
ulong: 0 to 18446744073709551615

IntelliJ IDEA "The selected directory is not a valid home for JDK"

In case you missed the configuration at the Project Structure(File -> Project Structure), just reconfigure it like below:

For Java enter image description here

For Android enter image description here

Enjoy coding J

CKEditor, Image Upload (filebrowserUploadUrl)

This simple demo may help you in getting what you want. Here is the html/php code from where you want to upload the image:

<html>
<head>
 <script src="http://cdn.ckeditor.com/4.6.2/standard-all/ckeditor.js"></script>
  </head>
<body>
<form  action="index.php" method="POST"  style="width:500xp;">

<textarea rows="5" name="content" id="content"></textarea>

<br>
<input type="submit" name="submit" value="Post">

</form>
<script>
 CKEDITOR.replace( 'content', {
  height: 300,
  filebrowserUploadUrl: "upload.php"
 });
</script>
</body>
</html>

and here is the code for upload.php file.

 <?php
if(isset($_FILES['upload']['name']))
{
 $file = $_FILES['upload']['tmp_name'];
 $file_name = $_FILES['upload']['name'];
 $file_name_array = explode(".", $file_name);
 $extension = end($file_name_array);
 //we want to save the image with timestamp and randomnumber
 $new_image_name = time() . rand(). '.' . $extension;
 chmod('upload', 0777);
 $allowed_extension = array("jpg", "gif", "png");
 if(in_array($extension, $allowed_extension))
 {
  move_uploaded_file($file, 'upload/' . $new_image_name);
  $function_number = $_GET['CKEditorFuncNum'];
  $url = 'upload/' . $new_image_name;
  $message = '';
  echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction($function_number, '$url', '$message');</script>";
 }
}
?>

Note: Don't forget to create a folder "upload" in the same folder and keep all the three files in the same directory. Later you may change their directories once you understand how it works. Also not forget to press send it to the server as shown in picture below.

screenshot

WPF MVVM ComboBox SelectedItem or SelectedValue not working

I have noticed this behavior before as well. I have noticed that the SelectedIndex property doesn't cause the same bug. If you can restructure your ViewModel to expose the index of the selected item, and bind to that, you should be good to go.

How to disable compiler optimizations in gcc?

Long time ago, but still needed.

info - https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html
list - gcc -Q --help=optimizers test.c | grep enabled
disable as many as you like with:
  gcc **-fno-web** -Q --help=optimizers test.c | grep enabled

SQL Inner join more than two tables

SELECT * 
FROM table1 
INNER JOIN table2
      ON table1.primaryKey=table2.table1Id
INNER JOIN table3
      ON table1.primaryKey=table3.table1Id

Benefits of using the conditional ?: (ternary) operator

One thing to recognize when using the ternary operator that it is an expression not a statement.

In functional languages like scheme the distinction doesn't exists:

(if (> a b) a b)

Conditional ?: Operator "Doesn't seem to be as flexible as the if/else construct"

In functional languages it is.

When programming in imperative languages I apply the ternary operator in situations where I typically would use expressions (assignment, conditional statements, etc).

How can I remove the search bar and footer added by the jQuery DataTables plugin?

this worked for me #table is a Id of table

$('#table').dataTable({searching: false, paging: false, info: false});

Capturing browser logs with Selenium WebDriver using Java

Before launching webdriver, we just set this environment variable to let chrome generate it:

export CHROME_LOG_FILE=$(pwd)/tests/e2e2/logs/client.log

Docker-Compose can't connect to Docker Daemon

It appears your issue was created by an old Docker bug, where the socket file was not recreated after Docker crashed. If this is the issue, then renaming the socket file should allow it to be re-created:

$ sudo service docker stop
$ sudo mv /var/lib/docker /var/lib/docker.bak
$ sudo service docker start

Since this bug is fixed, most people getting the error Couldn't connect to Docker daemon are probably getting it because they are not in the docker group and don't have permissions to read that file. Running with sudo docker ... will fix that, but isn't a great solution.

Docker can be run as a non-root user (without sudo) that has the proper group permissions. The Linux post-install docs has the details. The short version:

$ sudo groupadd docker
$ sudo usermod -aG docker $USER
# Log out and log back in again to apply the groups
$ groups  # docker should be in the list of groups for your user
$ docker run hello-world  # Works without sudo

This allows users in the docker group to run docker and docker-compose commands without sudo. Docker itself runs a root, allowing some attacks, so you still need to be careful with what containers you run. See Docker Security Documentation for more details.

What is the function of FormulaR1C1?

Here's some info from my blog on how I like to use formular1c1 outside of vba:

You’ve just finished writing a formula, copied it to the whole spreadsheet, formatted everything and you realize that you forgot to make a reference absolute: every formula needed to reference Cell B2 but now, they all reference different cells.

How are you going to do a Find/Replace on the cells, considering that one has B5, the other C12, the third D25, etc., etc.?

The easy way is to update your Reference Style to R1C1. The R1C1 reference works with relative positioning: R marks the Row, C the Column and the numbers that follow R and C are either relative positions (between [ ]) or absolute positions (no [ ]).

Examples:

  • R[2]C refers to the cell two rows below the cell in which the formula’s in
  • RC[-1] refers to the cell one column to the left
  • R1C1 refers the cell in the first row and first cell ($A$1)

What does it matter? Well, When you wrote your first formula back in the beginning of this post, B2 was the cell 4 rows above the cell you wrote it in, i.e. R[-4]C. When you copy it across and down, while the A1 reference changes, the R1C1 reference doesn’t. Throughout the whole spreadsheet, it’s R[-4]C. If you switch to R1C1 Reference Style, you can replace R[-4]C by R2C2 ($B$2) with a simple Find / Replace and be done in one fell swoop.

Force Internet Explorer to use a specific Java Runtime Environment install?

For the server-side solution (which your question was originally ambiguous about), this page at sun lists one way to specify a JRE. Specifically,

<OBJECT 
  classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
  width="200" height="200">
  <PARAM name="code" value="Applet1.class">
</OBJECT>

The classid attribute identifies which version of Java Plug-in to use.

Following is an alternative form of the classid attribute:

classid="clsid:CAFEEFAC-xxxx-yyyy-zzzz-ABCDEFFEDCBA"

In this form, "xxxx", "yyyy", and "zzzz" are four-digit numbers that identify the specific version of Java Plug-in to be used.

For example, to use Java Plug-in version 1.5.0, you specify:

classid="clsid:CAFEEFAC-0015-0000-0000-ABCDEFFEDCBA"

Working with dictionaries/lists in R

To extend a little bit answer of Calimo I present few more things you may find useful while creating this quasi dictionaries in R:

a) how to return all the VALUES of the dictionary:

>as.numeric(foo)
[1] 12 22 33

b) check whether dictionary CONTAINS KEY:

>'tic' %in% names(foo)
[1] TRUE

c) how to ADD NEW key, value pair to dictionary:

c(foo,tic2=44)

results:

tic       tac       toe     tic2
12        22        33        44 

d) how to fulfill the requirement of REAL DICTIONARY - that keys CANNOT repeat(UNIQUE KEYS)? You need to combine b) and c) and build function which validates whether there is such key, and do what you want: e.g don't allow insertion, update value if the new differs from the old one, or rebuild somehow key(e.g adds some number to it so it is unique)

e) how to DELETE pair BY KEY from dictionary:

foo<-foo[which(foo!=foo[["tac"]])]

offsetting an html anchor to adjust for fixed header

I was looking for a solution to this as well. In my case, it was pretty easy.

I have a list menu with all the links:

<ul>
<li><a href="#one">one</a></li>
<li><a href="#two">two</a></li>
<li><a href="#three">three</a></li>
<li><a href="#four">four</a></li>
</ul>

And below that the headings where it should go to.

<h3>one</h3>
<p>text here</p>

<h3>two</h3>
<p>text here</p>

<h3>three</h3>
<p>text here</p>

<h3>four</h3>
<p>text here</p>

Now because I have a fixed menu at the top of my page I can't just make it go to my tag because that would be behind the menu.

Instead, I put a span tag inside my tag with the proper id.

<h3><span id="one"></span>one</h3>

Now use 2 lines of CSS to position them properly.

h3{ position:relative; }
h3 span{ position:absolute; top:-200px;}

Change the top value to match the height of your fixed header (or more). Now I assume this would work with other elements as well.

Dynamically Changing log4j log level

If you would want to change the logging level of all the loggers use the below method. This will enumerate over all the loggers and change the logging level to given level. Please make sure that you DO NOT have log4j.appender.loggerName.Threshold=DEBUG property set in your log4j.properties file.

public static void changeLogLevel(Level level) {
    Enumeration<?> loggers = LogManager.getCurrentLoggers();
    while(loggers.hasMoreElements()) {
        Logger logger = (Logger) loggers.nextElement();
        logger.setLevel(level);
    }
}

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I've gotten same problem. The servers logs showed:

DEBUG: <-- origin: null

I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine

How is length implemented in Java Arrays?

According to the Java Language Specification (specifically §10.7 Array Members) it is a field:

  • The public final field length, which contains the number of components of the array (length may be positive or zero).

Internally the value is probably stored somewhere in the object header, but that is an implementation detail and depends on the concrete JVM implementation.

The HotSpot VM (the one in the popular Oracle (formerly Sun) JRE/JDK) stores the size in the object-header:

[...] arrays have a third header field, for the array size.

Uncaught SyntaxError: Unexpected token < On Chrome

To override the error that you might experience in Chrome (and probably in Safari), try to set the Ajax parameter as dataType: "json". Then you shouldn't call parseJSON() on the obj because the response you'll get comes deserialized.

Draw path between two points using Google Maps Android API v2

First of all we will get source and destination points between which we have to draw route. Then we will pass these attribute to below function.

 public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
        StringBuilder urlString = new StringBuilder();
        urlString.append("http://maps.googleapis.com/maps/api/directions/json");
        urlString.append("?origin=");// from
        urlString.append(Double.toString(sourcelat));
        urlString.append(",");
        urlString.append(Double.toString( sourcelog));
        urlString.append("&destination=");// to
        urlString.append(Double.toString( destlat));
        urlString.append(",");
        urlString.append(Double.toString( destlog));
        urlString.append("&sensor=false&mode=driving&alternatives=true");
        urlString.append("&key=YOUR_API_KEY");
        return urlString.toString();
 }

This function will make the url that we will send to get Direction API response. Then we will parse that response . The parser class is

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    // constructor
    public JSONParser() {
    }
    public String getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            json = sb.toString();
            is.close();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        return json;

    }
}

This parser will return us string. We will call it like that.

JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);

Now we will send this string to our drawpath function. The drawpath function is

public void drawPath(String  result) {

    try {
            //Tranform the string into a json object
           final JSONObject json = new JSONObject(result);
           JSONArray routeArray = json.getJSONArray("routes");
           JSONObject routes = routeArray.getJSONObject(0);
           JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
           String encodedString = overviewPolylines.getString("points");
           List<LatLng> list = decodePoly(encodedString);
           Polyline line = mMap.addPolyline(new PolylineOptions()
                                    .addAll(list)
                                    .width(12)
                                    .color(Color.parseColor("#05b1fb"))//Google maps blue color
                                    .geodesic(true)
                    );
           /*
           for(int z = 0; z<list.size()-1;z++){
                LatLng src= list.get(z);
                LatLng dest= list.get(z+1);
                Polyline line = mMap.addPolyline(new PolylineOptions()
                .add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude,   dest.longitude))
                .width(2)
                .color(Color.BLUE).geodesic(true));
            }
           */
    } 
    catch (JSONException e) {

    }
} 

Above code will draw the path on mMap. The code of decodePoly is

private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<LatLng>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng( (((double) lat / 1E5)),
                 (((double) lng / 1E5) ));
        poly.add(p);
    }

    return poly;
}

As direction call may take time so we will do all this in Asynchronous task. My Asynchronous task was

private class connectAsyncTask extends AsyncTask<Void, Void, String>{
    private ProgressDialog progressDialog;
    String url;
    connectAsyncTask(String urlPass){
        url = urlPass;
    }
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Fetching route, Please wait...");
        progressDialog.setIndeterminate(true);
        progressDialog.show();
    }
    @Override
    protected String doInBackground(Void... params) {
        JSONParser jParser = new JSONParser();
        String json = jParser.getJSONFromUrl(url);
        return json;
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);   
        progressDialog.hide();        
        if(result!=null){
            drawPath(result);
        }
    }
}

I hope it will help.

cleanup php session files

Use cron with find to delete files older than given threshold. For example to delete files that haven't been accessed for at least a week.

find .session/ -atime +7  -exec rm {} \;

LF will be replaced by CRLF in git - What is that and is it important?

If you want, you can deactivate this feature in your git core config using

git config core.autocrlf false

But it would be better to just get rid of the warnings using

git config core.autocrlf true

Curl setting Content-Type incorrectly

I think you want to specify

-H "Content-Type:text/xml"

with a colon, not an equals.

Java List.contains(Object with field value equal to x)

Binary Search

You can use Collections.binarySearch to search an element in your list (assuming the list is sorted):

Collections.binarySearch(list, new YourObject("a1", "b",
                "c"), new Comparator<YourObject>() {

            @Override
            public int compare(YourObject o1, YourObject o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });

which will return a negative number if the object is not present in the collection or else it will return the index of the object. With this you can search for objects with different searching strategies.

Split String by delimiter position using oracle SQL

Therefore, I would like to separate the string by the furthest delimiter.

I know this is an old question, but this is a simple requirement for which SUBSTR and INSTR would suffice. REGEXP are still slower and CPU intensive operations than the old subtsr and instr functions.

SQL> WITH DATA AS
  2    ( SELECT 'F/P/O' str FROM dual
  3    )
  4  SELECT SUBSTR(str, 1, Instr(str, '/', -1, 1) -1) part1,
  5         SUBSTR(str, Instr(str, '/', -1, 1) +1) part2
  6  FROM DATA
  7  /

PART1 PART2
----- -----
F/P   O

As you said you want the furthest delimiter, it would mean the first delimiter from the reverse.

You approach was fine, but you were missing the start_position in INSTR. If the start_position is negative, the INSTR function counts back start_position number of characters from the end of string and then searches towards the beginning of string.

proper way to sudo over ssh

Another way is to use the -t switch to ssh:

ssh -t user@server "sudo script"

See man ssh:

 -t      Force pseudo-tty allocation.  This can be used to execute arbi-
         trary screen-based programs on a remote machine, which can be
         very useful, e.g., when implementing menu services.  Multiple -t
         options force tty allocation, even if ssh has no local tty.

Restoring database from .mdf and .ldf files of SQL Server 2008

Yes, it is possible. The steps are:

  1. First Put the .mdf and .ldf file in C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\ folder

  2. Then go to sql software , Right-click “Databases” and click the “Attach” option to open the Attach Databases dialog box

  3. Click the “Add” button to open and Locate Database Files From C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\folder

  4. Click the "OK" button. SQL Server Management Studio loads the database from the .MDF file.

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.

I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.

# Enable TCP/IP

Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable

# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433

# Modify TCP/IP properties to enable an IP address

$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }

# Restart SQL Server

Restart-Service 'MSSQL$SQLEXPRESS'

How to show live preview in a small popup of linked page on mouse over on link?

You can display a live preview of a link using javascript using the code below.

_x000D_
_x000D_
<embed src="https://www.w3schools.com/html/default.asp" width="60" height="40" />_x000D_
<p id="p1"><a href="http://cnet.com">Cnet</a></p>_x000D_
<p id="p2"><a href="http://codegena.com">Codegena</a></p>_x000D_
<p id="p3"><a href="http://apple.com">Apple</a></p>_x000D_
_x000D_
_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>_x000D_
  <link href="http://codegena.com/assets/css/image-preview-for-link.css" rel="stylesheet">     _x000D_
  <script type="text/javascript">_x000D_
    $(function() {_x000D_
                $('#p1 a').miniPreview({ prefetch: 'pageload' });_x000D_
                $('#p2 a').miniPreview({ prefetch: 'parenthover' });_x000D_
                $('#p3 a').miniPreview({ prefetch: 'none' });_x000D_
            });_x000D_
  </script> <script src="http://codegena.com/assets/js/image-preview-for-link.js"></script>
_x000D_
_x000D_
_x000D_

Learn more about it at Codegena

id="p1" - Fetch image preview on page load.
id="p2" - Fetch preview on hover.
id="p3" - Fetch preview image each time you hover.

Disable/Enable Submit Button until all forms have been filled

Just use

document.getElementById('submitbutton').disabled = !cansubmit;

instead of the the if-clause that works only one-way.

Also, for the users who have JS disabled, I'd suggest to set the initial disabled by JS only. To do so, just move the script behind the <form> and call checkform(); once.

Wordpress 403/404 Errors: You don't have permission to access /wp-admin/themes.php on this server

Just to follow up, problem solved! I mentioned mod_sec settings for my server as being the possible culprit as suggested and they were able to fix this issue. Here's what the tech agent said to tell them when you go to support:

Just let them know you need the rule 340163 whitelisted for domain.com as its hitting a mod_sec rule.

Apparently you will need to do this for each domain that is having the issue, but it works. Thanks for all the suggestions everyone!

Using CSS how to change only the 2nd column of a table

To change only the second column of a table use the following:

General Case:

table td + td{  /* this will go to the 2nd column of a table directly */

background:red

}

Your case:

.countTable table table td + td{ 

background: red

}

Note: this works for all browsers (Modern and old ones) that's why I added my answer to an old question

How do I protect javascript files?

As I said in the comment I left on gion_13 answer before (please read), you really can't. Not with javascript.

If you don't want the code to be available client-side (= stealable without great efforts), my suggestion would be to make use of PHP (ASP,Python,Perl,Ruby,JSP + Java-Servlets) that is processed server-side and only the results of the computation/code execution are served to the user. Or, if you prefer, even Flash or a Java-Applet that let client-side computation/code execution but are compiled and thus harder to reverse-engine (not impossible thus).

Just my 2 cents.

"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte

Open your file with Notepad++, select "Encoding" or "Encodage" menu to identify or to convert from ANSI to UTF-8 or the ISO 8859-1 code page.

Upload files with FTP using PowerShell

Easiest way

The most trivial way to upload a binary file to an FTP server using PowerShell is using WebClient.UploadFile:

$client = New-Object System.Net.WebClient
$client.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$client.UploadFile("ftp://ftp.example.com/remote/path/file.zip", "C:\local\path\file.zip")

Advanced options

If you need a greater control, that WebClient does not offer (like TLS/SSL encryption, etc), use FtpWebRequest. Easy way is to just copy a FileStream to FTP stream using Stream.CopyTo:

$request = [Net.WebRequest]::Create("ftp://ftp.example.com/remote/path/file.zip")
$request.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile 

$fileStream = [System.IO.File]::OpenRead("C:\local\path\file.zip")
$ftpStream = $request.GetRequestStream()

$fileStream.CopyTo($ftpStream)

$ftpStream.Dispose()
$fileStream.Dispose()

Progress monitoring

If you need to monitor an upload progress, you have to copy the contents by chunks yourself:

$request = [Net.WebRequest]::Create("ftp://ftp.example.com/remote/path/file.zip")
$request.Credentials = New-Object System.Net.NetworkCredential("username", "password")
$request.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile 

$fileStream = [System.IO.File]::OpenRead("C:\local\path\file.zip")
$ftpStream = $request.GetRequestStream()

$buffer = New-Object Byte[] 10240
while (($read = $fileStream.Read($buffer, 0, $buffer.Length)) -gt 0)
{
    $ftpStream.Write($buffer, 0, $read)
    $pct = ($fileStream.Position / $fileStream.Length)
    Write-Progress `
        -Activity "Uploading" -Status ("{0:P0} complete:" -f $pct) `
        -PercentComplete ($pct * 100)
}

$ftpStream.Dispose()
$fileStream.Dispose()

Uploading folder

If you want to upload all files from a folder, see
PowerShell Script to upload an entire folder to FTP

How can I list the contents of a directory in Python?

os.walk can be used if you need recursion:

import os
start_path = '.' # current directory
for path,dirs,files in os.walk(start_path):
    for filename in files:
        print os.path.join(path,filename)

What's "P=NP?", and why is it such a famous question?

To give the simplest answer I can think of:

Suppose we have a problem that takes a certain number of inputs, and has various potential solutions, which may or may not solve the problem for given inputs. A logic puzzle in a puzzle magazine would be a good example: the inputs are the conditions ("George doesn't live in the blue or green house"), and the potential solution is a list of statements ("George lives in the yellow house, grows peas, and owns the dog"). A famous example is the Traveling Salesman problem: given a list of cities, and the times to get from any city to any other, and a time limit, a potential solution would be a list of cities in the order the salesman visits them, and it would work if the sum of the travel times was less than the time limit.

Such a problem is in NP if we can efficiently check a potential solution to see if it works. For example, given a list of cities for the salesman to visit in order, we can add up the times for each trip between cities, and easily see if it's under the time limit. A problem is in P if we can efficiently find a solution if one exists.

(Efficiently, here, has a precise mathematical meaning. Practically, it means that large problems aren't unreasonably difficult to solve. When searching for a possible solution, an inefficient way would be to list all possible potential solutions, or something close to that, while an efficient way would require searching a much more limited set.)

Therefore, the P=NP problem can be expressed this way: If you can verify a solution for a problem of the sort described above efficiently, can you find a solution (or prove there is none) efficiently? The obvious answer is "Why should you be able to?", and that's pretty much where the matter stands today. Nobody has been able to prove it one way or another, and that bothers a lot of mathematicians and computer scientists. That's why anybody who can prove the solution is up for a million dollars from the Claypool Foundation.

We generally assume that P does not equal NP, that there is no general way to find solutions. If it turned out that P=NP, a lot of things would change. For example, cryptography would become impossible, and with it any sort of privacy or verifiability on the Internet. After all, we can efficiently take the encrypted text and the key and produce the original text, so if P=NP we could efficiently find the key without knowing it beforehand. Password cracking would become trivial. On the other hand, there's whole classes of planning problems and resource allocation problems that we could solve effectively.

You may have heard the description NP-complete. An NP-complete problem is one that is NP (of course), and has this interesting property: if it is in P, every NP problem is, and so P=NP. If you could find a way to efficiently solve the Traveling Salesman problem, or logic puzzles from puzzle magazines, you could efficiently solve anything in NP. An NP-complete problem is, in a way, the hardest sort of NP problem.

So, if you can find an efficient general solution technique for any NP-complete problem, or prove that no such exists, fame and fortune are yours.

Simple and fast method to compare images for similarity

If you can be sure to have precise alignment of your template (the icon) to the testing region, then any old sum of pixel differences will work.

If the alignment is only going to be a tiny bit off, then you can low-pass both images with cv::GaussianBlur before finding the sum of pixel differences.

If the quality of the alignment is potentially poor then I would recommend either a Histogram of Oriented Gradients or one of OpenCV's convenient keypoint detection/descriptor algorithms (such as SIFT or SURF).

Remove row lines in twitter bootstrap

Got the same question from a friend. My suggestion which does not require !Important looks like this: I add a custom class "no-border" which can be added to the bootstrap table.

.table.no-border tr td, .table.no-border tr th {
  border-width: 0;
}

You can see my go at a solution here

Renaming Column Names in Pandas Groupby function

For the first question I think answer would be:

<your DataFrame>.rename(columns={'count':'Total_Numbers'})

or

<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']

As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:

Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]

How can I copy a file from a remote server to using Putty in Windows?

It worked using PSCP. Instructions:

  1. Download PSCP.EXE from Putty download page
  2. Open command prompt and type set PATH=<path to the pscp.exe file>
  3. In command prompt point to the location of the pscp.exe using cd command
  4. Type pscp
  5. use the following command to copy file form remote server to the local system

    pscp [options] [user@]host:source target
    

So to copy the file /etc/hosts from the server example.com as user fred to the file c:\temp\example-hosts.txt, you would type:

pscp [email protected]:/etc/hosts c:\temp\example-hosts.txt

Unable to open debugger port in IntelliJ IDEA

I came in this scenario and as the above answers I tried to change the port like Edit Configuration -> Startup/Connection -> debug -> change the Port but it didn't solve my problem cause I was running my application in debug mode so once try to run the application as normal without debug. it solved my problem!

Which method performs better: .Any() vs .Count() > 0?

The exact details differ a bit in .NET Framework vs .NET Core, but it also somewhat depends on what you're doing: if you're using an ICollection or ICollection<T> type (such as with List<T>) there is a .Count property that's cheap to access, whereas other types might require enumeration.

TL;DR:

Use .Count > 0 if the property exists, and otherwise .Any().

Using .Count() > 0 is never the best option, and in some cases could be dramatically slower.

This applies to both .NET Framework and .NET Core.


Now we can dive into the details..

Lists and Collections

Let's start with a very common case: using List<T> (which is also ICollection<T>).

The .Count property is implemented as:

    private int _size;

    public int Count {
        get {
            Contract.Ensures(Contract.Result<int>() >= 0);
            return _size; 
        }
    }

What this is saying is _size is maintained by Add(),Remove() etc, and since it's just accessing a field this is an extremely cheap operation -- we don't need to iterate over values.

ICollection and ICollection<T> both have .Count and most types that implement them are likely to do so in a similar way.

Other IEnumerables

Any other IEnumerable types that aren't also ICollection require starting enumeration to determine if they're empty or not. The key factor affecting performance is if we end up enumerating a single item (ideal) or the entire collection (relatively expensive).

If the collection is actually causing I/O such as by reading from a database or disk, this could be a big performance hit.


.NET Framework .Any()

In .NET Framework (4.8), the Any() implementation is:

public static bool Any<TSource>(this IEnumerable<TSource> source) {
    if (source == null) throw Error.ArgumentNull("source");
    using (IEnumerator<TSource> e = source.GetEnumerator()) {
        if (e.MoveNext()) return true;
    }
    return false;
}

This means no matter what, it's going to get a new enumerator object and try iterating once. This is more expensive than calling the List<T>.Count property, but at least it's not iterating the entire list.

.NET Framework .Count()

In .NET Framework (4.8), the Count() implementation is (basically):

public static int Count<TSource>(this IEnumerable<TSource> source)
{
    ICollection<TSource> collection = source as ICollection<TSource>;
    if (collection != null)
    { 
        return collection.Count;
    }
    int num = 0;
    using (IEnumerator<TSource> enumerator = source.GetEnumerator())
    {
        while (enumerator.MoveNext())
        {
            num = checked(num + 1);
        }
        return num;
    }
}

If available, ICollection.Count is used, but otherwise the collection is enumerated.


.NET Core .Any()

The LINQ Any() implementation in .NET Core is much smarter. You can see the complete source here but the relevant bits to this discussion:

    public static bool Any<TSource>(this IEnumerable<TSource> source)
    {
        //..snip..
        
        if (source is ICollection<TSource> collectionoft)
        {
            return collectionoft.Count != 0;
        }
        
        //..snip..

        using (IEnumerator<TSource> e = source.GetEnumerator())
        {
            return e.MoveNext();
        }
    }

Because a List<T> is an ICollection<T>, this will call the Count property (and though it calls another method, there's no extra allocations).

.NET Core .Count()

The .NET Core implementation (source) is basically the same as .NET Framework (see above), and so it will use ICollection.Count if available, and otherwise enumerates the collection.


Summary

.NET Framework

  • With ICollection:

    • .Count > 0 is best
    • .Count() > 0 is fine, but ultimately just calls ICollection.Count
    • .Any() is going to be slower, as it enumerates a single item
  • With non-ICollection (no .Count property)

    • .Any() is best, as it only enumerates a single item
    • .Count() > 0 is bad as it causes complete enumeration

.NET Core

  • .Count > 0 is best, if available (ICollection)
  • .Any() is fine, and will either do ICollection.Count > 0 or enumerate a single item
  • .Count() > 0 is bad as it causes complete enumeration

anaconda - graphviz - can't import after installation

Check if tensorflow is activated in your terminal

first deactivate it using

conda deactivate

then use the command

conda install python-graphviz

and then install

conda install graphviz

this is solution for UBUNTU USERS :) CHEERS :)

How to use greater than operator with date?

Adding this since this was not mentioned.

SELECT * FROM `la_schedule` WHERE date(start_date) > date('2012-11-18');

Because that's what actually works for me. Adding date() function on both comparison values.

How often should Oracle database statistics be run?

In the case of a data warehouse-type system you can consider collecting no statistics at all, and relying on dynamic sampling (setting optimizer_dynamic_sampling to level 2 or above).

Where does MAMP keep its php.ini?

Just run the following command from your terminal, it will show you your Loaded Configuration File easiest way I have ever found.

php --ini

How to retrieve the current version of a MySQL database management system (DBMS)?

I found a easy way to get that.

Example: Unix command(this way you don't need 2 commands.),

$ mysql -u root -p -e 'SHOW VARIABLES LIKE "%version%";'

Sample outputs:

+-------------------------+-------------------------+
| Variable_name           | Value                   |
+-------------------------+-------------------------+
| innodb_version          | 5.5.49                  |
| protocol_version        | 10                      |
| slave_type_conversions  |                         |
| version                 | 5.5.49-0ubuntu0.14.04.1 |
| version_comment         | (Ubuntu)                |
| version_compile_machine | x86_64                  |
| version_compile_os      | debian-linux-gnu        |
+-------------------------+-------------------------+

In above case mysql version is 5.5.49.

Please find this useful reference.

Converting Date and Time To Unix Timestamp

Using a date picker to get date and a time picker I get two variables, this is how I put them together in unixtime format and then pull them out...

let datetime = oDdate+' '+oDtime;
let unixtime = Date.parse(datetime)/1000;
console.log('unixtime:',unixtime);

to prove it:

let milliseconds = unixtime * 1000;
dateObject = new Date(milliseconds);
console.log('dateObject:',dateObject);

enjoy!

jQuery: get the file name selected from <input type="file" />

//get file input
var $el = $('input[type=file]');
//set the next siblings (the span) text to the input value 
$el.next().text( $el.val() );

What is ToString("N0") format?

Checkout the following article on MSDN about examples of the N format. This is also covered in the Standard Numeric Format Strings article.

Relevant excerpts:

//       Formatting of 1054.32179:
//          N:                     1,054.32 
//          N0:                    1,054 
//          N1:                    1,054.3 
//          N2:                    1,054.32 
//          N3:                    1,054.322 

When precision specifier controls the number of fractional digits in the result string, the result string reflects a number that is rounded to a representable result nearest to the infinitely precise result. If there are two equally near representable results:

  • On the .NET Framework and .NET Core up to .NET Core 2.0, the runtime selects the result with the greater least significant digit (that is, using MidpointRounding.AwayFromZero).
  • On .NET Core 2.1 and later, the runtime selects the result with an even least significant digit (that is, using MidpointRounding.ToEven).

The endpoint reference (EPR) for the Operation not found is

Late answer but:

I see you do a GET - should be a POST ?

How to call execl() in C with the proper arguments?

If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:

system("The same thing you type into console");

Matching special characters and letters in regex

let pattern = /^(?=.*[0-9])(?=.*[!@#$%^&*])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9!@#$%^&*]{6,16}$/;

//following will give you the result as true(if the password contains Capital, small letter, number and special character) or false based on the string format

let reee =pattern .test("helLo123@");   //true as it contains all the above

Importing Excel files into R, xlsx or xls

You may also want to try the XLConnect package. I've had better luck with it than xlsx (plus it can read .xls files too).

library(XLConnect)
theData <- readWorksheet(loadWorkbook("C:/AB_DNA_Tag_Numbers.xlsx"),sheet=1)

also, if you are having trouble with your file not being found, try selecting it with file.choose().

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

So try uninstalling all other versions other than the one you need, then set the JAVA_HOMEpath variable for that JDK remaining, and you're done.

That's worked for me, I have two JDK (version 8 & 11) installed on my local mac, that causes the issue, for uninstalling, I followed these two steps:

  • cd /Library/Java/JavaVirtualMachines
  • rm -rf openjdk-11.0.1.jdk

CSS3 transitions inside jQuery .css()

Your code can get messy fast when dealing with CSS3 transitions. I would recommend using a plugin such as jQuery Transit that handles the complexity of CSS3 animations/transitions.

Moreover, the plugin uses webkit-transform rather than webkit-transition, which allows for mobile devices to use hardware acceleration in order to give your web apps that native look and feel when the animations occur.

JS Fiddle Live Demo

Javascript:

$("#startTransition").on("click", function()
{

    if( $(".boxOne").is(":visible")) 
    {
        $(".boxOne").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxOne").hide(); });
        $(".boxTwo").css({ x: '100%' });
        $(".boxTwo").show().transition({ x: '0%', opacity: 1.0 });
        return;        
    }

    $(".boxTwo").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxTwo").hide(); });
    $(".boxOne").css({ x: '100%' });
    $(".boxOne").show().transition({ x: '0%', opacity: 1.0 });

});

Most of the hard work of getting cross-browser compatibility is done for you as well and it works like a charm on mobile devices.

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

Differences between Hashtable and Dictionary

Dictionary:

  • Dictionary returns error if we try to find a key which does not exist.
  • Dictionary faster than a Hashtable because there is no boxing and unboxing.
  • Dictionary is a generic type which means we can use it with any data type.

Hashtable:

  • Hashtable returns null if we try to find a key which does not exist.
  • Hashtable slower than dictionary because it requires boxing and unboxing.
  • Hashtable is not a generic type,

Convert string to datetime

Keep it simple with new Date(string). This should do it...

const s = '01-01-1970 00:03:44';
const d = new Date(s);
console.log(d); // ---> Thu Jan 01 1970 00:03:44 GMT-0500 (Eastern Standard Time)

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date


EDIT: "Code Different" left a valuable comment that MDN no longer recommends using Date as a constructor like this due to browser differences. While the code above works fine in Chrome (v87.0.x) and Edge (v87.0.x), it gives an "Invalid Date" error in Firefox (v84.0.2).

One way to work around this is to make sure your string is in the more universal format of YYYY-MM-DD (obligatory xkcd), e.g., const s = '1970-01-01 00:03:44';, which seems to work in the three major browsers, but this doesn't exactly answer the original question.

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

Pandas magic at work. All logic is out.

The error message "ValueError: If using all scalar values, you must pass an index" Says you must pass an index.

This does not necessarily mean passing an index makes pandas do what you want it to do

When you pass an index, pandas will treat your dictionary keys as column names and the values as what the column should contain for each of the values in the index.

a = 2
b = 3
df2 = pd.DataFrame({'A':a,'B':b}, index=[1])

    A   B
1   2   3

Passing a larger index:

df2 = pd.DataFrame({'A':a,'B':b}, index=[1, 2, 3, 4])

    A   B
1   2   3
2   2   3
3   2   3
4   2   3

An index is usually automatically generated by a dataframe when none is given. However, pandas does not know how many rows of 2 and 3 you want. You can however be more explicit about it

df2 = pd.DataFrame({'A':[a]*4,'B':[b]*4})
df2

    A   B
0   2   3
1   2   3
2   2   3
3   2   3

The default index is 0 based though.

I would recommend always passing a dictionary of lists to the dataframe constructor when creating dataframes. It's easier to read for other developers. Pandas has a lot of caveats, don't make other developers have to experts in all of them in order to read your code.

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

You want your if check to be:

{% if not loop.last %}
    ,
{% endif %}

Note that you can also shorten the code by using If Expression:

{{ ", " if not loop.last else "" }}

How to see if an object is an array without using reflection?

There is no subtyping relationship between arrays of primitive type, or between an array of a primitive type and array of a reference type. See JLS 4.10.3.

Therefore, the following is incorrect as a test to see if obj is an array of any kind:

// INCORRECT!
public boolean isArray(final Object obj) {
    return obj instanceof Object[];
}

Specifically, it doesn't work if obj is 1-D array of primitives. (It does work for primitive arrays with higher dimensions though, because all array types are subtypes of Object. But it is moot in this case.)

I use Google GWT so I am not allowed to use reflection :(

The best solution (to the isArray array part of the question) depends on what counts as "using reflection".

  • In GWT, calling obj.getClass().isArray() does not count as using reflection1, so that is the best solution.

  • Otherwise, the best way of figuring out whether an object has an array type is to use a sequence of instanceof expressions.

    public boolean isArray(final Object obj) {
        return obj instanceof Object[] || obj instanceof boolean[] ||
           obj instanceof byte[] || obj instanceof short[] ||
           obj instanceof char[] || obj instanceof int[] ||
           obj instanceof long[] || obj instanceof float[] ||
           obj instanceof double[];
    }
    
  • You could also try messing around with the name of the object's class as follows, but the call to obj.getClass() is bordering on reflection.

    public boolean isArray(final Object obj) {
        return obj.getClass().toString().charAt(0) == '[';
    }
    

1 - More precisely, the Class.isArray method is listed as supported by GWT in this page.

How to determine if a list of polygon points are in clockwise order?

This is my solution using the explanations in the other answers:

def segments(poly):
    """A sequence of (x,y) numeric coordinates pairs """
    return zip(poly, poly[1:] + [poly[0]])

def check_clockwise(poly):
    clockwise = False
    if (sum(x0*y1 - x1*y0 for ((x0, y0), (x1, y1)) in segments(poly))) < 0:
        clockwise = not clockwise
    return clockwise

poly = [(2,2),(6,2),(6,6),(2,6)]
check_clockwise(poly)
False

poly = [(2, 6), (6, 6), (6, 2), (2, 2)]
check_clockwise(poly)
True

"unadd" a file to svn before commit

Use svn revert --recursive folder_name


Warning

svn revert is inherently dangerous, since its entire purpose is to throw away data — namely, your uncommitted changes. Once you've reverted, Subversion provides no way to get back those uncommitted changes.

http://svnbook.red-bean.com/en/1.7/svn.ref.svn.c.revert.html

How to change the size of the radio button using CSS?

You can control radio button's size with css style:

style="height:35px; width:35px;"

This directly controls the radio button size.

<input type="radio" name="radio" value="value" style="height:35px; width:35px; vertical-align: middle;">

Difference between Parameters.Add(string, object) and Parameters.AddWithValue

There is no difference in terms of functionality. In fact, both do this:

return this.Add(new SqlParameter(parameterName, value));

The reason they deprecated the old one in favor of AddWithValue is to add additional clarity, as well as because the second parameter is object, which makes it not immediately obvious to some people which overload of Add was being called, and they resulted in wildly different behavior.

Take a look at this example:

 SqlCommand command = new SqlCommand();
 command.Parameters.Add("@name", 0);

At first glance, it looks like it is calling the Add(string name, object value) overload, but it isn't. It's calling the Add(string name, SqlDbType type) overload! This is because 0 is implicitly convertible to enum types. So these two lines:

 command.Parameters.Add("@name", 0);

and

 command.Parameters.Add("@name", 1);

Actually result in two different methods being called. 1 is not convertible to an enum implicitly, so it chooses the object overload. With 0, it chooses the enum overload.

How do I format a number to a dollar amount in PHP

PHP also has money_format().

Here's an example:

echo money_format('$%i', 3.4); // echos '$3.40'

This function actually has tons of options, go to the documentation I linked to to see them.

Note: money_format is undefined in Windows.


UPDATE: Via the PHP manual: https://www.php.net/manual/en/function.money-format.php

WARNING: This function [money_format] has been DEPRECATED as of PHP 7.4.0. Relying on this function is highly discouraged.

Instead, look into NumberFormatter::formatCurrency.

    $number = "123.45";
    $formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
    return $formatter->formatCurrency($number, 'USD');

How to access a preexisting collection with Mongoose?

Something else that was not obvious, to me at least, was that the when using Mongoose's third parameter to avoid replacing the actual collection with a new one with the same name, the new Schema(...) is actually only a placeholder, and doesn't interfere with the exisitng schema so

var User = mongoose.model('User', new Schema({ url: String, text: String, id: Number}, { collection : 'users' }));   // collection name;
User.find({}, function(err, data) { console.log(err, data, data.length);});

works fine and returns all fields - even if the actual (remote) Schema contains none of these fields. Mongoose will still want it as new Schema(...), and a variable almost certainly won't hack it.

shorthand If Statements: C#

Recently, I really enjoy shorthand if else statements as a swtich case replacement. In my opinion, this is better in read and take less place. Just take a look:

var redirectUrl =
      status == LoginStatusEnum.Success ? "/SecretPage"
    : status == LoginStatusEnum.Failure ? "/LoginFailed"
    : status == LoginStatusEnum.Sms ? "/2-StepSms"
    : status == LoginStatusEnum.EmailNotConfirmed ? "/EmailNotConfirmed"
    : "/404-Error";

instead of

string redirectUrl;
switch (status)
{
    case LoginStatusEnum.Success:
        redirectUrl = "/SecretPage";
        break;
    case LoginStatusEnum.Failure:
        redirectUrl = "/LoginFailed";
        break;
    case LoginStatusEnum.Sms:
        redirectUrl = "/2-StepSms";
        break;
    case LoginStatusEnum.EmailNotConfirmed:
        redirectUrl = "/EmailNotConfirmed";
        break;
    default:
        redirectUrl = "/404-Error";
        break;
}

How to programmatically modify WCF app.config endpoint address setting?

I think what you want is to swap out at runtime a version of your config file, if so create a copy of your config file (also give it the relevant extension like .Debug or .Release) that has the correct addresses (which gives you a debug version and a runtime version ) and create a postbuild step that copies the correct file depending on the build type.

Here is an example of a postbuild event that I've used in the past which overrides the output file with the correct version (debug/runtime)

copy "$(ProjectDir)ServiceReferences.ClientConfig.$(ConfigurationName)" "$(ProjectDir)ServiceReferences.ClientConfig" /Y

where : $(ProjectDir) is the project directory where the config files are located $(ConfigurationName) is the active configuration build type

EDIT: Please see Marc's answer for a detailed explanation on how to do this programmatically.

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

Difference between application/x-javascript and text/javascript content types

Use type="application/javascript"

In case of HTML5, the type attribute is obsolete, you may remove it. Note: that it defaults to "text/javascript" according to w3.org, so I would suggest to add the "application/javascript" instead of removing it.

http://www.w3.org/TR/html5/scripting-1.html#attr-script-type
The type attribute gives the language of the script or format of the data. If the attribute is present, its value must be a valid MIME type. The charset parameter must not be specified. The default, which is used if the attribute is absent, is "text/javascript".

Use "application/javascript", because "text/javascript" is obsolete:

RFC 4329: http://www.rfc-editor.org/rfc/rfc4329.txt

  1. Deployed Scripting Media Types and Compatibility

    Various unregistered media types have been used in an ad-hoc fashion to label and exchange programs written in ECMAScript and JavaScript. These include:

    +-----------------------------------------------------+ | text/javascript | text/ecmascript | | text/javascript1.0 | text/javascript1.1 | | text/javascript1.2 | text/javascript1.3 | | text/javascript1.4 | text/javascript1.5 | | text/jscript | text/livescript | | text/x-javascript | text/x-ecmascript | | application/x-javascript | application/x-ecmascript | | application/javascript | application/ecmascript | +-----------------------------------------------------+

Use of the "text" top-level type for this kind of content is known to be problematic. This document thus defines text/javascript and text/
ecmascript but marks them as "obsolete". Use of experimental and
unregistered media types, as listed in part above, is discouraged.
The media types,

  * application/javascript
  * application/ecmascript

which are also defined in this document, are intended for common use and should be used instead.

This document defines equivalent processing requirements for the
types text/javascript, text/ecmascript, and application/javascript.
Use of and support for the media type application/ecmascript is
considerably less widespread than for other media types defined in
this document. Using that to its advantage, this document defines
stricter processing rules for this type to foster more interoperable
processing.

x-javascript is experimental, don't use it.

how to call a function from another function in Jquery

wrap you shared code into another function:

<script>
  function myFun () {
      //do something
  }

  $(document).ready(function(){
    //Load City by State
    $(document).on('change', '#billing_state_id', function() {
       myFun ();
    });   
    $(document).on('click', '#click_me', function() {
       //do something
       myFun();
    });   
  });
</script>

How do I use WebRequest to access an SSL encrypted site using https?

This link will be of interest to you: http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx

For http connections, the WebRequest and WebResponse classes use SSL to communicate with web hosts that support SSL. The decision to use SSL is made by the WebRequest class, based on the URI it is given. If the URI begins with "https:", SSL is used; if the URI begins with "http:", an unencrypted connection is used.

Install apps silently, with granted INSTALL_PACKAGES permission

Your first bet is to look into Android's native PackageInstaller. I would recommend modifying that app the way you like, or just extract required functionality.


Specifically, if you look into PackageInstallerActivity and its method onClickListener:

 public void onClick(View v) {
    if(v == mOk) {
        // Start subactivity to actually install the application
        Intent newIntent = new Intent();
        ...
        newIntent.setClass(this, InstallAppProgress.class);
        ...
        startActivity(newIntent);
        finish();
    } else if(v == mCancel) {
        // Cancel and finish
        finish();
    }
}

Then you'll notice that actual installer is located in InstallAppProgress class. Inspecting that class you'll find that initView is the core installer function, and the final thing it does is call to PackageManager's installPackage function:

public void initView() {
...
pm.installPackage(mPackageURI, observer, installFlags, installerPackageName);
}

Next step is to inspect PackageManager, which is abstract class. You'll find installPackage(...) function there. The bad news is that it's marked with @hide. This means it's not directly available (you won't be able to compile with call to this method).

 /**
  * @hide
  * ....
  */
  public abstract void installPackage(Uri packageURI,
             IPackageInstallObserver observer, 
             int flags,String installerPackageName); 

But you will be able to access this methods via reflection.

If you are interested in how PackageManager's installPackage function is implemented, take a look at PackageManagerService.

Summary

You'll need to get package manager object via Context's getPackageManager(). Then you will call installPackage function via reflection.

Removing header column from pandas dataframe

How to get rid of a header(first row) and an index(first column).

To write to CSV file:

df = pandas.DataFrame(your_array)
df.to_csv('your_array.csv', header=False, index=False)

To read from CSV file:

df = pandas.read_csv('your_array.csv')
a = df.values

If you want to read a CSV file that doesn't contain a header, pass additional parameter header:

df = pandas.read_csv('your_array.csv', header=None)

How to get character for a given ascii value

Simply Try this:

int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("data is: {0}", Convert.ToChar(n));

HTML5 form validation pattern alphanumeric with spaces?

How about adding a space in the pattern attribute like pattern="[a-zA-Z0-9 ]+". If you want to support any kind of space try pattern="[a-zA-Z0-9\s]+"

Split and join C# string

You can use string.Split and string.Join:

string theString = "Some Very Large String Here";
var array = theString.Split(' ');
string firstElem = array.First();
string restOfArray = string.Join(" ", array.Skip(1));

If you know you always only want to split off the first element, you can use:

var array = theString.Split(' ', 2);

This makes it so you don't have to join:

string restOfArray = array[1];

What is the difference between __str__ and __repr__?

Every object inherits __repr__ from the base class that all objects created.

class Person:
     pass

p=Person()

if you call repr(p) you will get this as default:

 <__main__.Person object at 0x7fb2604f03a0>

But if you call str(p) you will get the same output. it is because when __str__ does not exist, Python calls __repr__

Let's implement our own __str__

class Person:
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def __repr__(self):
        print("__repr__ called")
        return f"Person(name='{self.name}',age={self.age})"

p=Person("ali",20)

print(p) and str(p)will return

 __repr__ called
     Person(name='ali',age=20)

let's add __str__()

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
    def __repr__(self):
        print('__repr__ called')
        return f"Person(name='{self.name}, age=self.age')"
    
    def __str__(self):
        print('__str__ called')
        return self.name

p=Person("ali",20)

if we call print(p) and str(p), it will call __str__() so it will return

__str__ called
ali

repr(p) will return

repr called "Person(name='ali, age=self.age')"

Let's omit __repr__ and just implement __str__.

class Person:
def __init__(self, name, age):
    self.name = name
    self.age = age

def __str__(self):
    print('__str__ called')
    return self.name

p=Person('ali',20)

print(p) will look for the __str__ and will return:

__str__ called
ali

NOTE= if we had __repr__ and __str__ defined, f'name is {p}' would call __str__

git rebase fatal: Needed a single revision

Check that you spelled the branch name correctly. I was rebasing a story branch (i.e. branch_name) and forgot the story part. (i.e. story/branch_name) and then git spit this error at me which didn't make much sense in this context.

input file appears to be a text format dump. Please use psql

In order to create a backup using pg_dump that is compatible with pg_restore you must use the --format=custom / -Fc when creating your dump.

From the docs:

Output a custom-format archive suitable for input into pg_restore.

So your pg_dump command might look like:

pg_dump --file /tmp/db.dump --format=custom --host localhost --dbname my-source-database --username my-username --password

And your pg_restore command:

pg_restore --verbose --clean --no-acl --no-owner --host localhost --dbname my-destination-database /tmp/db.dump

Completely cancel a rebase

You are lucky that you didn't complete the rebase, so you can still do git rebase --abort. If you had completed the rebase (it rewrites history), things would have been much more complex. Consider tagging the tips of branches before doing potentially damaging operations (particularly history rewriting), that way you can rewind if something blows up.

Output data from all columns in a dataframe in pandas

I know this is an old question, but I have just had a similar problem and I think what I did would work for you too.

I used the to_csv() method and wrote to stdout:

import sys

paramdata.to_csv(sys.stdout)

This should dump the whole dataframe whether it's nicely-printable or not, and you can use the to_csv parameters to configure column separators, whether the index is printed, etc.

Edit: It is now possible to use None as the target for .to_csv() with similar effect, which is arguably a lot nicer:

paramdata.to_csv(None)

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:

Delivery -> Package (One -> Many)

CREATE TABLE Delivery(
    Id INT IDENTITY PRIMARY KEY,
    NoteNumber NVARCHAR(255) NOT NULL
)

CREATE TABLE Package(
    Id INT IDENTITY PRIMARY KEY,
    Status INT NOT NULL DEFAULT 0,
    Delivery_Id INT NOT NULL,
    CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
)

The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).

So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.

how to fix EXE4J_JAVA_HOME, No JVM could be found on your system error?

BH's answer of installing Java 6u45 was very close... still got the popup on reboot...BUT after uninstalling Java 6u45, rebooted, no warning! Thank you BH! Then installed the latest version, 8u151-i586, rebooted no warning.

I added lines in PATH as above, didn't do anything.

My system: Windows 7, 64 bit. Warning was for No JVM, 32 bit Java not found. Yes, I could have installed the 64 bit version, but 32bit is more compatible with all programs.

How do I create a datetime in Python from milliseconds?

Just convert it to timestamp

datetime.datetime.fromtimestamp(ms/1000.0)

Which command in VBA can count the number of characters in a string variable?

Try this:

word = "habit"
findchar = 'b"
replacechar = ""
charactercount = len(word) - len(replace(word,findchar,replacechar))

How to include header files in GCC search path?

Try gcc -c -I/home/me/development/skia sample.c.

How can I quantify difference between two images?

I had a similar problem at work, I was rewriting our image transform endpoint and I wanted to check that the new version was producing the same or nearly the same output as the old version. So I wrote this:

https://github.com/nicolashahn/diffimg

Which operates on images of the same size, and at a per-pixel level, measures the difference in values at each channel: R, G, B(, A), takes the average difference of those channels, and then averages the difference over all pixels, and returns a ratio.

For example, with a 10x10 image of white pixels, and the same image but one pixel has changed to red, the difference at that pixel is 1/3 or 0.33... (RGB 0,0,0 vs 255,0,0) and at all other pixels is 0. With 100 pixels total, 0.33.../100 = a ~0.33% difference in image.

I believe this would work perfectly for OP's project (I realize this is a very old post now, but posting for future StackOverflowers who also want to compare images in python).

Escaping HTML strings with jQuery

Here is a clean, clear JavaScript function. It will escape text such as "a few < many" into "a few &lt; many".

function escapeHtmlEntities (str) {
  if (typeof jQuery !== 'undefined') {
    // Create an empty div to use as a container,
    // then put the raw text in and get the HTML
    // equivalent out.
    return jQuery('<div/>').text(str).html();
  }

  // No jQuery, so use string replace.
  return str
    .replace(/&/g, '&amp;')
    .replace(/>/g, '&gt;')
    .replace(/</g, '&lt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;');
}

Java Try Catch Finally blocks without Catch

If any of the code in the try block can throw a checked exception, it has to appear in the throws clause of the method signature. If an unchecked exception is thrown, it's bubbled out of the method.

The finally block is always executed, whether an exception is thrown or not.

How do I align spans or divs horizontally?

you can do:

<div style="float: left;"></div>

or

<div style="display: inline;"></div>

Either one will cause the divs to tile horizontally.

How to decide when to use Node.js?

My piece: nodejs is great for making real time systems like analytics, chat-apps, apis, ad servers, etc. Hell, I made my first chat app using nodejs and socket.io under 2 hours and that too during exam week!

Edit

Its been several years since I have started using nodejs and I have used it in making many different things including static file servers, simple analytics, chat apps and much more. This is my take on when to use nodejs

When to use

When making system which put emphasis on concurrency and speed.

  • Sockets only servers like chat apps, irc apps, etc.
  • Social networks which put emphasis on realtime resources like geolocation, video stream, audio stream, etc.
  • Handling small chunks of data really fast like an analytics webapp.
  • As exposing a REST only api.

When not to use

Its a very versatile webserver so you can use it wherever you want but probably not these places.

  • Simple blogs and static sites.
  • Just as a static file server.

Keep in mind that I am just nitpicking. For static file servers, apache is better mainly because it is widely available. The nodejs community has grown larger and more mature over the years and it is safe to say nodejs can be used just about everywhere if you have your own choice of hosting.

Sending HTTP Post request with SOAP action using org.apache.http

The simplest way to identify what needs to be set on the soap action when invoking WCF service through a java client would to load the wsdl, go to the operation name matching the service. From there pick up the action URI and set it in the soap action header. You are done.

eg: from wsdl

<wsdl:operation name="MyOperation">
  <wsdl:input wsaw:Action="http://tempuri.org/IMyService/MyOperation" message="tns:IMyService_MyOperation_InputMessage" />
  <wsdl:output wsaw:Action="http://tempuri.org/IMyService/MyServiceResponse" message="tns:IMyService_MyOperation_OutputMessage" />

Now in the java code we should set the soap action as the Action URI.

//The rest of the httpPost object properties have not been shown for brevity
string actionURI='http://tempuri.org/IMyService/MyOperation';
httpPost.setHeader( "SOAPAction", actionURI);

Javascript form validation with password confirming

add this to your form:

<form  id="regform" action="insert.php" method="post">

add this to your function:

<script>
    function myFunction() {
        var pass1 = document.getElementById("pass1").value;
        var pass2 = document.getElementById("pass2").value;
        if (pass1 != pass2) {
            //alert("Passwords Do not match");
            document.getElementById("pass1").style.borderColor = "#E34234";
            document.getElementById("pass2").style.borderColor = "#E34234";
        }
        else {
            alert("Passwords Match!!!");
            document.getElementById("regForm").submit();
        }
    }
</script>

Output of git branch in tree like fashion

You can use a tool called gitk.

How to see full absolute path of a symlink

realpath isn't available on all linux flavors, but readlink should be.

readlink -f symlinkName

The above should do the trick.

Alternatively, if you don't have either of the above installed, you can do the following if you have python 2.6 (or later) installed

python -c 'import os.path; print(os.path.realpath("symlinkName"))'

PHP CURL Enable Linux

If it's php 7 on ubuntu, try this

apt-get install php7.0-curl
/etc/init.d/apache2 restart

Editor does not contain a main type

Try 'Update Project'. Once I did this, The Run as Java Application option appeared.

display: inline-block extra margin

You can get a vertical space even though you have NO WHITESPACE whatsoever between your inline-block elements.

For me, this was caused by line-height. The simple fix was:

div.container {
    line-height: 0;
}
div.container > * {
    line-height: normal;
}

how to get login option for phpmyadmin in xampp

Can you set the password to the phpmyadmin here

http://localhost/security/index.php

Regular Expression for matching parentheses

  • You can escape any meta-character by using a backslash, so you can match ( with the pattern \(.
  • Many languages come with a build-in escaping function, for example, .Net's Regex.Escape or Java's Pattern.quote
  • Some flavors support \Q and \E, with literal text between them.
  • Some flavors (VIM, for example) match ( literally, and require \( for capturing groups.

See also: Regular Expression Basic Syntax Reference

AngularJs: How to check for changes in file input fields?

This directive pass the selected files as well:

/**
 *File Input - custom call when the file has changed
 */
.directive('onFileChange', function() {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      var onChangeHandler = scope.$eval(attrs.onFileChange);

      element.bind('change', function() {
        scope.$apply(function() {
          var files = element[0].files;
          if (files) {
            onChangeHandler(files);
          }
        });
      });

    }
  };
});

The HTML, how to use it:

<input type="file" ng-model="file" on-file-change="onFilesSelected">

In my controller:

$scope.onFilesSelected = function(files) {
     console.log("files - " + files);
};

SQL Server® 2016, 2017 and 2019 Express full download

Download the developer edition. There you can choose Express as license when installing.

enter image description here

How do I delete an entity from symfony2

Symfony is smart and knows how to make the find() by itself :

public function deleteGuestAction(Guest $guest)
{
    if (!$guest) {
        throw $this->createNotFoundException('No guest found');
    }

    $em = $this->getDoctrine()->getEntityManager();
    $em->remove($guest);
    $em->flush();

    return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
}

To send the id in your controller, use {{ path('your_route', {'id': guest.id}) }}

Java generics - get class?

Short answer: You can't.

Long answer:

Due to the way generics is implemented in Java, the generic type T is not kept at runtime. Still, you can use a private data member:

public class Foo<T> 
{
    private Class<T> type;

    public Foo(Class<T> type) { this.type = type; } 
}

Usage example:

Foo<Integer> test = new Foo<Integer>(Integer.class);

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

Your Custom AuthenticationProvider class should be annotated with the following:

@Transactional

This will make sure the presence of the hibernate session there as well.

How do I print part of a rendered HTML page in JavaScript?

Along the same lines as some of the suggestions you would need to do at least the following:

  • Load some CSS dynamically through JavaScript
  • Craft some print-specific CSS rules
  • Apply your fancy CSS rules through JavaScript

An example CSS could be as simple as this:

@media print {
  body * {
    display:none;
  }

  body .printable {
    display:block;
  }
}

Your JavaScript would then only need to apply the "printable" class to your target div and it will be the only thing visible (as long as there are no other conflicting CSS rules -- a separate exercise) when printing happens.

<script type="text/javascript">
  function divPrint() {
    // Some logic determines which div should be printed...
    // This example uses div3.
    $("#div3").addClass("printable");
    window.print();
  }
</script>

You may want to optionally remove the class from the target after printing has occurred, and / or remove the dynamically-added CSS after printing has occurred.

Below is a full working example, the only difference is that the print CSS is not loaded dynamically. If you want it to really be unobtrusive then you will need to load the CSS dynamically like in this answer.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Print Portion Example</title>
    <style type="text/css">
      @media print {
        body * {
          display:none;
        }

        body .printable {
          display:block;
        }
      }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  </head>

  <body>
    <h1>Print Section Example</h1>
    <div id="div1">Div 1</div>
    <div id="div2">Div 2</div>
    <div id="div3">Div 3</div>
    <div id="div4">Div 4</div>
    <div id="div5">Div 5</div>
    <div id="div6">Div 6</div>
    <p><input id="btnSubmit" type="submit" value="Print" onclick="divPrint();" /></p>
    <script type="text/javascript">
      function divPrint() {
        // Some logic determines which div should be printed...
        // This example uses div3.
        $("#div3").addClass("printable");
        window.print();
      }
    </script>
  </body>
</html>

How to get current value of RxJS Subject or Observable?

You could store the last emitted value separately from the Observable. Then read it when needed.

let lastValue: number;

const subscription = new Service().start();
subscription
    .subscribe((data) => {
        lastValue = data;
    }
);

React - clearing an input value after form submit

Since you input field is a controlled element, you cannot directly change the input field value without modifying the state.

Also in

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.mainInput.value = "";
  }

this.mainInput doesn't refer the input since mainInput is an id, you need to specify a ref to the input

<input
      ref={(ref) => this.mainInput= ref}
      onChange={this.onHandleChange}
      placeholder="Get current weather..."
      value={this.state.city}
      type="text"
    />

In you current state the best way is to clear the state to clear the input value

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.setState({city: ""});
  }

However if you still for some reason want to keep the value in state even if the form is submitted, you would rather make the input uncontrolled

<input
      id="mainInput"
      onChange={this.onHandleChange}
      placeholder="Get current weather..."
      type="text"
    />

and update the value in state onChange and onSubmit clear the input using ref

 onHandleChange(e) {
    this.setState({
      city: e.target.value
    });
  }

  onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.mainInput.value = "";
  }

Having Said that, I don't see any point in keeping the state unchanged, so the first option should be the way to go.

html select option separator

The disabled option approach seems to look the best and be the best supported. I've also included an example of using the optgroup.

optgroup (this way kinda sucks):

_x000D_
_x000D_
<select>_x000D_
    <optgroup>_x000D_
        <option>First</option>_x000D_
    </optgroup>_x000D_
    <optgroup label="_________">_x000D_
        <option>Second</option>_x000D_
        <option>Third</option>_x000D_
    </optgroup>_x000D_
</select>
_x000D_
_x000D_
_x000D_

disabled option (a bit better):

_x000D_
_x000D_
<select>_x000D_
    <option>First</option>_x000D_
    <option disabled>_________</option>_x000D_
    <option>Second</option>_x000D_
    <option>Third</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

And if you want to be really fancy, use the horizontal unicode box drawing character.
(BEST OPTION!)

_x000D_
_x000D_
<select>_x000D_
    <option>First</option>_x000D_
    <option disabled>----------</option>_x000D_
    <option>Second</option>_x000D_
    <option>Third</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/JFDgH/2/

Using multiple parameters in URL in express

app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
    var data = {
        "fruit": {
            "apple": req.params.fruitName,
            "color": req.params.fruitColor
        }
    }; 

    send.json(data);
});

If that doesn't work, try using console.log(req.params) to see what it is giving you.

How to upload file to server with HTTP POST multipart/form-data?

The below code reads a file, converts it to a byte array and then makes a request to the server.

    public void PostImage()
    {
        HttpClient httpClient = new HttpClient();
        MultipartFormDataContent form = new MultipartFormDataContent();

        byte[] imagebytearraystring = ImageFileToByteArray(@"C:\Users\Downloads\icon.png");
        form.Add(new ByteArrayContent(imagebytearraystring, 0, imagebytearraystring.Count()), "profile_pic", "hello1.jpg");
        HttpResponseMessage response = httpClient.PostAsync("your url", form).Result;

        httpClient.Dispose();
        string sd = response.Content.ReadAsStringAsync().Result;
    }

    private byte[] ImageFileToByteArray(string fullFilePath)
    {
        FileStream fs = File.OpenRead(fullFilePath);
        byte[] bytes = new byte[fs.Length];
        fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
        fs.Close();
        return bytes;
    }

Python conditional assignment operator

(can't comment or I would just do that) I believe the suggestion to check locals above is not quite right. It should be:

foo = foo if 'foo' in locals() or 'foo' in globals() else 'default'

to be correct in all contexts.

However, despite its upvotes, I don't think even that is a good analog to the Ruby operator. Since the Ruby operator allows more than just a simple name on the left:

foo[12] ||= something
foo.bar ||= something

The exception method is probably closest analog.

Get current NSDate in timestamp format

Here's what I use:

NSString * timestamp = [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000];

(times 1000 for milliseconds, otherwise, take that out)

If You're using it all the time, it might be nice to declare a macro

#define TimeStamp [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000]

Then Call it like this:

NSString * timestamp = TimeStamp;

Or as a method:

- (NSString *) timeStamp {
    return [NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970] * 1000];
}

As TimeInterval

- (NSTimeInterval) timeStamp {
    return [[NSDate date] timeIntervalSince1970] * 1000;
}

NOTE:

The 1000 is to convert the timestamp to milliseconds. You can remove this if you prefer your timeInterval in seconds.

Swift

If you'd like a global variable in Swift, you could use this:

var Timestamp: String {
    return "\(NSDate().timeIntervalSince1970 * 1000)"
}

Then, you can call it

println("Timestamp: \(Timestamp)")

Again, the *1000 is for miliseconds, if you'd prefer, you can remove that. If you want to keep it as an NSTimeInterval

var Timestamp: NSTimeInterval {
    return NSDate().timeIntervalSince1970 * 1000
}

Declare these outside of the context of any class and they'll be accessible anywhere.

Nginx: Job for nginx.service failed because the control process exited

May come in handy to check syntax of Nginx's configuration files by running:

nginx -t -c /etc/nginx/nginx.conf

Convert columns to string in Pandas

pandas >= 1.0: It's time to stop using astype(str)!

Prior to pandas 1.0 (well, 0.25 actually) this was the defacto way of declaring a Series/column as as string:

# pandas <= 0.25
# Note to pedants: specifying the type is unnecessary since pandas will 
# automagically infer the type as object
s = pd.Series(['a', 'b', 'c'], dtype=str)
s.dtype
# dtype('O')

From pandas 1.0 onwards, consider using "string" type instead.

# pandas >= 1.0
s = pd.Series(['a', 'b', 'c'], dtype="string")
s.dtype
# StringDtype

Here's why, as quoted by the docs:

  1. You can accidentally store a mixture of strings and non-strings in an object dtype array. It’s better to have a dedicated dtype.

  2. object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text but still object-dtype columns.

  3. When reading code, the contents of an object dtype array is less clear than 'string'.

See also the section on Behavioral Differences between "string" and object.

Extension types (introduced in 0.24 and formalized in 1.0) are closer to pandas than numpy, which is good because numpy types are not powerful enough. For example NumPy does not have any way of representing missing data in integer data (since type(NaN) == float). But pandas can using Nullable Integer columns.


Why should I stop using it?

Accidentally mixing dtypes
The first reason, as outlined in the docs is that you can accidentally store non-text data in object columns.

# pandas <= 0.25
pd.Series(['a', 'b', 1.23])   # whoops, this should have been "1.23"

0       a
1       b
2    1.23
dtype: object

pd.Series(['a', 'b', 1.23]).tolist()
# ['a', 'b', 1.23]   # oops, pandas was storing this as float all the time.
# pandas >= 1.0
pd.Series(['a', 'b', 1.23], dtype="string")

0       a
1       b
2    1.23
dtype: string

pd.Series(['a', 'b', 1.23], dtype="string").tolist()
# ['a', 'b', '1.23']   # it's a string and we just averted some potentially nasty bugs.

Challenging to differentiate strings and other python objects
Another obvious example example is that it's harder to distinguish between "strings" and "objects". Objects are essentially the blanket type for any type that does not support vectorizable operations.

Consider,

# Setup
df = pd.DataFrame({'A': ['a', 'b', 'c'], 'B': [{}, [1, 2, 3], 123]})
df
 
   A          B
0  a         {}
1  b  [1, 2, 3]
2  c        123

Upto pandas 0.25, there was virtually no way to distinguish that "A" and "B" do not have the same type of data.

# pandas <= 0.25  
df.dtypes

A    object
B    object
dtype: object

df.select_dtypes(object)

   A          B
0  a         {}
1  b  [1, 2, 3]
2  c        123

From pandas 1.0, this becomes a lot simpler:

# pandas >= 1.0
# Convenience function I call to help illustrate my point.
df = df.convert_dtypes()
df.dtypes

A    string
B    object
dtype: object

df.select_dtypes("string")

   A
0  a
1  b
2  c

Readability
This is self-explanatory ;-)


OK, so should I stop using it right now?

...No. As of writing this answer (version 1.1), there are no performance benefits but the docs expect future enhancements to significantly improve performance and reduce memory usage for "string" columns as opposed to objects. With that said, however, it's never too early to form good habits!

Basic Python client socket example

Here is the simplest python socket example.

Server side:

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8089))
serversocket.listen(5) # become a server socket, maximum 5 connections

while True:
    connection, address = serversocket.accept()
    buf = connection.recv(64)
    if len(buf) > 0:
        print buf
        break

Client Side:

import socket

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8089))
clientsocket.send('hello')
  • First run the SocketServer.py, and make sure the server is ready to listen/receive sth
  • Then the client send info to the server;
  • After the server received sth, it terminates

What is so bad about singletons?

The Singleton – the anti-pattern! by Mark Radford (Overload Journal #57 – Oct 2003) is a good read about why Singleton is regarded an anti-pattern. The article also discusses two alternatives design approaches for replacing Singleton.

How to check if $? is not equal to zero in unix shell scripting?

You don't need to test if $? is not 0. The shell provides && and || so you can easily branch based on implicit result of that test:

some_command && {
    # executes this block of code,
    # if some_command would result in:  $? -eq 0
} || {
    # executes this block of code,
    # if some_command would result in:  $? -ne 0
}

You can remove either branch, depending on what you want. So if you just want to test for failure (i.e. $? -ne 0):

some_command_returning_nonzero || {
    # executes this block of code when:     $? -ne 0
    # and nothing if the command succeeds:  $? -eq 0
}

However, the code you provided in the question works, as is. I'm confused that you got syntax errors & concluded that $? was a string. It's most likely that the errant code causing the syntax error was not provided with the question. This is especially evident because you claim that no one else's solutions work either. When this happens, you have to re-evaluate your assumptions.

NB: The code above may give confusing results if the code inside the braces returns an error. In that case simply use the if command instead, like this:

if some_command; then
    # executes this block of code,
    # if some_command would result in:  $? -eq 0
else
    # executes this block of code,
    # if some_command would result in:  $? -ne 0
fi

How to resolve "Waiting for Debugger" message?

I used Task Manager to kill adb.exe to solve this problem. Adb.exe will automatically start after being killed.

Killing adb.exe has solved a lot of problems related to debug and emulators for me so far.

Return row of Data Frame based on value in a column - R

Based on the syntax provided

 Select * Where Amount = min(Amount)

You could do using:

 library(sqldf)

Using @Kara Woo's example df

  sqldf("select * from df where Amount in (select min(Amount) from df)")
  #Name Amount
 #1    B    120
 #2    E    120

CSS transition when class removed

In my case i had some problem with opacity transition so this one fix it:

#dropdown {
    transition:.6s opacity;
}
#dropdown.ns {
    opacity:0;
    transition:.6s all;
}
#dropdown.fade {
    opacity:1;
}

Mouse Enter

$('#dropdown').removeClass('ns').addClass('fade');

Mouse Leave

$('#dropdown').addClass('ns').removeClass('fade');

How to add a button dynamically using jquery

the $("body").append(r) statement should be within the test function, also there was misplaced " in the test method

function test() {
    var r=$('<input/>').attr({
        type: "button",
        id: "field",
        value: 'new'
    });
    $("body").append(r);    
}

Demo: Fiddle

Update
In that case try a more jQuery-ish solution

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript">
          jQuery(function($){
              $('#mybutton').one('click', function(){
                  var r=$('<input/>').attr({
                      type: "button",
                      id: "field",
                      value: 'new'
                  });
                  $("body").append(r);   
              })
          })
        </script>
    </head>
    <body>
        <button id="mybutton">Insert after</button> 
    </body>
</html>

Demo: Plunker

Direct method from SQL command text to DataSet

Just finish it up.

string sqlCommand = "SELECT * FROM TABLE";
string connectionString = "blahblah";

DataSet ds = GetDataSet(sqlCommand, connectionString);
DataSet GetDataSet(string sqlCommand, string connectionString)
{
    DataSet ds = new DataSet();
    using (SqlCommand cmd = new SqlCommand(
        sqlCommand, new SqlConnection(connectionString)))
    {
        cmd.Connection.Open();
        DataTable table = new DataTable();
        table.Load(cmd.ExecuteReader());
        ds.Tables.Add(table);
    }
    return ds;
}

Handling warning for possible multiple enumeration of IEnumerable

The problem with taking IEnumerable as a parameter is that it tells callers "I wish to enumerate this". It doesn't tell them how many times you wish to enumerate.

I can change the objects parameter to be List and then avoid the possible multiple enumeration but then I don't get the highest object that I can handle.

The goal of taking the highest object is noble, but it leaves room for too many assumptions. Do you really want someone to pass a LINQ to SQL query to this method, only for you to enumerate it twice (getting potentially different results each time?)

The semantic missing here is that a caller, who perhaps doesn't take time to read the details of the method, may assume you only iterate once - so they pass you an expensive object. Your method signature doesn't indicate either way.

By changing the method signature to IList/ICollection, you will at least make it clearer to the caller what your expectations are, and they can avoid costly mistakes.

Otherwise, most developers looking at the method might assume you only iterate once. If taking an IEnumerable is so important, you should consider doing the .ToList() at the start of the method.

It's a shame .NET doesn't have an interface that is IEnumerable + Count + Indexer, without Add/Remove etc. methods, which is what I suspect would solve this problem.

When to use the JavaScript MIME type application/javascript instead of text/javascript?

application/javascript is the correct type to use but since it's not supported by IE6-8 you're going to be stuck with text/javascript. If you don't care about validity (HTML5 excluded) then just don't specify a type.

How to make a drop down list in yii2?

Following can also be done. If you want to append prepend icon. This will be helpful.

<?php $form = ActiveForm::begin();    
   echo $form->field($model, 'field')->begin();
     echo Html::activeLabel($model, 'field', ["class"=>"control-label col-md-4"]); ?>
       <div class="col-md-5">
          <?php echo Html::activeDropDownList($model, 'field', $array_list, ['class'=>'form-control']); ?>
          <p><i><small>Please select field</small></i>.</p>
          <?php echo Html::error($model, 'field', ['class'=>'help-block']); ?>
       </div>
   <?php echo $form->field($model, 'field')->end(); 
ActiveForm::end();?>

Downloading folders from aws s3, cp or sync?

In the case you want to download a single file, you can try the following command:

aws s3 cp s3://bucket/filename /path/to/dest/folder

restart mysql server on windows 7

Ctrl + alt +delete to start TASK MANAGER ,choose Service ,Then you will find MySQL, click that item by right click,then choose start, your MySQL Server will start!

How to make MySQL table primary key auto increment with some prefix

Here is PostgreSQL example without trigger if someone need it on PostgreSQL:

CREATE SEQUENCE messages_seq;

 CREATE TABLE IF NOT EXISTS messages (
    id CHAR(20) NOT NULL DEFAULT ('message_' || nextval('messages_seq')),
    name CHAR(30) NOT NULL,
);

ALTER SEQUENCE messages_seq OWNED BY messages.id;

How to check if a file exists in the Documents directory in Swift?

Very simple: If your path is a URL instance convert to string by 'path' method.

    let fileManager = FileManager.default
    var isDir: ObjCBool = false
    if fileManager.fileExists(atPath: yourURLPath.path, isDirectory: &isDir) {
        if isDir.boolValue {
            //it's a Directory path
        }else{
            //it's a File path
        }
    }

How do you extract classes' source code from a dll file?

I used Refractor to recover my script/code from dll file.

How can I tell how many objects I've stored in an S3 bucket?

You can potentially use Amazon S3 inventory that will give you list of objects in a csv file

How do I collapse a table row in Bootstrap?

You are using collapse on the div inside of your table row (tr). So when you collapse the div, the row is still there. You need to change it to where your id and class are on the tr instead of the div.

Change this:

<tr><td><div class="collapse out" id="collapseme">Should be collapsed</div></td></tr>

to this:

<tr class="collapse out" id="collapseme"><td><div>Should be collapsed</div></td></tr>

JSFiddle: http://jsfiddle.net/KnuU6/21/

EDIT: If you are unable to upgrade to 3.0.0, I found a JQuery workaround in 2.3.2:

Remove your data-toggle and data-target and add this JQuery to your button.

$(".btn").click(function() {
    if($("#collapseme").hasClass("out")) {
        $("#collapseme").addClass("in");
        $("#collapseme").removeClass("out");
    } else {
        $("#collapseme").addClass("out");
        $("#collapseme").removeClass("in");
    }
});

JSFiddle: http://jsfiddle.net/KnuU6/25/

What's the difference between [ and [[ in Bash?

  • [ is the same as the test builtin, and works like the test binary (man test)
    • works about the same as [ in all the other sh-based shells in many UNIX-like environments
    • only supports a single condition. Multiple tests with the bash && and || operators must be in separate brackets.
    • doesn't natively support a 'not' operator. To invert a condition, use a ! outside the first bracket to use the shell's facility for inverting command return values.
    • == and != are literal string comparisons
  • [[ is a bash
    • is bash-specific, though others shells may have implemented similar constructs. Don't expect it in an old-school UNIX sh.
    • == and != apply bash pattern matching rules, see "Pattern Matching" in man bash
    • has a =~ regex match operator
    • allows use of parentheses and the !, &&, and || logical operators within the brackets to combine subexpressions

Aside from that, they're pretty similar -- most individual tests work identically between them, things only get interesting when you need to combine different tests with logical AND/OR/NOT operations.

Dark Theme for Visual Studio 2010 With Productivity Power Tools

You can also try this handy online tool, which generates .vssettings file for you.

Visual Studio Color Theme Generator

Python __call__ special method practical example

IMHO __call__ method and closures give us a natural way to create STRATEGY design pattern in Python. We define a family of algorithms, encapsulate each one, make them interchangeable and in the end we can execute a common set of steps and, for example, calculate a hash for a file.

Convert Decimal to Varchar

You might need to convert the decimal to money (or decimal(8,2)) to get that exact formatting. The convert method can take a third parameter that controls the formatting style:

convert(varchar, cast(price as money))       12345.67
convert(varchar, cast(price as money), 0)    12345.67
convert(varchar, cast(price as money), 1)    12,345.67

What is the difference between "expose" and "publish" in Docker?

EXPOSE is used to map local port container port ie : if you specify expose in docker file like

EXPOSE 8090

What will does it will map localhost port 8090 to container port 8090

How to get ID of clicked element with jQuery

First off you can't have just a number for your id unless you are using the HTML5 DOCTYPE. Secondly, you need to either remove the # in each id or replace it with this:

$container.cycle(id.replace('#','')); 

Express.js - app.listen vs server.listen

The second form (creating an HTTP server yourself, instead of having Express create one for you) is useful if you want to reuse the HTTP server, for example to run socket.io within the same HTTP server instance:

var express = require('express');
var app     = express();
var server  = require('http').createServer(app);
var io      = require('socket.io').listen(server);
...
server.listen(1234);

However, app.listen() also returns the HTTP server instance, so with a bit of rewriting you can achieve something similar without creating an HTTP server yourself:

var express   = require('express');
var app       = express();

// app.use/routes/etc...

var server    = app.listen(3033);
var io        = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
  ...
});

new Image(), how to know if image 100% loaded or not?

Using the Promise pattern:

function getImage(url){
        return new Promise(function(resolve, reject){
            var img = new Image()
            img.onload = function(){
                resolve(url)
            }
            img.onerror = function(){
                reject(url)
            }
            img.src = url
        })
    }

And when calling the function we can handle its response or error quite neatly.

getImage('imgUrl').then(function(successUrl){
    //do stufff
}).catch(function(errorUrl){
    //do stuff
})

OracleCommand SQL Parameters Binding

You need to use something like this:

 OracleCommand oraCommand = new OracleCommand("SELECT fullname FROM sup_sys.user_profile
                       WHERE domain_user_name = :userName", db);

More can be found in this MSDN article: http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.parameters%28v=vs.100%29.aspx

It is advised you use the : character instead of @ for Oracle.

Matching an optional substring in a regex

This ought to work:

^\d+\s?(\([^\)]+\)\s?)?Z$

Haven't tested it though, but let me give you the breakdown, so if there are any bugs left they should be pretty straightforward to find:

First the beginning:

^ = beginning of string
\d+ = one or more decimal characters
\s? = one optional whitespace

Then this part:

(\([^\)]+\)\s?)?

Is actually:

(.............)?

Which makes the following contents optional, only if it exists fully

\([^\)]+\)\s?

\( = an opening bracket
[^\)]+ = a series of at least one character that is not a closing bracket
\) = followed by a closing bracket
\s? = followed by one optional whitespace

And the end is made up of

Z$

Where

Z = your constant string
$ = the end of the string

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

As explained in the documentation, by using an @RequestParam annotation:

public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
    return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
           + foo;
}

iPhone App Development on Ubuntu

Perhaps the best way would be to implement your app as a web app. I think you can also make web apps that run direct on the phone, without internet access or a remote server.

Web app, sounds lame? But a lot can be done with DHTML / HTML5 / JavaScript. It's a rare app that requires more power and couldn't be done as a web app. And you get pretty good cross platform with Web / JavaScript - the browsers vary a bit but a good web dev can write one web app that works pretty much everywhere.

Of course if you're writing a high-performance 3D game, the browser might not deliver what you need! maybe in a few years... Apparently some Google hackers ported Quake 2 to HTML5 already!

http://web.appstorm.net/roundups/browsers/10-html5-games-paving-the-way/

How do I override nested NPM dependency versions?

For those from 2018 and beyond, using npm version 5 or later: edit your package-lock.json: remove the library from "requires" section and add it under "dependencies".

For example, you want deglob package to use glob package version 3.2.11 instead of its current one. You open package-lock.json and see:

"deglob": {
  "version": "2.1.0",
  "resolved": "https://registry.npmjs.org/deglob/-/deglob-2.1.0.tgz",
  "integrity": "sha1-TUSr4W7zLHebSXK9FBqAMlApoUo=",
  "requires": {
    "find-root": "1.1.0",
    "glob": "7.1.2",
    "ignore": "3.3.5",
    "pkg-config": "1.1.1",
    "run-parallel": "1.1.6",
    "uniq": "1.0.1"
  }
},

Remove "glob": "7.1.2", from "requires", add "dependencies" with proper version:

"deglob": {
  "version": "2.1.0",
  "resolved": "https://registry.npmjs.org/deglob/-/deglob-2.1.0.tgz",
  "integrity": "sha1-TUSr4W7zLHebSXK9FBqAMlApoUo=",
  "requires": {
    "find-root": "1.1.0",
    "ignore": "3.3.5",
    "pkg-config": "1.1.1",
    "run-parallel": "1.1.6",
    "uniq": "1.0.1"
  },
  "dependencies": {
    "glob": {
      "version": "3.2.11"
    }
  }
},

Now remove your node_modules folder, run npm install and it will add missing parts to the "dependencies" section.

FailedPreconditionError: Attempting to use uninitialized in Tensorflow

When I had this issue with tf.train.string_input_producer() and tf.train.batch() initializing the local variables before I started the Coordinator solved the problem. I had been getting the error when I initialized the local variables after starting the Coordinator.

Bitbucket fails to authenticate on git pull

If you found authentication error problem when you entered correct password and username it's git problem. To solves this problem when you are installing the git in your machine uncheck the enable git credential manager enter image description here

Truncate (not round) decimal places in SQL Server

ROUND ( 123.456 , 2 , 1 )

When the third parameter != 0 it truncates rather than rounds

http://msdn.microsoft.com/en-us/library/ms175003(SQL.90).aspx

Syntax

ROUND ( numeric_expression , length [ ,function ] )

Arguments

  • numeric_expression Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.

  • length Is the precision to which numeric_expression is to be rounded. length must be an expression of type tinyint, smallint, or int. When length is a positive number, numeric_expression is rounded to the number of decimal positions specified by length. When length is a negative number, numeric_expression is rounded on the left side of the decimal point, as specified by length.

  • function Is the type of operation to perform. function must be tinyint, smallint, or int. When function is omitted or has a value of 0 (default), numeric_expression is rounded. When a value other than 0 is specified, numeric_expression is truncated.

How to add conditional attribute in Angular 2?

If it's an input element you can write something like.... <input type="radio" [checked]="condition"> The value of condition must be true or false.

Also for style attributes... <h4 [style.color]="'red'">Some text</h4>

Bootstrap modal z-index

The problem almost always has something to do with "nested" z-indexes. As an Example:

<div style="z-index:1">
  some content A
  <div style="z-index:1000000000">
    some content B
  </div>
</div>
<div style="z-index:10">
  Some content C
</div>

if you look at the z-index only you would expect B,C,A, but because B is nested in a div that is expressly set to 1, it will show up as C,B,A.

Setting position:fixed locks the z-index for that element and all its children, which is why changing that can solve the problem.

The solution is to find the parent element that has the z-index set and either adjust the setting or move the content so the layers and their parent containers stack up the way you want. Firebug in Firefox has a tab in the far right named "Layout" and you can quickly go up the parent elements and see where the z-index is set.

adding a datatable in a dataset

I assume that you haven't set the TableName property of the DataTable, for example via constructor:

var tbl = new DataTable("dtImage");

If you don't provide a name, it will be automatically created with "Table1", the next table will get "Table2" and so on.

Then the solution would be to provide the TableName and then check with Contains(nameOfTable).

To clarify it: You'll get an ArgumentException if that DataTable already belongs to the DataSet (the same reference). You'll get a DuplicateNameException if there's already a DataTable in the DataSet with the same name(not case-sensitive).

http://msdn.microsoft.com/en-us/library/as4zy2kc.aspx

What is the use of static synchronized method in java?

In simple words a static synchronized method will lock the class instead of the object, and it will lock the class because the keyword static means: "class instead of instance".

The keyword synchronized means that only one thread can access the method at a time.
And static synchronized mean:

Only one thread can access the class at one time.

Difference between CR LF, LF and CR line break types?

Systems based on ASCII or a compatible character set use either LF (Line feed, 0x0A, 10 in decimal) or CR (Carriage return, 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, 0x0D 0x0A); These characters are based on printer commands: The line feed indicated that one line of paper should feed out of the printer, and a carriage return indicated that the printer carriage should return to the beginning of the current line.

Here is the details.

I'm getting favicon.ico error

For me the answer didn't work too, but this work fine:

<link rel="shortcut icon" href="data:image/x-icon;," type="image/x-icon">

Inline Form nested within Horizontal Form in Bootstrap 3

To make it work in Chrome (and bootply) i had to change code in this way:

<form class="form-horizontal">
  <div class="form-group">
    <label for="name" class="col-xs-2 control-label">Name</label>
    <div class="col-xs-10">
      <input type="text" class="form-control col-sm-10" name="name" placeholder="name" />
    </div>
  </div>

  <div class="form-group">
    <label for="birthday" class="col-xs-2 control-label">Birthday</label>
    <div class="col-xs-10">
      <div class="form-inline">
        <input type="text" class="form-control" placeholder="year" />
        <input type="text" class="form-control" placeholder="month" />
        <input type="text" class="form-control" placeholder="day" />
      </div>
    </div>
  </div>
</form>

Array Index Out of Bounds Exception (Java)

for ( i = 0; i < total.length; i++ );
                                    ^-- remove the semi-colon here

With this semi-colon, the loop loops until i == total.length, doing nothing, and then what you thought was the body of the loop is executed.

Is there any way to show a countdown on the lockscreen of iphone?

Or you could figure out the exacting amount of hours and minutes and have that displayed by puttin it into the timer app that already exist in every iphone :)

Sending a mail from a linux shell script

Another option for in a bash script:

mailbody="Testmail via bash script"
echo "From: [email protected]" > /tmp/mailtest
echo "To: [email protected]" >> /tmp/mailtest
echo "Subject: Mailtest subject" >> /tmp/mailtest
echo "" >> /tmp/mailtest
echo $mailbody >> /tmp/mailtest
cat /tmp/mailtest | /usr/sbin/sendmail -t
  • The file /tmp/mailtest is overwritten everytime this script is used.
  • The location of sendmail may differ per system.
  • When using this in a cron script, you have to use the absolute path for the sendmail command.

Making an svg image object clickable with onclick, avoiding absolute positioning

If you just use inline svg there is no problem.

_x000D_
_x000D_
<svg id="svg1" xmlns="http://www.w3.org/2000/svg" style="width: 3.5in; height: 1in">_x000D_
  <circle id="circle1" r="30" cx="34" cy="34" onclick="circle1.style.fill='yellow';"_x000D_
            style="fill: red; stroke: blue; stroke-width: 2"/>_x000D_
  </svg>_x000D_
  
_x000D_
_x000D_
_x000D_

Foreign Key to multiple tables

Another approach is to create an association table that contains columns for each potential resource type. In your example, each of the two existing owner types has their own table (which means you have something to reference). If this will always be the case you can have something like this:

CREATE TABLE dbo.Group
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL
)  

CREATE TABLE dbo.User
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL
)

CREATE TABLE dbo.Ticket
(
    ID int NOT NULL,
    Owner_ID int NOT NULL,
    Subject varchar(50) NULL
)

CREATE TABLE dbo.Owner
(
    ID int NOT NULL,
    User_ID int NULL,
    Group_ID int NULL,
    {{AdditionalEntity_ID}} int NOT NULL
)

With this solution, you would continue to add new columns as you add new entities to the database and you would delete and recreate the foreign key constraint pattern shown by @Nathan Skerl. This solution is very similar to @Nathan Skerl but looks different (up to preference).

If you are not going to have a new Table for each new Owner type then maybe it would be good to include an owner_type instead of a foreign key column for each potential Owner:

CREATE TABLE dbo.Group
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL
)  

CREATE TABLE dbo.User
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL
)

CREATE TABLE dbo.Ticket
(
    ID int NOT NULL,
    Owner_ID int NOT NULL,
    Owner_Type string NOT NULL, -- In our example, this would be "User" or "Group"
    Subject varchar(50) NULL
)

With the above method, you could add as many Owner Types as you want. Owner_ID would not have a foreign key constraint but would be used as a reference to the other tables. The downside is that you would have to look at the table to see what the owner types there are since it isn't immediately obvious based upon the schema. I would only suggest this if you don't know the owner types beforehand and they won't be linking to other tables. If you do know the owner types beforehand, I would go with a solution like @Nathan Skerl.

Sorry if I got some SQL wrong, I just threw this together.

jquery .on() method with load event

Refer to http://api.jquery.com/on/

It says

In all browsers, the load, scroll, and error events (e.g., on an <img> element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event.

If you want to do something when a new input box is added then you can simply write the code after appending it.

$('#add').click(function(){
        $('body').append(x);
        // Your code can be here
    });

And if you want the same code execute when the first input box within the document is loaded then you can write a function and call it in both places i.e. $('#add').click and document's ready event

How to add values in a variable in Unix shell scripting?

In ksh ,bash ,sh:

$ count7=0                     
$ count1=5
$ 
$ (( count7 += count1 ))
$ echo $count7
$ 5

Python: Converting from ISO-8859-1/latin1 to UTF-8

Decode to Unicode, encode the results to UTF8.

apple.decode('latin1').encode('utf8')

Accessing elements by type in javascript

The sizzle selector engine (what powers JQuery) is perfectly geared up for this:

var elements = $('input[type=text]');

Or

var elements = $('input:text');

Centering FontAwesome icons vertically and horizontally

So I finally got it(http://jsfiddle.net/ncapito/eYtU5/):

.centerWrapper:before {
    content:'';
    height: 100%;
    display: inline-block;
    vertical-align: middle;
}

.center {
    display:inline-block;
    vertical-align: middle;
}

<div class='row'>
    <div class='login-icon'>
        <div class='centerWrapper'>
            <div class='center'> <i class='icon-user'></i></div>
       </div>
    </div>
    <input type="text" placeholder="Email" />
 </div>

How do I get TimeSpan in minutes given two Dates?

Why not just doing it this way?

DateTime dt1 = new DateTime(2009, 6, 1);
DateTime dt2 = DateTime.Now;
double totalminutes = (dt2 - dt1).TotalMinutes;

Hope this helps.

Concatenating multiple text files into a single file in Bash

The most upvoted answers will fail if the file list is too long.

A more portable solution would be using fd

fd -e txt -d 1 -X awk 1 > combined.txt

-d 1 limits the search to the current directory. If you omit this option then it will recursively find all .txt files from the current directory.
-X (otherwise known as --exec-batch) executes a command (awk 1 in this case) for all the search results at once.

Regex: match word that ends with "Id"

This may do the trick:

\b\p{L}*Id\b

Where \p{L} matches any (Unicode) letter and \b matches a word boundary.