Programs & Examples On #Pt

A measurement in the print industry. The 'point' (pt) is a unit of length, commonly used to measure the height of a font, but capable of measuring any length( 1pt is equal to 1/72th of an inch).

Pointtype command for gnuplot

You first have to tell Gnuplot to use a style that uses points, e.g. with points or with linespoints. Try for example:

plot sin(x) with points

Output:

Now try:

plot sin(x) with points pointtype 5

Output:

You may also want to look at the output from the test command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:

Rails: Adding an index after adding column

If you need to create a user_id then it would be a reasonable assumption that you are referencing a user table. In which case the migration shall be:

rails generate migration AddUserRefToProducts user:references

This command will generate the following migration:

class AddUserRefToProducts < ActiveRecord::Migration
  def change
    add_reference :user, :product, index: true
  end
end

After running rake db:migrate both a user_id column and an index will be added to the products table.

In case you just need to add an index to an existing column, e.g. name of a user table, the following technique may be helpful:

rails generate migration AddIndexToUsers name:string:index will generate the following migration:

class AddIndexToUsers < ActiveRecord::Migration
  def change
    add_column :users, :name, :string
    add_index :users, :name
  end
end

Delete add_column line and run the migration.

In the case described you could have issued rails generate migration AddIndexIdToTable index_id:integer:index command and then delete add_column line from the generated migration. But I'd rather recommended to undo the initial migration and add reference instead:

rails generate migration RemoveUserIdFromProducts user_id:integer
rails generate migration AddUserRefToProducts user:references

Extracting a parameter from a URL in WordPress

Why not just use the WordPress get_query_var() function? WordPress Code Reference

// Test if the query exists at the URL
if ( get_query_var('ppc') ) {

    // If so echo the value
    echo get_query_var('ppc');

}

Since get_query_var can only access query parameters available to WP_Query, in order to access a custom query var like 'ppc', you will also need to register this query variable within your plugin or functions.php by adding an action during initialization:

add_action('init','add_get_val');
function add_get_val() { 
    global $wp; 
    $wp->add_query_var('ppc'); 
}

Or by adding a hook to the query_vars filter:

function add_query_vars_filter( $vars ){
  $vars[] = "ppc";
  return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

JetBrains / IntelliJ keyboard shortcut to collapse all methods

You Can Go To setting > editor > general > code folding and check "show code folding outline" .

Using Page_Load and Page_PreRender in ASP.Net

Page_Load happens after ViewState and PostData is sent into all of your server side controls by ASP.NET controls being created on the page. Page_Init is the event fired prior to ViewState and PostData being reinstated. Page_Load is where you typically do any page wide initilization. Page_PreRender is the last event you have a chance to handle prior to the page's state being rendered into HTML. Page_Load is the more typical event to work with.

Python Pip install Error: Unable to find vcvarsall.bat. Tried all solutions

I have tried all suggestions and found my own simple solution.

The problem is that codes written in external environment like C need compiler. Look for its own VS environment, i.e. VS 2008.

Currently my machine runs VS 2012 and faces Unable to find vcvarsall.bat. I studied codes that i want to install to find the VS version. It was VS 2008. i have add to system variable VS90COMNTOOLS as variable name and gave the value of VS120COMNTOOLS.

You can find my step by step solution below:

  1. Right click on My Computer.
  2. Click Properties
  3. Advanced system settings
  4. Environment variables
  5. Add New system variable
  6. Enter VS90COMNTOOLS to the variable name
  7. Enter the value of current version to the new variable.
  8. Close all windows

Now open a new session and pip install your-package

What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

Jon skeet said:

The documentation seems pretty clear to me: "Base implementation of HttpClient that also implements Closeable" - HttpClient is an interface; CloseableHttpClient is an abstract class, but because it implements AutoCloseable you can use it in a try-with-resources statement.

But then Jules asked:

@JonSkeet That much is clear, but how important is it to close HttpClient instances? If it's important, why is the close() method not part of the basic interface?

Answer for Jules

close need not be part of basic interface since underlying connection is released back to the connection manager automatically after every execute

To accommodate the try-with-resources statement. It is mandatory to implement Closeable. Hence included it in CloseableHttpClient.

Note:

close method in AbstractHttpClient which is extending CloseableHttpClient is deprecated, I was not able to find the source code for that.

How do you clear the SQL Server transaction log?

DB Transaction Log Shrink to min size:

  1. Backup: Transaction log
  2. Shrink files: Transaction log
  3. Backup: Transaction log
  4. Shrink files: Transaction log

I made tests on several number of DBs: this sequence works.

It usually shrinks to 2MB.

OR by a script:

DECLARE @DB_Name nvarchar(255);
DECLARE @DB_LogFileName nvarchar(255);
SET @DB_Name = '<Database Name>';               --Input Variable
SET @DB_LogFileName = '<LogFileEntryName>';         --Input Variable
EXEC 
(
'USE ['+@DB_Name+']; '+
'BACKUP LOG ['+@DB_Name+'] WITH TRUNCATE_ONLY ' +
'DBCC SHRINKFILE( '''+@DB_LogFileName+''', 2) ' +
'BACKUP LOG ['+@DB_Name+'] WITH TRUNCATE_ONLY ' +
'DBCC SHRINKFILE( '''+@DB_LogFileName+''', 2)'
)
GO

C# guid and SQL uniqueidentifier

You can pass a C# Guid value directly to a SQL Stored Procedure by specifying SqlDbType.UniqueIdentifier.

Your method may look like this (provided that your only parameter is the Guid):

public static void StoreGuid(Guid guid)
{
    using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
    using (var cmd = new SqlCommand {
        Connection = cnx,
        CommandType = CommandType.StoredProcedure,
        CommandText = "StoreGuid",
        Parameters = {
            new SqlParameter {
                ParameterName = "@guid",
                SqlDbType = SqlDbType.UniqueIdentifier, // right here
                Value = guid
            }
        }
    })
    {
        cnx.Open();
        cmd.ExecuteNonQuery();
    }
}

See also: SQL Server's uniqueidentifier

Twitter bootstrap float div right

You can assign the class name like text-center, left or right. The text will align accordingly to these class name. You don't need to make extra class name separately. These classes are built in BootStrap 3 and bootstrap 4.

Bootstrap 3

v3 Text Alignment Docs

<p class="text-left">Left aligned text.</p>
<p class="text-center">Center aligned text.</p>
<p class="text-right">Right aligned text.</p>
<p class="text-justify">Justified text.</p>
<p class="text-nowrap">No wrap text.</p>

Bootstrap 4

v4 Text Alignment Docs

<p class="text-xs-left">Left aligned text on all viewport sizes.</p>
<p class="text-xs-center">Center aligned text on all viewport sizes.</p>
<p class="text-xs-right">Right aligned text on all viewport sizes.</p>

<p class="text-sm-left">Left aligned text on viewports sized SM (small) or wider.</p>
<p class="text-md-left">Left aligned text on viewports sized MD (medium) or wider.</p>
<p class="text-lg-left">Left aligned text on viewports sized LG (large) or wider.</p>
<p class="text-xl-left">Left aligned text on viewports sized XL (extra-large) or wider.</p>

How to check if a "lateinit" variable has been initialized?

Try to use it and you will receive a UninitializedPropertyAccessException if it is not initialized.

lateinit is specifically for cases where fields are initialized after construction, but before actual use (a model which most injection frameworks use). If this is not your use case lateinit might not be the right choice.

EDIT: Based on what you want to do something like this would work better:

val chosenFile = SimpleObjectProperty<File?>
val button: Button

// Disables the button if chosenFile.get() is null
button.disableProperty.bind(chosenFile.isNull())

ORA-12154 could not resolve the connect identifier specified

If you are using LDAP, make sure that the environment variable "TNS_ADMIN" exists and points to the folder containing the file "ldap.ora".

If this variable does not exist, create it and restart Visual Studio.

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.

POST request not allowed - 405 Not Allowed - nginx, even with headers included

I noticed this wasn't working with a static-first-then-reverse-proxy setup. Here's what that looks like:

location @app {
  proxy_pass http://localhost:3000$request_uri;
}

location / {
  try_files $uri $uri/ @app;
  error_page 405 @app;
}

Get file path of image on Android

You can do like that In Kotlin If you need kotlin code in the future

val myUri = getImageUri(applicationContext, myBitmap!!)
val finalFile = File(getRealPathFromURI(myUri))

fun getImageUri(inContext: Context, inImage: Bitmap): Uri {
    val bytes = ByteArrayOutputStream()
    inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes)
    val path = MediaStore.Images.Media.insertImage(inContext.contentResolver, inImage, "Title", null)
    return Uri.parse(path)
}

fun getRealPathFromURI(uri: Uri): String {
    val cursor = contentResolver.query(uri, null, null, null, null)
    cursor!!.moveToFirst()
    val idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
    return cursor.getString(idx)
}

How to manually set REFERER header in Javascript?

You cannot set Referer header manually but you can use location.href to set the referer header to the link used in href but it will cause reloading of the page.

How to map with index in Ruby?

A fun, but useless way to do this:

az  = ('a'..'z').to_a
azz = az.map{|e| [e, az.index(e)+2]}

Get attribute name value of <input>

If you're dealing with a single element preferably you should use the id selector as stated on GenericTypeTea answer and get the name like $("#id").attr("name");.

But if you want, as I did when I found this question, a list with all the input names of a specific class (in my example a list with the names of all unchecked checkboxes with .selectable-checkbox class) you could do something like:

var listOfUnchecked = $('.selectable-checkbox:unchecked').toArray().map(x=>x.name);

or

var listOfUnchecked = [];
$('.selectable-checkbox:unchecked').each(function () {
    listOfUnchecked.push($(this).attr('name'));
});

Set a div width, align div center and text align left

Set auto margins on the inner div:

<div id="header" style="width:864px;">
    <div id="centered" style="margin: 0 auto; width:855px;"></div>
</div>

Alternatively, text align center the parent, and force text align left on the inner div:

<div id="header" style="width:864px;text-align: center;">
    <div id="centered" style="text-align: left; width:855px;"></div>
</div>

pycharm running way slow

Well Lorenz Lo Sauer already have a good question for this. but if you want to resolve this problem through the Pycharm Tuning (without turning off Pycharm code inspection). you can tuning the heap size as you need. since I prefer to use increasing Heap Size solution for slow running Pycharm Application.

You can tune up Heap Size by editing pycharm.exe.vmoptions file. and pycharm64.exe.vmoptions for 64bit application. and then edit -Xmx and -Xms value on it.

So I allocate 2048m for xmx and xms value (which is 2GB) for my Pycharm Heap Size. Here it is My Configuration. I have 8GB memory so I had set it up with this setting:

-server
-Xms2048m
-Xmx2048m
-XX:MaxPermSize=2048m
-XX:ReservedCodeCacheSize=2048m

save the setting, and restart IDE. And I enable "Show memory indicator" in settings->Appearance & Behavior->Appearance. to see it in action :

Pycharm slow, slow typing, increase Pycharm Heap Size

and Pycharm is quick and running fine now.

Reference : https://www.jetbrains.com/help/pycharm/2017.1/tuning-pycharm.html#d176794e266

Making a flex item float right

You don't need floats. In fact, they're useless because floats are ignored in flexbox.

You also don't need CSS positioning.

There are several flex methods available. auto margins have been mentioned in another answer.

Here are two other options:

  • Use justify-content: space-between and the order property.
  • Use justify-content: space-between and reverse the order of the divs.

_x000D_
_x000D_
.parent {_x000D_
    display: flex;_x000D_
    justify-content: space-between;_x000D_
}_x000D_
_x000D_
.parent:first-of-type > div:last-child { order: -1; }_x000D_
_x000D_
p { background-color: #ddd;}
_x000D_
<p>Method 1: Use <code>justify-content: space-between</code> and <code>order-1</code></p>_x000D_
_x000D_
<div class="parent">_x000D_
    <div class="child" style="float:right"> Ignore parent? </div>_x000D_
    <div>another child </div>_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<p>Method 2: Use <code>justify-content: space-between</code> and reverse the order of _x000D_
             divs in the mark-up</p>_x000D_
_x000D_
<div class="parent">_x000D_
    <div>another child </div>_x000D_
    <div class="child" style="float:right"> Ignore parent? </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why do I get "warning longer object length is not a multiple of shorter object length"?

I had a similar issue and using %in% operator instead of the == (equality) operator was the solution:

# %in%

Hope it helps.

Cannot redeclare function php

Remove the function and check the output of:

var_dump(function_exists('parseDate'));

In which case, change the name of the function.

If you get false, you're including the file with that function twice, replace :

include

by

include_once

And replace :

require

by

require_once

EDIT : I'm just a little too late, post before beat me to it !

jump to line X in nano editor

I am using Linux raspi 4.19.118+ #1311 via ssh Powershell on Win 10 Pro 1909 with German keyboard. nano shortcut Goto Line with "Crtl + Shift + -" was not working Solution: Step 1 - Do Current Position with "Crtl + C" Step 2 - Goto Line with "Crtl + Shift + -" IS working!

I dont know what effects it. But now its working without step 1!

How do I make the return type of a method generic?

You have to convert the type of your return value of the method to the Generic type which you pass to the method during calling.

    public static T values<T>()
    {
        Random random = new Random();
        int number = random.Next(1, 4);
        return (T)Convert.ChangeType(number, typeof(T));
    }

You need pass a type that is type casteable for the value you return through that method.

If you would want to return a value which is not type casteable to the generic type you pass, you might have to alter the code or make sure you pass a type that is casteable for the return value of method. So, this approach is not reccomended.

How to Resize image in Swift?

Since @KiritModi 's answer is from 2015, this is the Swift 3.0's version:

func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
    let size = image.size

    let widthRatio  = targetSize.width  / image.size.width
    let heightRatio = targetSize.height / image.size.height

    // Figure out what our orientation is, and use that to form the rectangle
    var newSize: CGSize
    if(widthRatio > heightRatio) {
        newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio)
    } else {
        newSize = CGSize(width: size.width * widthRatio,  height: size.height * widthRatio)
    }

    // This is the rect that we've calculated out and this is what is actually used below
    let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)

    // Actually do the resizing to the rect using the ImageContext stuff
    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    image.draw(in: rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage!
}

In java how to get substring from a string till a character c?

or you may try something like

"abc.def.ghi".substring(0,"abc.def.ghi".indexOf(c)-1);

How do I change the default library path for R packages

I was struggling for a while with this as my work computer (with Windows 10) created the default user library on a network drive, which would slow down R and RStudio to an unusable state.

In case this helps someone, this is the easiest way I found, without requiring admin rights:

  • make sure the directory you want to install your packages into exists. If you want to respect the convention, use: C:\Users\username\R\win-library\rversion (for example, something like: C:\Users\janebloggs\R\win-library\3.6)
  • create a .Renviron file in your home directory (which might be on the network drive?), and in it, write one single line that defines the R_LIBS_USER variable to be your custom path:

R_LIBS_USER=C:\Users\janebloggs\R\win-library\3.6

(feel free to add comments too, with lines starting with #)

If a .Renviron file exists, R will read it at startup and use the variables as they are defined in there, before running the code in the .Rprofile. You can read about it in help(Startup).

Now it should be persistent between sessions!

The network adapter could not establish the connection - Oracle 11g

I had the similar issue. its resolved for me with a simple command.

lsnrctl start

The Network Adapter exception is caused because:

  1. The database host name or port number is wrong (OR)
  2. The database TNSListener has not been started. The TNSListener may be started with the lsnrctl utility.

Try to start the listener using the command prompt:

  1. Click Start, type cmd in the search field, and when cmd shows up in the list of options, right click it and select ‘Run as Administrator’.
  2. At the Command Prompt window, type lsnrctl start without the quotes and press Enter.
  3. Type Exit and press Enter.

Hope it helps.

How to find files modified in last x minutes (find -mmin does not work as expected)

I can reproduce your problem if there are no files in the directory that were modified in the last hour. In that case, find . -mmin -60 returns nothing. The command find . -mmin -60 |xargs ls -l, however, returns every file in the directory which is consistent with what happens when ls -l is run without an argument.

To make sure that ls -l is only run when a file is found, try:

find . -mmin -60 -type f -exec ls -l {} +

How to properly assert that an exception gets raised in pytest?

you can try

def test_exception():
    with pytest.raises(Exception) as excinfo:   
        function_that_raises_exception()   
    assert str(excinfo.value) == 'some info' 

Unpacking a list / tuple of pairs into two lists / tuples

list1 = (x[0] for x in source_list)
list2 = (x[1] for x in source_list)

How to use systemctl in Ubuntu 14.04

I just encountered this problem myself and found that Ubuntu 14.04 uses Upstart instead of Systemd, so systemctl commands will not work. This changed in 15.04, so one way around this would be to update your ubuntu install.

If this is not an option for you (it's not for me right now), you need to find the Upstart command that does what you need to do.

For enable, the generic looks to be the following:

update-rc.d <service> enable

Link to Ubuntu documentation: https://wiki.ubuntu.com/SystemdForUpstartUsers

JQuery - Call the jquery button click event based on name property

$('element[name="element_name"]').click(function(){
    //do stuff
});

in your case:

$('input[name="btnName"]').click(function(){
    //do stuff
});

Where is the Global.asax.cs file?

That's because you created a Web Site instead of a Web Application. The cs/vb files can only be seen in a Web Application, but in a website you can't have a separate cs/vb file.

Edit: In the website you can add a cs file behavior like..

<%@ Application CodeFile="Global.asax.cs" Inherits="ApplicationName.MyApplication" Language="C#" %>

~/Global.asax.cs:

namespace ApplicationName
{
    public partial class MyApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
        }
    }
}

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

For Vb.Net Framework 4.0, U can use:

Alert("your message here", Boolean)

The Boolean here can be True or False. True If you want to close the window right after, False If you want to keep the window open.

jquery function setInterval

This is because you are executing the function not referencing it. You should do:

  setInterval(swapImages,1000);

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

SEVERE: Error listenerStart

This boils down to that a ServletContextListener which is registered by either @WebListener annotation on the class, or by a <listener> declaration in web.xml, has thrown an unhandled exception inside the contextInitialized() method. This is usually caused by a developer's mistake (a bug) and needs to be fixed. For example, a NullPointerException.

The full exception should be visible in webapp-specific startup log as well as the IDE console, before the particular line which you've copypasted. If there is none and you still can't figure the cause of the exception by just looking at the code, put the entire contextInitialized() code in a try-catch wherein you log the exception to a reliable output and then interpret and fix it accordingly.

Post request with Wget?

Wget currently only supports x-www-form-urlencoded data. --post-file is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example.

--post-data and --post-file work the same way: the only difference is that --post-data allows you to specify the data in the command line, while --post-file allows you to specify the path of the file that contain the data to send.

Here's the documentation:

 --post-data=string
       --post-file=file
           Use POST as the method for all HTTP requests and send the specified data
           in the request body.  --post-data sends string as data, whereas
           --post-file sends the contents of file.  Other than that, they work in
           exactly the same way. In particular, they both expect content of the
           form "key1=value1&key2=value2", with percent-encoding for special
           characters; the only difference is that one expects its content as a
           command-line parameter and the other accepts its content from a file. In
           particular, --post-file is not for transmitting files as form
           attachments: those must appear as "key=value" data (with appropriate
           percent-coding) just like everything else. Wget does not currently
           support "multipart/form-data" for transmitting POST data; only
           "application/x-www-form-urlencoded". Only one of --post-data and
           --post-file should be specified.

Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.

Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN.

wget --post-data 'user=foo&password=bar' http://example.com/auth.php

Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.

What is the largest TCP/IP network port number allowable for IPv4?

The largest port number is an unsigned short 2^16-1: 65535

A registered port is one assigned by the Internet Corporation for Assigned Names and Numbers (ICANN) to a certain use. Each registered port is in the range 1024–49151.

Since 21 March 2001 the registry agency is ICANN; before that time it was IANA.

Ports with numbers lower than those of the registered ports are called well known ports; port with numbers greater than those of the registered ports are called dynamic and/or private ports.

Wikipedia : Registered Ports

Django: TemplateSyntaxError: Could not parse the remainder

This error usually means you've forgotten a closing quote somewhere in the template you're trying to render. For example: {% url 'my_view %} (wrong) instead of {% url 'my_view' %} (correct). In this case it's the colon that's causing the problem. Normally you'd edit the template to use the correct {% url %} syntax.

But there's no reason why the django admin site would throw this, since it would know it's own syntax. My best guess is therefore that grapelli is causing your problem since it changes the admin templates. Does removing grappelli from installed apps help?

Install gitk on Mac

Correct, the 1.7.12.4 (Apple Git-37) does not come with gitk. You can install a more recent version of git + git-ui as a separate formula by using brew. More thorough instructions located here: http://www.moncefbelyamani.com/how-to-install-xcode-homebrew-git-rvm-ruby-on-mac/ (see this commit extracting git-gui/gitk into its own formula: https://github.com/Homebrew/homebrew-core/commit/dfa3ccf1e7d3901e371b5140b935839ba9d8b706)

Run the following commands at the terminal:

brew update
brew install git
brew install git-gui

If you get an error indicating it could not link git, then you may need to change permissions/owners of the files it mentions.

Once completed, run:

type -a git

And make sure it shows:

/usr/local/bin/git

If it does not, run:

brew doctor

And make the path change to put /usr/local/bin earlier in the path. Now, gitk should be on your path (along with an updated version of git).

How can I compile my Perl script so it can be executed on systems without perl installed?

pp can create an executable that includes perl and your script (and any module dependencies), but it will be specific to your architecture, so you couldn't run it on both Windows and linux for instance.

From its doc:

To make a stand-alone executable, suitable for running on a machine that doesn't have perl installed:

   % pp -o packed.exe source.pl        # makes packed.exe
   # Now, deploy 'packed.exe' to target machine...
   $ packed.exe                        # run it

(% and $ there are command prompts on different machines).

Add ... if string is too long PHP

For some of you who uses Yii2 there is a method under the hood yii\helpers\StringHelper::truncate().

Example of usage:

$sting = "stringToTruncate";
$truncatedString = \yii\helpers\StringHelper::truncate($string, 6, '...');
echo $truncatedString; // result: "string..."

Here is the doc: https://www.yiiframework.com/doc/api/2.0/yii-helpers-basestringhelper#truncate()-detail

Subtracting time.Duration from time in Go

Try AddDate:

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    fmt.Println("now:", now)

    then := now.AddDate(0, -1, 0)

    fmt.Println("then:", then)
}

Produces:

now: 2009-11-10 23:00:00 +0000 UTC
then: 2009-10-10 23:00:00 +0000 UTC

Playground: http://play.golang.org/p/QChq02kisT

Replace all particular values in a data frame

Here are a couple dplyr options:

library(dplyr)

# all columns:
df %>% 
  mutate_all(~na_if(., ''))

# specific column types:
df %>% 
  mutate_if(is.factor, ~na_if(., ''))

# specific columns:  
df %>% 
  mutate_at(vars(A, B), ~na_if(., ''))

# or:
df %>% 
  mutate(A = replace(A, A == '', NA))

# replace can be used if you want something other than NA:
df %>% 
  mutate(A = as.character(A)) %>% 
  mutate(A = replace(A, A == '', 'used to be empty'))

How to increase dbms_output buffer?

When buffer size gets full. There are several options you can try:

1) Increase the size of the DBMS_OUTPUT buffer to 1,000,000

2) Try filtering the data written to the buffer - possibly there is a loop that writes to DBMS_OUTPUT and you do not need this data.

3) Call ENABLE at various checkpoints within your code. Each call will clear the buffer.

DBMS_OUTPUT.ENABLE(NULL) will default to 20000 for backwards compatibility Oracle documentation on dbms_output

You can also create your custom output display.something like below snippets

create or replace procedure cust_output(input_string in varchar2 )
is 

   out_string_in long default in_string; 
   string_lenth number; 
   loop_count number default 0; 

begin 

   str_len := length(out_string_in);

   while loop_count < str_len
   loop 
      dbms_output.put_line( substr( out_string_in, loop_count +1, 255 ) ); 
      loop_count := loop_count +255; 
   end loop; 
end;

Link -Ref :Alternative to dbms_output.putline @ By: Alexander

How to remove commits from a pull request

You have several techniques to do it.

This post - read the part about the revert will explain in details what we want to do and how to do it.

Here is the most simple solution to your problem:

# Checkout the desired branch
git checkout <branch>

# Undo the desired commit
git revert <commit>

# Update the remote with the undo of the code
git push origin <branch>

The revert command will create a new commit with the undo of the original commit.

DSO missing from command line

DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.

That is, try adding -lpthread to your command line.

What are these attributes: `aria-labelledby` and `aria-hidden`

HTML5 ARIA attribute is what you're looking for. It can be used in your code even without bootstrap.

Accessible Rich Internet Applications (ARIA) defines ways to make Web content and Web applications (especially those developed with Ajax and JavaScript) more accessible to people with disabilities.

To be precise for your question, here is what your attributes are called as ARIA attribute states and model

aria-labelledby: Identifies the element (or elements) that labels the current element.

aria-hidden (state): Indicates that the element and all of its descendants are not visible or perceivable to any user as implemented by the author.

How to quickly clear a JavaScript Object?

You can try this. Function below sets all values of object's properties to undefined. Works as well with nested objects.

var clearObjectValues = (objToClear) => {
    Object.keys(objToClear).forEach((param) => {
        if ( (objToClear[param]).toString() === "[object Object]" ) {
            clearObjectValues(objToClear[param]);
        } else {
            objToClear[param] = undefined;
        }
    })
    return objToClear;
};

Progress during large file copy (Copy-Item & Write-Progress?)

Hate to be the one to bump an old subject, but I found this post extremely useful. After running performance tests on the snippets by stej and it's refinement by Graham Gold, plus the BITS suggestion by Nacht, I have decuded that:

  1. I really liked Graham's command with time estimations and speed readings.
  2. I also really liked the significant speed increase of using BITS as my transfer method.

Faced with the decision between the two... I found that Start-BitsTransfer supported Asynchronous mode. So here is the result of my merging the two.

function Copy-File {
    # ref: https://stackoverflow.com/a/55527732/3626361
    param([string]$From, [string]$To)

    try {
        $job = Start-BitsTransfer -Source $From -Destination $To `
            -Description "Moving: $From => $To" `
            -DisplayName "Backup" -Asynchronous

        # Start stopwatch
        $sw = [System.Diagnostics.Stopwatch]::StartNew()
        Write-Progress -Activity "Connecting..."

        while ($job.JobState.ToString() -ne "Transferred") {
            switch ($job.JobState.ToString()) {
                "Connecting" {
                    break
                }
                "Transferring" {
                    $pctcomp = ($job.BytesTransferred / $job.BytesTotal) * 100
                    $elapsed = ($sw.elapsedmilliseconds.ToString()) / 1000

                    if ($elapsed -eq 0) {
                        $xferrate = 0.0
                    }
                    else {
                        $xferrate = (($job.BytesTransferred / $elapsed) / 1mb);
                    }

                    if ($job.BytesTransferred % 1mb -eq 0) {
                        if ($pctcomp -gt 0) {
                            $secsleft = ((($elapsed / $pctcomp) * 100) - $elapsed)
                        }
                        else {
                            $secsleft = 0
                        }

                        Write-Progress -Activity ("Copying file '" + ($From.Split("\") | Select-Object -last 1) + "' @ " + "{0:n2}" -f $xferrate + "MB/s") `
                            -PercentComplete $pctcomp `
                            -SecondsRemaining $secsleft
                    }
                    break
                }
                "Transferred" {
                    break
                }
                Default {
                    throw $job.JobState.ToString() + " unexpected BITS state."
                }
            }
        }

        $sw.Stop()
        $sw.Reset()
    }
    finally {
        Complete-BitsTransfer -BitsJob $job
        Write-Progress -Activity "Completed" -Completed
    }
}

Why does git say "Pull is not possible because you have unmerged files"?

If you want to pull down a remote branch to run locally (say for reviewing or testing purposes), and when you $ git pull you get local merge conflicts:

$ git checkout REMOTE-BRANCH
$ git pull  (you get local merge conflicts)
$ git reset --hard HEAD (discards local conflicts, and resets to remote branch HEAD)
$ git pull (now get remote branch updates without local conflicts)

Parameterize an SQL IN clause

The proper way IMHO is to store the list in a character string (limited in length by what the DBMS support); the only trick is that (in order to simplify processing) I have a separator (a comma in my example) at the beginning and at the end of the string. The idea is to "normalize on the fly", turning the list into a one-column table that contains one row per value. This allows you to turn

in (ct1,ct2, ct3 ... ctn)

into an

in (select ...)

or (the solution I'd probably prefer) a regular join, if you just add a "distinct" to avoid problems with duplicate values in the list.

Unfortunately, the techniques to slice a string are fairly product-specific. Here is the SQL Server version:

 with qry(n, names) as
       (select len(list.names) - len(replace(list.names, ',', '')) - 1 as n,
               substring(list.names, 2, len(list.names)) as names
        from (select ',Doc,Grumpy,Happy,Sneezy,Bashful,Sleepy,Dopey,' names) as list
        union all
        select (n - 1) as n,
               substring(names, 1 + charindex(',', names), len(names)) as names
        from qry
        where n > 1)
 select n, substring(names, 1, charindex(',', names) - 1) dwarf
 from qry;

The Oracle version:

 select n, substr(name, 1, instr(name, ',') - 1) dwarf
 from (select n,
             substr(val, 1 + instr(val, ',', 1, n)) name
      from (select rownum as n,
                   list.val
            from  (select ',Doc,Grumpy,Happy,Sneezy,Bashful,Sleepy,Dopey,' val
                   from dual) list
            connect by level < length(list.val) -
                               length(replace(list.val, ',', ''))));

and the MySQL version:

select pivot.n,
      substring_index(substring_index(list.val, ',', 1 + pivot.n), ',', -1) from (select 1 as n
     union all
     select 2 as n
     union all
     select 3 as n
     union all
     select 4 as n
     union all
     select 5 as n
     union all
     select 6 as n
     union all
     select 7 as n
     union all
     select 8 as n
     union all
     select 9 as n
     union all
     select 10 as n) pivot,    (select ',Doc,Grumpy,Happy,Sneezy,Bashful,Sleepy,Dopey,' val) as list where pivot.n <  length(list.val) -
                   length(replace(list.val, ',', ''));

(Of course, "pivot" must return as many rows as the maximum number of items we can find in the list)

jQuery get specific option tag text

$(this).children(":selected").text()

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

You can access afterRender hook by using plugins.

And here are all the plugin api available.

In html file:

<html>
  <canvas id="myChart"></canvas>
  <div id="imgWrap"></div>
</html>

In js file:

var chart = new Chart(ctx, {
  ...,
  plugins: [{
    afterRender: function () {
      // Do anything you want
      renderIntoImage()
    },
  }],
  ...,
});

const renderIntoImage = () => {
  const canvas = document.getElementById('myChart')
  const imgWrap = document.getElementById('imgWrap')
  var img = new Image();
  img.src = canvas.toDataURL()
  imgWrap.appendChild(img)
  canvas.style.display = 'none'
}

SQLite Reset Primary Key Field

You can reset by update sequence after deleted rows in your-table

UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME='table_name';

How to .gitignore all files/folder in a folder, but not the folder itself?

You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.

For example, add an empty file called .gitkeep to the folder you want to keep, then in your .gitignore file write:

# exclude everything
somefolder/*

# exception to the rule
!somefolder/.gitkeep 

Commit your .gitignore and .gitkeep files and this should resolve your issue.

What is the best/safest way to reinstall Homebrew?

The way to reinstall Homebrew is completely remove it and start over. The Homebrew FAQ has a link to a shell script to uninstall homebrew.

If the only thing you've installed in /usr/local is homebrew itself, you can just rm -rf /usr/local/* /usr/local/.git to clear it out. But /usr/local/ is the standard Unix directory for all extra binaries, not just Homebrew, so you may have other things installed there. In that case uninstall_homebrew.sh is a better bet. It is careful to only remove homebrew's files and leave the rest alone.

How to pass parameters using ui-sref in ui-router to controller

You simply misspelled $stateParam, it should be $stateParams (with an s). That's why you get undefined ;)

C# : Out of Memory exception

As .Net progresses, so does their ability to add new 32-bit configurations that trips everyone up it seems.

If you are on .Net Framework 4.7.2 do the following:

Go to Project Properties

Build

Uncheck 'prefer 32-bit'

Cheers!

How can I switch word wrap on and off in Visual Studio Code?

Go to menu FilePreferencesUser Settings.

It will open up Default Settings and settings.json automatically. Just add the following in the settings.json file and save it. This will overwrite the default settings.

// Place your settings in this file to overwrite the default settings
{ "editor.wrappingColumn": 0 }

Screenshot of settings being edited.

Change language of Visual Studio 2017 RC

Polish-> English (VS on MAC) answer: When I started a project and was forced to download Visual Studio, went to their page and saw that Microsoft logo I knew there would be problems... And here it is. It occurred difficult to change the language of VS on Mac. My OS is purely English and only because of the fact I downloaded it using a browser with Polish set as a default language I got the wrong version. I had to reinstall the version to the newest and then Visual Studio Community -> Preferences(in the environment section) -> Visual Style-> User Interface Language.

It translates to polish: Visual Studio Community -> Preferencje -> Styl Wizualny w sekcji Srodowisko -> Jezyk interfejsu uzytkownika -> English.

If you don't see such an option then, as I was, you are forced to upgrade this crappy VS to the newest version.

How to change time in DateTime?

Try this one

var NewDate = Convert.ToDateTime(DateTime.Now.ToString("dd/MMM/yyyy")+" "+"10:15 PM")/*Add your time here*/;

Integer to hex string in C++

My solution. Only integral types are allowed.

Update. You can set optional prefix 0x in second parameter.

definition.h

#include  <iomanip>
#include <sstream>

template <class T, class T2 = typename std::enable_if<std::is_integral<T>::value>::type>
static std::string ToHex(const T & data, bool addPrefix = true);



template<class T, class>
inline std::string Convert::ToHex(const T & data, bool addPrefix)
{
    std::stringstream sstream;
    sstream << std::hex;
    std::string ret;
    if (typeid(T) == typeid(char) || typeid(T) == typeid(unsigned char) || sizeof(T)==1)
    {
        sstream << static_cast<int>(data);
        ret = sstream.str();
        if (ret.length() > 2)
        {
            ret = ret.substr(ret.length() - 2, 2);
        }
    }
    else
    {
        sstream << data;
        ret = sstream.str();
    }
    return (addPrefix ? u8"0x" : u8"") + ret;
}

main.cpp

#include <definition.h>
int main()
{
    std::cout << ToHex<unsigned char>(254) << std::endl;
    std::cout << ToHex<char>(-2) << std::endl;
    std::cout << ToHex<int>(-2) << std::endl;
    std::cout << ToHex<long long>(-2) << std::endl;

    std::cout<< std::endl;
    std::cout << ToHex<unsigned char>(254, false) << std::endl;
    std::cout << ToHex<char>(-2, false) << std::endl;
    std::cout << ToHex<int>(-2, false) << std::endl;
    std::cout << ToHex<long long>(-2, false) << std::endl;
    return 0;
}

Results:
0xfe
0xfe
0xfffffffe
0xfffffffffffffffe

fe
fe fffffffe
fffffffffffffffe

How to get hex color value rather than RGB value?

Here is my solution, also does touppercase by the use of an argument and checks for other possible white-spaces and capitalisation in the supplied string.

var a = "rgb(10, 128, 255)";
var b = "rgb( 10, 128, 255)";
var c = "rgb(10, 128, 255 )";
var d = "rgb ( 10, 128, 255 )";
var e = "RGB ( 10, 128, 255 )";
var f = "rgb(10,128,255)";
var g = "rgb(10, 128,)";

var rgbToHex = (function () {
    var rx = /^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i;

    function pad(num) {
        if (num.length === 1) {
            num = "0" + num;
        }

        return num;
    }

    return function (rgb, uppercase) {
        var rxArray = rgb.match(rx),
            hex;

        if (rxArray !== null) {
            hex = pad(parseInt(rxArray[1], 10).toString(16)) + pad(parseInt(rxArray[2], 10).toString(16)) + pad(parseInt(rxArray[3], 10).toString(16));

            if (uppercase === true) {
                hex = hex.toUpperCase();
            }

            return hex;
        }

        return;
    };
}());

console.log(rgbToHex(a));
console.log(rgbToHex(b, true));
console.log(rgbToHex(c));
console.log(rgbToHex(d));
console.log(rgbToHex(e));
console.log(rgbToHex(f));
console.log(rgbToHex(g));

On jsfiddle

Speed comparison on jsperf

A further improvement could be to trim() the rgb string

var rxArray = rgb.trim().match(rx),

How to draw circle in html page?

Simply do the following in the script tags:

_x000D_
_x000D_
<!Doctype html>_x000D_
<html>_x000D_
<head>_x000D_
 <title>Circle Canvas</title>_x000D_
</head>_x000D_
<body>_x000D_
 <canvas id="myCanvas" width="300" height="150" style="border:1px solid _x000D_
#d3d3d3;">_x000D_
 <body>_x000D_
  <script>_x000D_
   var c = document.getElementById("myCanvas");_x000D_
   var ctx = c.getContext("2d");_x000D_
   ctx.beginPath();_x000D_
   ctx.arc(100, 75, 50, 0, 2 * Math.PI);_x000D_
   ctx.stroke();_x000D_
  </script>_x000D_
    </body>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

And there you go you got your circle.

How to check string length and then select substring in Sql Server

To conditionally check the length of the string, use CASE.

SELECT  CASE WHEN LEN(comments) <= 60 
             THEN comments
             ELSE LEFT(comments, 60) + '...'
        END  As Comments
FROM    myView

Getting request payload from POST request in Java servlet

If you are able to send the payload in JSON, this is a most convenient way to read the playload:

Example data class:

public class Person {
    String firstName;
    String lastName;
    // Getters and setters ...
}

Example payload (request body):

{ "firstName" : "John", "lastName" : "Doe" }

Code to read payload in servlet (requires com.google.gson.*):

Person person = new Gson().fromJson(request.getReader(), Person.class);

That's all. Nice, easy and clean. Don't forget to set the content-type header to application/json.

How do I split a string in Rust?

There is a special method split for struct String:

fn split<'a, P>(&'a self, pat: P) -> Split<'a, P> where P: Pattern<'a>

Split by char:

let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);

Split by string:

let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);

Split by closure:

let v: Vec<&str> = "abc1def2ghi".split(|c: char| c.is_numeric()).collect();
assert_eq!(v, ["abc", "def", "ghi"]);

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

on Kate

Ctrl + Shift + B also allows you to add more columns by simply clicking anywhere and paste it.

I used this when saving text files I copied from Google Translate as a side-by-side view.

NSUserDefaults - How to tell if a key exists

In Swift3, I have used in this way

var hasAddedGeofencesAtleastOnce: Bool {
    get {
        return UserDefaults.standard.object(forKey: "hasAddedGeofencesAtleastOnce") != nil
    }
}

The answer is great if you are to use that multiple times.

I hope it helps :)

Force uninstall of Visual Studio

Microsoft now has this:

https://github.com/Microsoft/VisualStudioUninstaller/releases

I allowed a windows 10 update to go through that completely f****d VS2015 so I am trying this before having to resort to a rebuild. WT*. :-(

https://visualstudio.uservoice.com/forums/121579-visual-studio-ide/suggestions/3487794-create-a-remove-all-remnants-of-visual-studio-fro

List All Google Map Marker Images

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(12, 18)
);

How do I set the time zone of MySQL?

If anyone is using GoDaddy Shared Hosting, you can try for following solution, worked for me.

When starting DB connection, set the time_zone command in my PDO object e.g.:

$pdo = new PDO($dsn, $user, $pass, $opt);
$pdo->exec("SET time_zone='+05:30';");

Where "+05:30" is the TimeZone of India. You can change it as per your need.

After that; all the MySQL processes related to Date and Time are set with required timezone.

Source : https://in.godaddy.com/community/cPanel-Hosting/How-to-change-TimeZone-for-MySqL/td-p/31861

How to create JSON object using jQuery

A "JSON object" doesn't make sense : JSON is an exchange format based on the structure of Javascript object declaration.

If you want to convert your javascript object to a json string, use JSON.stringify(yourObject);

If you want to create a javascript object, simply do it like this :

var yourObject = {
          test:'test 1',
          testData: [ 
                {testName: 'do',testId:''}
          ],
          testRcd:'value'   
};

pip cannot install anything

This has happened to my because of proxy-authntication, so I did this to resolve it

export http_proxy=http://uname:[email protected]:8080
export https_proxy=http://uname:[email protected]:8080
export ftp_proxy=http://uname:[email protected]:8080

apt-get for Cygwin?

This got it working for me:

curl https://raw.githubusercontent.com/transcode-open/apt-cyg/master/apt-cyg > \
apt-cyg && install apt-cyg /bin

How to write log file in c#?

create a class create a object globally and call this

using System.IO;
using System.Reflection;


   public class LogWriter
{
    private string m_exePath = string.Empty;
    public LogWriter(string logMessage)
    {
        LogWrite(logMessage);
    }
    public void LogWrite(string logMessage)
    {
        m_exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        try
        {
            using (StreamWriter w = File.AppendText(m_exePath + "\\" + "log.txt"))
            {
                Log(logMessage, w);
            }
        }
        catch (Exception ex)
        {
        }
    }

    public void Log(string logMessage, TextWriter txtWriter)
    {
        try
        {
            txtWriter.Write("\r\nLog Entry : ");
            txtWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
                DateTime.Now.ToLongDateString());
            txtWriter.WriteLine("  :");
            txtWriter.WriteLine("  :{0}", logMessage);
            txtWriter.WriteLine("-------------------------------");
        }
        catch (Exception ex)
        {
        }
    }
}

Should I use != or <> for not equal in T-SQL?

They are both accepted in T-SQL. However, it seems that using <> works a lot faster than !=. I just ran a complex query that was using !=, and it took about 16 seconds on average to run. I changed those to <> and the query now takes about 4 seconds on average to run. That's a huge improvement!

How to let PHP to create subdomain automatically for each user?

You're looking to create a custom A record.

I'm pretty sure that you can use wildcards when specifying A records which would let you do something like this:

*.mywebsite.com       IN  A       127.0.0.1

127.0.0.1 would be the IP address of your webserver. The method of actually adding the record will depend on your host.


Doing it like http://mywebsite.com/user would be a lot easier to set up if it's an option.

Then you could just add a .htaccess file that looks like this:

Options +FollowSymLinks

RewriteEngine On
RewriteRule ^([aA-zZ])$  dostuff.php?username=$1

In the above, usernames are limited to the characters a-z


The rewrite rule for grabbing the subdomain would look like this:

RewriteCond %{HTTP_HOST} ^(^.*)\.mywebsite.com
RewriteRule (.*)  dostuff.php?username=%1

However, you don't really need any rewrite rules. The HTTP_HOST header is available in PHP as well, so you can get it already, like

$username = strtok($_SERVER['HTTP_HOST'], ".");

select data up to a space?

select left(col, charindex(' ', col) - 1)

What is parsing in terms that a new programmer would understand?

I'd explain parsing as the process of turning some kind of data into another kind of data.

In practice, for me this is almost always turning a string, or binary data, into a data structure inside my Program.

For example, turning

":Nick!User@Host PRIVMSG #channel :Hello!"

into (C)

struct irc_line {
    char *nick;
    char *user;
    char *host;
    char *command;
    char **arguments;
    char *message;
} sample = { "Nick", "User", "Host", "PRIVMSG", { "#channel" }, "Hello!" }

How can I get Git to follow symlinks?

I used to add files beyond symlinks for quite some time now. This used to work just fine, without making any special arrangements. Since I updated to Git 1.6.1, this does not work any more.

You may be able to switch to Git 1.6.0 to make this work. I hope that a future version of Git will have a flag to git-add allowing it to follow symlinks again.

Sum values from multiple rows using vlookup or index/match functions

You should use Ctrl+shift+enter when using the =SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE)) that results in {=SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE))} en also works.

Using CookieContainer with WebClient class

Yes. IMHO, overriding GetWebRequest() is the best solution to WebClient's limited functionalty. Before I knew about this option, I wrote lots of really painful code at the HttpWebRequest layer because WebClient almost, but not quite, did what I needed. Derivation is much easier.

Another option is to use the regular WebClient class, but manually populate the Cookie header before making the request and then pull out the Set-Cookies header on the response. There are helper methods on the CookieContainer class which make creating and parsing these headers easier: CookieContainer.SetCookies() and CookieContainer.GetCookieHeader(), respectively.

I prefer the former approach since it's easier for the caller and requires less repetitive code than the second option. Also, the derivation approach works the same way for multiple extensibility scenarios (e.g. cookies, proxies, etc.).

Pipe subprocess standard output to a variable

If you are using python 2.7 or later, the easiest way to do this is to use the subprocess.check_output() command. Here is an example:

output = subprocess.check_output('ls')

To also redirect stderr you can use the following:

output = subprocess.check_output('ls', stderr=subprocess.STDOUT)



In the case that you want to pass parameters to the command, you can either use a list or use invoke a shell and use a single string.

output = subprocess.check_output(['ls', '-a'])
output = subprocess.check_output('ls -a', shell=True)

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

This was the best solution for me, just follow this path C:\Users\yourusername.gradle\wrapper\dists then delete all the files inside this folder. Close your android studio and restart it and it will automatically download the updated gradle files.

Cannot make file java.io.IOException: No such file or directory

File.isFile() is false if the file / directory does not exist, so you can't use it to test whether you're trying to create a directory. But that's not the first issue here.

The issue is that the intermediate directories don't exist. You want to call f.mkdirs() first.

C# Java HashMap equivalent

I just wanted to give my two cents.
This is according to @Powerlord 's answer.

Puts "null" instead of null strings.

private static Dictionary<string, string> map = new Dictionary<string, string>();

public static void put(string key, string value)
{
    if (value == null) value = "null";
    map[key] = value;
}

public static string get(string key, string defaultValue)
{
    try
    {
        return map[key];
    }
    catch (KeyNotFoundException e)
    {
        return defaultValue;
    }
}

public static string get(string key)
{
    return get(key, "null");
}

How to search in array of object in mongodb

as explained in above answers Also, to return only one field from the entire array you can use projection into find. and use $

db.getCollection("sizer").find(
  { awards: { $elemMatch: { award: "National Medal", year: 1975 } } },
  { "awards.$": 1, name: 1 }
);

will be reutrn

{
    _id: 1,
    name: {
        first: 'John',
        last: 'Backus'
    },
    awards: [
        {
            award: 'National Medal',
            year: 1975,
            by: 'NSF'
        }
    ]
}

IEnumerable<object> a = new IEnumerable<object>(); Can I do this?

Since you now specified you want to add to it, what you want isn't a simple IEnumerable<T> but at least an ICollection<T>. I recommend simply using a List<T> like this:

List<object> myList=new List<object>();
myList.Add(1);
myList.Add(2);
myList.Add(3);

You can use myList everywhere an IEnumerable<object> is expected, since List<object> implements IEnumerable<object>.

(old answer before clarification)

You can't create an instance of IEnumerable<T> since it's a normal interface(It's sometimes possible to specify a default implementation, but that's usually used only with COM).

So what you really want is instantiate a class that implements the interface IEnumerable<T>. The behavior varies depending on which class you choose.

For an empty sequence use:

IEnumerable<object> e0=Enumerable.Empty<object>();

For an non empty enumerable you can use some collection that implements IEnumerable<T>. Common choices are the array T[], List<T> or if you want immutability ReadOnlyCollection<T>.

IEnumerable<object> e1=new object[]{1,2,3};
IEnumerable<object> e2=new List<object>(){1,2,3};
IEnumerable<object> e3=new ReadOnlyCollection(new object[]{1,2,3});

Another common way to implement IEnumerable<T> is the iterator feature introduced in C# 3:

IEnumerable<object> MyIterator()
{
  yield return 1;
  yield return 2;
  yield return 3;
}

IEnumerable<object> e4=MyIterator();

How to make --no-ri --no-rdoc the default for gem install?

As mentioned above, put gem: --no-document in your gem file. However, the system-wide gemrc will not always necessarily go into /etc/gemrc. If you are using RVM, or you have Ruby installed under /usr/local/bin, it needs to go in a different location. You can find this location by running irb and typing...

require 'rubygems'
Gem::ConfigFile::SYSTEM_WIDE_CONFIG_FILE

See the original post on this over here.

Getting vertical gridlines to appear in line plot in matplotlib

maybe this can solve the problem: matplotlib, define size of a grid on a plot

ax.grid(True, which='both')

The truth is that the grid is working, but there's only one v-grid in 00:00 and no grid in others. I meet the same problem that there's only one grid in Nov 1 among many days.

Scp command syntax for copying a folder from local machine to a remote server

In stall PuTTY in our system and set the environment variable PATH Pointing to putty path. open the command prompt and move to putty folder. Using PSCP command

Please check this

What is callback in Android?

Callback can be very helpful in Java.

Using Callback you can notify another Class of an asynchronous action that has completed with success or error.

Javascript: 'window' is not defined

It is from an external js file and it is the only file linked to the page.

OK.

When I double click this file I get the following error

Sounds like you're double-clicking/running a .js file, which will attempt to run the script outside the browser, like a command line script. And that would explain this error:

Windows Script Host Error: 'window' is not defined Code: 800A1391

... not an error you'll see in a browser. And of course, the browser is what supplies the window object.

ADDENDUM: As a course of action, I'd suggest opening the relevant HTML file and taking a peek at the console. If you don't see anything there, it's likely your window.onload definition is simply being hit after the browser fires the window.onload event.

When use getOne and findOne methods Spring Data JPA

TL;DR

T findOne(ID id) (name in the old API) / Optional<T> findById(ID id) (name in the new API) relies on EntityManager.find() that performs an entity eager loading.

T getOne(ID id) relies on EntityManager.getReference() that performs an entity lazy loading. So to ensure the effective loading of the entity, invoking a method on it is required.

findOne()/findById() is really more clear and simple to use than getOne().
So in the very most of cases, favor findOne()/findById() over getOne().


API Change

From at least, the 2.0 version, Spring-Data-Jpa modified findOne().
Previously, it was defined in the CrudRepository interface as :

T findOne(ID primaryKey);

Now, the single findOne() method that you will find in CrudRepository is which one defined in the QueryByExampleExecutor interface as :

<S extends T> Optional<S> findOne(Example<S> example);

That is implemented finally by SimpleJpaRepository, the default implementation of the CrudRepository interface.
This method is a query by example search and you don't want to that as replacement.

In fact, the method with the same behavior is still there in the new API but the method name has changed.
It was renamed from findOne() to findById() in the CrudRepository interface :

Optional<T> findById(ID id); 

Now it returns an Optional. Which is not so bad to prevent NullPointerException.

So, the actual choice is now between Optional<T> findById(ID id) and T getOne(ID id).


Two distinct methods that rely on two distinct JPA EntityManager retrieval methods

1) The Optional<T> findById(ID id) javadoc states that it :

Retrieves an entity by its id.

As we look into the implementation, we can see that it relies on EntityManager.find() to do the retrieval :

public Optional<T> findById(ID id) {

    Assert.notNull(id, ID_MUST_NOT_BE_NULL);

    Class<T> domainType = getDomainClass();

    if (metadata == null) {
        return Optional.ofNullable(em.find(domainType, id));
    }

    LockModeType type = metadata.getLockModeType();

    Map<String, Object> hints = getQueryHints().withFetchGraphs(em).asMap();

    return Optional.ofNullable(type == null ? em.find(domainType, id, hints) : em.find(domainType, id, type, hints));
}

And here em.find() is an EntityManager method declared as :

public <T> T find(Class<T> entityClass, Object primaryKey,
                  Map<String, Object> properties);

Its javadoc states :

Find by primary key, using the specified properties

So, retrieving a loaded entity seems expected.

2) While the T getOne(ID id) javadoc states (emphasis is mine) :

Returns a reference to the entity with the given identifier.

In fact, the reference terminology is really board and JPA API doesn't specify any getOne() method.
So the best thing to do to understand what the Spring wrapper does is looking into the implementation :

@Override
public T getOne(ID id) {
    Assert.notNull(id, ID_MUST_NOT_BE_NULL);
    return em.getReference(getDomainClass(), id);
}

Here em.getReference() is an EntityManager method declared as :

public <T> T getReference(Class<T> entityClass,
                              Object primaryKey);

And fortunately, the EntityManager javadoc defined better its intention (emphasis is mine) :

Get an instance, whose state may be lazily fetched. If the requested instance does not exist in the database, the EntityNotFoundException is thrown when the instance state is first accessed. (The persistence provider runtime is permitted to throw the EntityNotFoundException when getReference is called.) The application should not expect that the instance state will be available upon detachment, unless it was accessed by the application while the entity manager was open.

So, invoking getOne() may return a lazily fetched entity.
Here, the lazy fetching doesn't refer to relationships of the entity but the entity itself.

It means that if we invoke getOne() and then the Persistence context is closed, the entity may be never loaded and so the result is really unpredictable.
For example if the proxy object is serialized, you could get a null reference as serialized result or if a method is invoked on the proxy object, an exception such as LazyInitializationException is thrown.
So in this kind of situation, the throw of EntityNotFoundException that is the main reason to use getOne() to handle an instance that does not exist in the database as an error situation may be never performed while the entity is not existing.

In any case, to ensure its loading you have to manipulate the entity while the session is opened. You can do it by invoking any method on the entity.
Or a better alternative use findById(ID id) instead of.


Why a so unclear API ?

To finish, two questions for Spring-Data-JPA developers:

  • why not having a clearer documentation for getOne() ? Entity lazy loading is really not a detail.

  • why do you need to introduce getOne() to wrap EM.getReference() ?
    Why not simply stick to the wrapped method :getReference() ? This EM method is really very particular while getOne() conveys a so simple processing.

PHP Composer update "cannot allocate memory" error (using Laravel 4)

I had a same issue on vagrant. I fixed it by allcate more memory.

 config.vm.provider :virtualbox do |vb|
      vb.customize ["modifyvm", :id, "--memory", "1024"]
 end

How can I do width = 100% - 100px in CSS?

There are 2 techniques which can come in handy for this common scenario. Each have their drawbacks but can both be useful at times.

box-sizing: border-box includes padding and border width in the width of an item. For example, if you set the width of a div with 20px 20px padding and 1px border to 100px, the actual width would be 142px but with border-box, both padding and margin are inside the 100px.

.bb{
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;     
    width: 100%;
    height:200px;
    padding: 50px;
}

Here's an excellent article on it: http://css-tricks.com/box-sizing/ and here's a fiddle http://jsfiddle.net/L3Rvw/

And then there's position: absolute

.padded{
    position: absolute;
    top: 50px;
    right: 50px;
    left: 50px;
    bottom: 50px;
    background-color: #aefebc;
}

http://jsfiddle.net/Mw9CT/1/

Neither are perfect of course, box-sizing doesn't exactly fit the question as the element is actually 100% width, rather than 100% - 100px (however a child div would be). And absolute positioning definitely can't be used in every situation, but is usually okay as long as the parent height is set.

How can I divide one column of a data frame through another?

Hadley Wickham

dplyr

packages is always a saver in case of data wrangling. To add the desired division as a third variable I would use mutate()

d <- mutate(d, new = min / count2.freq)

'Field required a bean of type that could not be found.' error spring restful API using mongodb

Add @Repository in your dao class

    @Repository
    public interface UserDao extends CrudRepository<User, Long> {
         User findByUsername(String username);
         User findByEmail(String email);    
      }

Add element to a list In Scala

Use import scala.collection.mutable.MutableList or similar if you really need mutation.

import scala.collection.mutable.MutableList
val x = MutableList(1, 2, 3, 4, 5)
x += 6 // MutableList(1, 2, 3, 4, 5, 6)
x ++= MutableList(7, 8, 9) // MutableList(1, 2, 3, 4, 5, 6, 7, 8, 9)

Replace String in all files in Eclipse

  • "Search"->"File"
  • Enter text, file pattern and projects
  • "Replace"
  • Enter new text

Voilà...

How to construct a set out of list items in python?

If you have a list of hashable objects (filenames would probably be strings, so they should count):

lst = ['foo.py', 'bar.py', 'baz.py', 'qux.py', Ellipsis]

you can construct the set directly:

s = set(lst)

In fact, set will work this way with any iterable object! (Isn't duck typing great?)


If you want to do it iteratively:

s = set()
for item in iterable:
    s.add(item)

But there's rarely a need to do it this way. I only mention it because the set.add method is quite useful.

How can I drop all the tables in a PostgreSQL database?

I modified Pablo's answer slightly for the convenience of having the generated SQL commands returned as one single string:

select string_agg('drop table "' || tablename || '" cascade', '; ') 
from pg_tables where schemaname = 'public'

Where to place and how to read configuration resource files in servlet based application?

It just needs to be in the classpath (aka make sure it ends up under /WEB-INF/classes in the .war as part of the build).

How to prompt for user input and read command-line arguments

To read user input you can try the cmd module for easily creating a mini-command line interpreter (with help texts and autocompletion) and raw_input (input for Python 3+) for reading a line of text from the user.

text = raw_input("prompt")  # Python 2
text = input("prompt")  # Python 3

Command line inputs are in sys.argv. Try this in your script:

import sys
print (sys.argv)

There are two modules for parsing command line options: optparse (deprecated since Python 2.7, use argparse instead) and getopt. If you just want to input files to your script, behold the power of fileinput.

The Python library reference is your friend.

mysql - move rows from one table to another

INSERT INTO Persons_Table (person_id, person_name,person_email)
      SELECT person_id, customer_name, customer_email
      FROM customer_table
      ORDER BY `person_id` DESC LIMIT 0, 15 
      WHERE "insert your where clause here";
DELETE FROM customer_table
      WHERE "repeat your where clause here";

You can also use ORDER BY, LIMIT and ASC/DESC to limit and select the specific column that you want to move.

Static constant string (class member)

In C++ 17 you can use inline variables:

class A {
 private:
  static inline const std::string my_string = "some useful string constant";
};

Note that this is different from abyss.7's answer: This one defines an actual std::string object, not a const char*

Getting an Embedded YouTube Video to Auto Play and Loop

Playlist hack didn't work for me either. Working workaround for September 2018 (bonus: set width and height by CSS for #yt-wrap instead of hard-coding it in JS):

<div id="yt-wrap">
    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
    <div id="ytplayer"></div>
</div>

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
      width: '100%',
      height: '100%',
      videoId: 'VIDEO_ID',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
    player.mute(); // comment out if you don't want the auto played video muted
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.ENDED) {
      player.seekTo(0);
      player.playVideo();
    }
  }
  function stopVideo() {
    player.stopVideo();
  }
</script>

How can I select from list of values in Oracle

You can do this:

create type number_tab is table of number;

select * from table (number_tab(1,2,3,4,5,6));

The column is given the name COLUMN_VALUE by Oracle, so this works too:

select column_value from table (number_tab(1,2,3,4,5,6));

Having a UITextField in a UITableViewCell

Here is how I have achieved this:

TextFormCell.h

#import <UIKit/UIKit.h>

#define CellTextFieldWidth 90.0
#define MarginBetweenControls 20.0

@interface TextFormCell : UITableViewCell {
 UITextField *textField;
}

@property (nonatomic, retain) UITextField *textField;

@end

TextFormCell.m

#import "TextFormCell.h"

@implementation TextFormCell

@synthesize textField;

- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithReuseIdentifier:reuseIdentifier]) {
  // Adding the text field
  textField = [[UITextField alloc] initWithFrame:CGRectZero];
  textField.clearsOnBeginEditing = NO;
  textField.textAlignment = UITextAlignmentRight;
  textField.returnKeyType = UIReturnKeyDone;
  [self.contentView addSubview:textField];
    }
    return self;
}

- (void)dealloc {
 [textField release];
    [super dealloc];
}

#pragma mark -
#pragma mark Laying out subviews

- (void)layoutSubviews {
 CGRect rect = CGRectMake(self.contentView.bounds.size.width - 5.0, 
        12.0, 
        -CellTextFieldWidth, 
        25.0);
 [textField setFrame:rect];
 CGRect rect2 = CGRectMake(MarginBetweenControls,
       12.0,
         self.contentView.bounds.size.width - CellTextFieldWidth - MarginBetweenControls,
         25.0);
 UILabel *theTextLabel = (UILabel *)[self textLabel];
 [theTextLabel setFrame:rect2];
}

It may seems a bit verbose, but it works!

Don't forget to set the delegate!

Use string value from a cell to access worksheet of same name

Here is a solution using INDIRECT, which if you drag the formula, it will pick up different cells from the target sheet accordingly. It uses R1C1 notation and is not limited to working only on columns A-Z.

=INDIRECT("'"&$A$5&"'!R"&ROW()&"C"&COLUMN(),FALSE)

This version picks up the value from the target cell corresponding to the cell where the formula is placed. For example, if you place the formula in 'Summary'!B5 then it will pick up the value from 'SERVER-ONE'!B5, not 'SERVER-ONE'!G7 as specified in the original question. But you could easily add in offsets to the row and column to achieve the desired mapping in any case.

jQuery: more than one handler for same event

Both handlers will run, the jQuery event model allows multiple handlers on one element, therefore a later handler does not override an older handler.

The handlers will execute in the order in which they were bound.

Catching an exception while using a Python 'with' statement

The best "Pythonic" way to do this, exploiting the with statement, is listed as Example #6 in PEP 343, which gives the background of the statement.

@contextmanager
def opened_w_error(filename, mode="r"):
    try:
        f = open(filename, mode)
    except IOError, err:
        yield None, err
    else:
        try:
            yield f, None
        finally:
            f.close()

Used as follows:

with opened_w_error("/etc/passwd", "a") as (f, err):
    if err:
        print "IOError:", err
    else:
        f.write("guido::0:0::/:/bin/sh\n")

What is a database transaction?

Here's a simple explanation. You need to transfer 100 bucks from account A to account B. You can either do:

accountA -= 100;
accountB += 100;

or

accountB += 100;
accountA -= 100;

If something goes wrong between the first and the second operation in the pair you have a problem - either 100 bucks have disappeared, or they have appeared out of nowhere.

A transaction is a mechanism that allows you to mark a group of operations and execute them in such a way that either they all execute (commit), or the system state will be as if they have not started to execute at all (rollback).

beginTransaction;
accountB += 100;
accountA -= 100;
commitTransaction;

will either transfer 100 bucks or leave both accounts in the initial state.

How to get DateTime.Now() in YYYY-MM-DDThh:mm:ssTZD format using C#

use zzz instead of TZD

Example:

DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");

Response:

2011-08-09T11:50:00:02+02:00

How should I read a file line-by-line in Python?

Yes,

with open('filename.txt') as fp:
    for line in fp:
        print line

is the way to go.

It is not more verbose. It is more safe.

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

if ( [dictionary[@"data"][@"action"] isKindOfClass:NSNull.class ] ){
   //do something if doesn't exist
}

This is for nested dictionary structure

Check whether a string contains a substring

To find out if a string contains substring you can use the index function:

if (index($str, $substr) != -1) {
    print "$str contains $substr\n";
} 

It will return the position of the first occurrence of $substr in $str, or -1 if the substring is not found.

how to count length of the JSON array element

First if the object you're dealing with is a string then you need to parse it then figure out the length of the keys :

obj = JSON.parse(jsonString);
shareInfoLen = Object.keys(obj.shareInfo[0]).length;

How to change the font color in the textbox in C#?

RichTextBox will allow you to use html to specify the color. Another alternative is using a listbox and using the DrawItem event to draw how you would like. AFAIK, textbox itself can't be used in the way you're hoping.

Null pointer Exception on .setOnClickListener

android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Because Submit button is inside login_modal so you need to use loginDialog view to access button:

Submit = (Button)loginDialog.findViewById(R.id.Submit);

Can I access variables from another file?

Using Node.js you can export the variable via module.

//first.js
const colorCode = {
    black: "#000",
    white: "#fff"
};
module.exports = { colorCode };

Then, import the module/variable in second file using require.

//second.js
const { colorCode } = require('./first.js')

You can use the import and export aproach from ES6 using Webpack/Babel, but in Node.js you need to enable a flag, and uses the .mjs extension.

Converting ArrayList to Array in java

import java.util.*;
public class arrayList {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        ArrayList<String > x=new ArrayList<>();
        //inserting element
        x.add(sc.next());
        x.add(sc.next());
        x.add(sc.next());
        x.add(sc.next());
        x.add(sc.next());
         //to show element
         System.out.println(x);
        //converting arraylist to stringarray
         String[]a=x.toArray(new String[x.size()]);
          for(String s:a)
           System.out.print(s+" ");
  }

}

Android Studio suddenly cannot resolve symbols

I tried everything listed here. Then I checked my androidmanifest.xml I'd had some stoopid mismatched due to folder renames & package renames.

onclick on a image to navigate to another page using Javascript

Because it makes these things so easy, you could consider using a JavaScript library like jQuery to do this:

<script>
    $(document).ready(function() {
        $('img.thumbnail').click(function() {
            window.location.href = this.id + '.html';
        });
    });
</script>

Basically, it attaches an onClick event to all images with class thumbnail to redirect to the corresponding HTML page (id + .html). Then you only need the images in your HTML (without the a elements), like this:

<img src="bottle.jpg" alt="bottle" class="thumbnail" id="bottle" />
<img src="glass.jpg" alt="glass" class="thumbnail" id="glass" />

Default interface methods are only supported starting with Android N

In app-level gradle, you have to write these code:

android {
...
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

They come from JavaVersion.java in Android.

An enumeration of Java versions.

Before 9: http://www.oracle.com/technetwork/java/javase/versioning-naming-139433.html

After 9: http://openjdk.java.net/jeps/223

@canerkaseler

Should a 502 HTTP status code be used if a proxy receives no response at all?

Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.

For more information about the network errors

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

HTML to PDF with Node.js

In case you arrive here looking for a way to make PDF from view templates in Express, a colleague and I made express-template-to-pdf

which allows you to generate PDF from whatever templates you're using in Express - Pug, Nunjucks, whatever.

It depends on html-pdf and is written to use in your routes just like you use res.render:

const pdfRenderer = require('@ministryofjustice/express-template-to-pdf')

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')

app.use(pdfRenderer())

If you've used res.render then using it should look obvious:

app.use('/pdf', (req, res) => {
    res.renderPDF('helloWorld', { message: 'Hello World!' });
})

You can pass options through to html-pdf to control the PDF document page size etc

Merely building on the excellent work of others.

How to inject window into a service?

There is an opportunity for direct access to the object of window through the document

document.defaultView == window

PDOException “could not find driver”

On Ubuntu just execute

sudo apt-get install php5-mysql

How can I sort an ArrayList of Strings in Java?

Collections.sort(teamsName.subList(1, teamsName.size()));

The code above will reflect the actual sublist of your original list sorted.

How can I display a list view in an Android Alert Dialog?

private void AlertDialogue(final List<Animals> animals) {
 final AlertDialog.Builder alertDialog = new AlertDialog.Builder(AdminActivity.this);
 alertDialog.setTitle("Filter by tag");

 final String[] animalsArray = new String[animals.size()];

 for (int i = 0; i < tags.size(); i++) {
  animalsArray[i] = tags.get(i).getanimal();

 }

 final int checkedItem = 0;
 alertDialog.setSingleChoiceItems(animalsArray, checkedItem, new DialogInterface.OnClickListener() {
  @Override
  public void onClick(DialogInterface dialog, int which) {

   Log.e(TAG, "onClick: " + animalsArray[which]);

  }
 });


 AlertDialog alert = alertDialog.create();
 alert.setCanceledOnTouchOutside(false);
 alert.show();

}

How to upgrade pip3?

What worked for me was the following command:

python -m pip install --upgrade pip

How to find the .NET framework version of a Visual Studio project?

It depends which version of Visual Studio:

  • In 2002, all projects use .Net 1.0
  • In 2003, all projects use .Net 1.1
  • In 2005, all projects use .Net 2.0
  • In 2008, projects use .Net 2.0, 3.0, or 3.5; you can change the version in Project Properties
  • In 2010, projects use .Net 2.0, 3.0, 3.5, or 4.0; you can change the version in Project Properties
  • In 2012, projects use .Net 2.0, 3.0, 3.5, 4.0 or 4.5; you can change the version in Project Properties

Newer versions of Visual Studio support many versions of the .Net framework; check your project type and properties.

Why is this jQuery click function not working?

I found the best solution for this problem by using ON with $(document).

 $(document).on('click', '#yourid', function() { alert("hello"); });

for id start with see below:

$(document).on('click', 'div[id^="start"]', function() {
alert ('hello'); });

finally after 1 week I not need to add onclick triger. I hope this will help many people

How to check if string contains Latin characters only?

No jQuery Needed

if (str.match(/[a-z]/i)) {
    // alphabet letters found
}

How to auto adjust the <div> height according to content in it?

Don't set height. Use min-height and max-height instead.

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

Internet Explorer provides a resizeEnd event. Other browsers will trigger the resize event many times while you're resizing.

There are other great answers here that show how to use setTimeout and the .throttle, .debounce methods from lodash and underscore, so I will mention Ben Alman's throttle-debounce jQuery plugin which accomplishes what you're after.

Suppose you have this function that you want to trigger after a resize:

function onResize() {
  console.log("Resize just happened!");
};

Throttle Example
In the following example, onResize() will only be called once every 250 milliseconds during a window resize.

$(window).resize( $.throttle( 250, onResize) );

Debounce Example
In the following example, onResize() will only be called once at the end of a window resizing action. This achieves the same result that @Mark presents in his answer.

$(window).resize( $.debounce( 250, onResize) );

How do I convert array of Objects into one Object in JavaScript?

I like the functional approach to achieve this task:

var arr = [{ key:"11", value:"1100" }, { key:"22", value:"2200" }];
var result = arr.reduce(function(obj,item){
  obj[item.key] = item.value; 
  return obj;
}, {});

Note: Last {} is the initial obj value for reduce function, if you won't provide the initial value the first arr element will be used (which is probably undesirable).

https://jsfiddle.net/GreQ/2xa078da/

Eclipse - java.lang.ClassNotFoundException

Furthermore, DOUBLE-CHECK the eclipse "Web Deployment Assembly" dialog.

This can be found: Project Properties->Deployment Assembly.

Recently I had an eclipse plugin modify one of my web projects, and it added ~mysteriously~ added the maven test directories /src/test/java, /src/test/resources to the Deployment Assembly. UGGGG!!!

Which is why my project worked fine when I built & deployed just straight maven to tomcat, no ClassNotFoundExceptions... However, when I did the deploy through Eclipse, Whammo!! I start getting ClassNotFoundExceptions because the TestCode is getting deployed.

Eric

Simpler way to create dictionary of separate variables?

Here's the function I created to read the variable names. It's more general and can be used in different applications:

def get_variable_name(*variable):
    '''gets string of variable name
    inputs
        variable (str)
    returns
        string
    '''
    if len(variable) != 1:
        raise Exception('len of variables inputed must be 1')
    try:
        return [k for k, v in locals().items() if v is variable[0]][0]
    except:
        return [k for k, v in globals().items() if v is variable[0]][0]

To use it in the specified question:

>>> foo = False
>>> bar = True
>>> my_dict = {get_variable_name(foo):foo, 
               get_variable_name(bar):bar}
>>> my_dict
{'bar': True, 'foo': False}

Add external libraries to CMakeList.txt c++

I would start with upgrade of CMAKE version.

You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries

INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)

note that lib1 is expanded to liblib1.so (on Linux), so use ln to create appropriate links in case you do not have them

What does "#pragma comment" mean?

The answers and the documentation provided by MSDN is the best, but I would like to add one typical case that I use a lot which requires the use of #pragma comment to send a command to the linker at link time for example

#pragma comment(linker,"/ENTRY:Entry")

tell the linker to change the entry point form WinMain() to Entry() after that the CRTStartup going to transfer controll to Entry()

Eclipse won't compile/run java file

This worked for me:

  1. Create a new project
  2. Create a class in it
  3. Add erroneous code, let error come
  4. Now go to your project
  5. Go to Problems window
  6. Double click on a error

It starts showing compilation errors in the code.

Under what conditions is a JSESSIONID created?

JSESSIONID cookie is created/sent when session is created. Session is created when your code calls request.getSession() or request.getSession(true) for the first time. If you just want to get the session, but not create it if it doesn't exist, use request.getSession(false) -- this will return you a session or null. In this case, new session is not created, and JSESSIONID cookie is not sent. (This also means that session isn't necessarily created on first request... you and your code are in control when the session is created)

Sessions are per-context:

SRV.7.3 Session Scope

HttpSession objects must be scoped at the application (or servlet context) level. The underlying mechanism, such as the cookie used to establish the session, can be the same for different contexts, but the object referenced, including the attributes in that object, must never be shared between contexts by the container.

(Servlet 2.4 specification)

Update: Every call to JSP page implicitly creates a new session if there is no session yet. This can be turned off with the session='false' page directive, in which case session variable is not available on JSP page at all.

Get access to parent control from user control - C#

((frmMain)this.Owner).MyListControl.Items.Add("abc");

Make sure to provide access level you want at Modifiers properties other than Private for MyListControl at frmMain

using nth-child in tables tr td

Current css version still doesn't support selector find by content. But there is a way, by using css selector find by attribute, but you have to put some identifier on all of the <td> that have $ inside. Example: using nth-child in tables tr td

html

<tr>
    <td>&nbsp;</td>
    <td data-rel='$'>$</td>
    <td>&nbsp;</td>
</tr>

css

table tr td[data-rel='$'] {
    background-color: #333;
    color: white;
}

Please try these example.

_x000D_
_x000D_
table tr td[data-content='$'] {_x000D_
    background-color: #333;_x000D_
    color: white;_x000D_
}
_x000D_
<table border="1">_x000D_
    <tr>_x000D_
        <td>A</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>B</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>C</td>_x000D_
        <td data-content='$'>$</td>_x000D_
        <td>D</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to create and write to a txt file using VBA

Use FSO to create the file and write to it.

Dim fso as Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim oFile as Object
Set oFile = FSO.CreateTextFile(strPath)
oFile.WriteLine "test" 
oFile.Close
Set fso = Nothing
Set oFile = Nothing    

See the documentation here:

Parse json string to find and element (key / value)

You want to convert it to an object first and then access normally making sure to cast it.

JObject obj = JObject.Parse(json);
string name = (string) obj["Name"];

Using jQuery To Get Size of Viewport

Please note that CSS3 viewport units (vh,vw) wouldn't play well on iOS When you scroll the page, viewport size is somehow recalculated and your size of element which uses viewport units also increases. So, actually some javascript is required.

How to print something to the console in Xcode?

You can also use breakpoints. Assuming the value you want is defined within the scope of your breakpoint you have 3 options:

print it in console doing:

po some_paramter

Bare in mind in objective-c for properties you can't use self.

po _someProperty
po self.someProperty // would not work

po stands for print object.


Or can just use Xcode 'Variable Views' . See the image enter image description here

I highly recommend seeing Debugging with Xcode from Apple


Or just hover over within your code. Like the image below.

enter image description here

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

so its true, just add a primary key

Note: be sure that when you're updating your EF diagram from the database that you're pointing to the right database, in my case the connection string was pointing to a local DB instead of the up-to-date Dev DB, schoolboy error i know, but I wanted to post this because it can be very frustrating if you're convinced you've added the primary key and you're still getting the same error

How can you encode a string to Base64 in JavaScript?

While a bit more work, if you want a high performance native solution there are some HTML5 functions you can use.

If you can get your data into a Blob, then you can use the FileReader.readAsDataURL() function to get a data:// URL and chop off the front of it to get at the base64 data.

You may have to do further processing however to urldecode the data, as I'm not sure whether + characters are escaped or not for the data:// URL, but this should be pretty trivial.

How to get HQ youtube thumbnails?

Are you referring to the full resolution one?:

https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

I don't believe you can get 'multiple' images of HQ because the one you have is the one.

Check the following answer out for more information on the URLs: How do I get a YouTube video thumbnail from the YouTube API?

For live videos use https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault_live.jpg

- cornips

Determine path of the executing script

I liked steamer25's solution as it seems the most robust for my purposes. However, when debugging in RStudio (in windows), the path would not get set properly. The reason being that if a breakpoint is set in RStudio, sourcing the file uses an alternate "debug source" command which sets the script path a little differently. Here is the final version which I am currently using which accounts for this alternate behavior within RStudio when debugging:

# @return full path to this script
get_script_path <- function() {
    cmdArgs = commandArgs(trailingOnly = FALSE)
    needle = "--file="
    match = grep(needle, cmdArgs)
    if (length(match) > 0) {
        # Rscript
        return(normalizePath(sub(needle, "", cmdArgs[match])))
    } else {
        ls_vars = ls(sys.frames()[[1]])
        if ("fileName" %in% ls_vars) {
            # Source'd via RStudio
            return(normalizePath(sys.frames()[[1]]$fileName)) 
        } else {
            # Source'd via R console
            return(normalizePath(sys.frames()[[1]]$ofile))
        }
    }
}

How to retrieve the hash for the current commit in Git?

git show-ref --head --hash head

If you're going for speed though, the approach mentioned by Deestan

cat .git/refs/heads/<branch-name>

is significantly faster than any other method listed here so far.

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

Leave you stuff there and Try the following as well:

Start > Right-click on My computer > Properties > Advanced system settings > Environment Variables > look for variable name called "Path" in the lower box

set path value value as: (you can just add it to the starting of line, don't forgot semi column in between )

c:\Program Files\java\jre7\bin

IntelliJ: Never use wildcard imports

Like a dum-dum I couldn't figure out why none of these answers were working for my Kotlin files for java.util.*, so if this is happening to you then:

Preferences
> Editor
> Code Style
> **Kotlin**
> Imports
> Packages to Use Import with '*'
-> Remove 'java.util.*'

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

In my case I have replaced my build.gradle file this line

implementation 'com.google.firebase:firebase-core:16.0.8'

with

implementation 'com.google.firebase:firebase-core:15.0.0' 

and added this line

implementation 'com.google.android.gms:play-services-location:15.0.0'

Now its fine

updating table rows in postgres using subquery

@Mayur "4.2 [Using query with complex JOIN]" with Common Table Expressions (CTEs) did the trick for me.

WITH cte AS (
SELECT e.id, e.postcode
FROM employees e
LEFT JOIN locations lc ON lc.postcode=cte.postcode
WHERE e.id=1
)
UPDATE employee_location SET lat=lc.lat, longitude=lc.longi
FROM cte
WHERE employee_location.id=cte.id;

Hope this helps... :D

Restart pods when configmap updates in Kubernetes?

Had this problem where the Deployment was in a sub-chart and the values controlling it were in the parent chart's values file. This is what we used to trigger restart:

spec:
  template:
    metadata:
      annotations:
        checksum/config: {{ tpl (toYaml .Values) . | sha256sum }}

Obviously this will trigger restart on any value change but it works for our situation. What was originally in the child chart would only work if the config.yaml in the child chart itself changed:

    checksum/config: {{ include (print $.Template.BasePath "/config.yaml") . | sha256sum }}

how to add background image to activity?

Place the Image in the folder drawable. drawable folder is in res. drawable have 5 variants drawable-hdpi drawable-ldpi drawable-mdpi drawable-xhdpi drawable-xxhdpi

How to create unit tests easily in eclipse

You can use my plug-in to create tests easily:

  1. highlight the method
  2. press Ctrl+Alt+Shift+U
  3. it will create the unit test for it.

The plug-in is available here. Hope this helps.

How to import component into another root component in Angular 2

For Angular RC5 and RC6 you have to declare component in the module metadata decorator's declarations key, so add CoursesComponent in your main module declarations as below and remove directives from AppComponent metadata.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { CoursesComponent } from './courses.component';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent, CoursesComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Why does git status show branch is up-to-date when changes exist upstream?

This is because your local repo hasn't checked in with the upstream remotes. To have this work as you're expecting it to, use git fetch then run a git status again.

Good PHP ORM Library?

A really good simple ORM is MyActiveRecord. MyActiveRecord documentation. I have been using it a lot and can say it's very simple and well tested.

Show datalist labels but submit the actual value

When clicking on the button for search you can find it without a loop.
Just add to the option an attribute with the value you need (like id) and search for it specific.

$('#search_wrapper button').on('click', function(){
console.log($('option[value="'+ 
$('#autocomplete_input').val() +'"]').data('value'));
})

What is Domain Driven Design?

DDD(domain driven design) is a useful concept for analyse of requirements of a project and handling the complexity of these requirements.Before that people were analysing these requirements with considering the relationships between classes and tables and in fact their design were based on database tables relationships it is not old but it has some problems:

  • In big projects with complex requirements it is not useful although this is a great way of design for small projects.

  • when you are dealing with none technical persons that they don,t have technical concept, this conflict may cause some huge problems in our project.

So DDD handle the first problem with considering the main project as a Domain and splitting each part of this project to small pieces which we are famous to Bounded Context and each of them do not have any influence on other pieces. And the second problem has been solved with a ubiquitous language which is a common language between technical team members and Product owners which are not technical but have enough knowledge about their requirements

Generally the simple definition for Domain is the main project that makes money for the owners and other teams.

Unable to open debugger port in IntelliJ IDEA

This happens when you have application running on the same port number. One way to do this by killing the process forcefully. Open command prompt as an admin. Run command 'taskkill /IM "java.exe" /F'. This worked for me in Windows. Let me know if this works.

Styling multi-line conditions in 'if' statements?

(I've lightly modified the identifiers as fixed-width names aren't representative of real code – at least not real code that I encounter – and will belie an example's readability.)

if (cond1 == "val1" and cond22 == "val2"
and cond333 == "val3" and cond4444 == "val4"):
    do_something

This works well for "and" and "or" (it's important that they're first on the second line), but much less so for other long conditions. Fortunately, the former seem to be the more common case while the latter are often easily rewritten with a temporary variable. (It's usually not hard, but it can be difficult or much less obvious/readable to preserve the short-circuiting of "and"/"or" when rewriting.)

Since I found this question from your blog post about C++, I'll include that my C++ style is identical:

if (cond1 == "val1" and cond22 == "val2"
and cond333 == "val3" and cond4444 == "val4") {
    do_something
}

What is the difference between __init__ and __call__?

__init__ is a special method in Python classes, it is the constructor method for a class. It is called whenever an object of the class is constructed or we can say it initialises a new object. Example:

    In [4]: class A:
   ...:     def __init__(self, a):
   ...:         print(a)
   ...:
   ...: a = A(10) # An argument is necessary
10

If we use A(), it will give an error TypeError: __init__() missing 1 required positional argument: 'a' as it requires 1 argument a because of __init__ .

........

__call__ when implemented in the Class helps us invoke the Class instance as a function call.

Example:

In [6]: class B:
   ...:     def __call__(self,b):
   ...:         print(b)
   ...:
   ...: b = B() # Note we didn't pass any arguments here
   ...: b(20)   # Argument passed when the object is called
   ...:
20

Here if we use B(), it runs just fine because it doesn't have an __init__ function here.

Authorize a non-admin developer in Xcode / Mac OS

Ned Deily's solution works perfectly fine, provided your user is allowed to sudo.

If he's not, you can su to an admin account, then use his dscl . append /Groups/_developer GroupMembership $user, where $user is the username.

However, I mistakenly thought it did not because I wrongly typed in the user's name in the command and it silently fails.

Therefore, after entering this command, you should proof-check it. This will check if $user is in $group, where the variables represent respectively the user name and the group name.

dsmemberutil checkmembership -U $user -G $group

This command will either print the message user is not a member of the group or user is a member of the group.

Why is it important to override GetHashCode when Equals method is overridden?

You should always guarantee that if two objects are equal, as defined by Equals(), they should return the same hash code. As some of the other comments state, in theory this is not mandatory if the object will never be used in a hash based container like HashSet or Dictionary. I would advice you to always follow this rule though. The reason is simply because it is way too easy for someone to change a collection from one type to another with the good intention of actually improving the performance or just conveying the code semantics in a better way.

For example, suppose we keep some objects in a List. Sometime later someone actually realizes that a HashSet is a much better alternative because of the better search characteristics for example. This is when we can get into trouble. List would internally use the default equality comparer for the type which means Equals in your case while HashSet makes use of GetHashCode(). If the two behave differently, so will your program. And bear in mind that such issues are not the easiest to troubleshoot.

I've summarized this behavior with some other GetHashCode() pitfalls in a blog post where you can find further examples and explanations.

How to style UITextview to like Rounded Rect text field?

Edit: You have to import

#import <QuartzCore/QuartzCore.h>

for using corner radius.

Try this it will work for sure

UITextView* txtView = [[UITextView alloc] initWithFrame:CGRectMake(50, 50, 300, 100)];
txtView.layer.cornerRadius = 5.0;
txtView.clipsToBounds = YES;

As Rob figured it out setting the if you want the border color to be similar as UITextField then you need to change the border width to 2.0 and color to gray by adding the following line

[textView.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.5] CGColor]]; 
[textView.layer setBorderWidth:2.0];

Where can I find documentation on formatting a date in JavaScript?

You can just expand the Date Object with a new format method as noted by meizz, below is the code given by the author. And here is a jsfiddle.

Date.prototype.format = function(format) //author: meizz
{
  var o = {
    "M+" : this.getMonth()+1, //month
    "d+" : this.getDate(),    //day
    "h+" : this.getHours(),   //hour
    "m+" : this.getMinutes(), //minute
    "s+" : this.getSeconds(), //second
    "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
    "S" : this.getMilliseconds() //millisecond
  }

  if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
    (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  for(var k in o)if(new RegExp("("+ k +")").test(format))
    format = format.replace(RegExp.$1,
      RegExp.$1.length==1 ? o[k] :
        ("00"+ o[k]).substr((""+ o[k]).length));
  return format;
}

alert(new Date().format("yyyy-MM-dd"));
alert(new Date("january 12 2008 11:12:30").format("yyyy-MM-dd h:mm:ss"));

javascript date to string

A little bit simpler using regex and toJSON().

var now = new Date();
var timeRegex = /^.*T(\d{2}):(\d{2}):(\d{2}).*$/
var dateRegex = /^(\d{4})-(\d{2})-(\d{2})T.*$/
var dateData = dateRegex.exec(now.toJSON());
var timeData = timeRegex.exec(now.toJSON());
var myFormat = dateData[1]+dateData[2]+dateData[3]+timeData[1]+timeData[2]+timeData[3]

Which at the time of writing gives you "20151111180924".

The good thing of using toJSON() is that everything comes already padded.

Using HttpClient and HttpPost in Android with post parameters

have you tried doing it without the JSON object and just passed two basicnamevaluepairs? also, it might have something to do with your serversettings

Update: this is a piece of code I use:

InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate)); 

try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(connection);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.d("HTTP", "HTTP: OK");
    } catch (Exception e) {
        Log.e("HTTP", "Error in http connection " + e.toString());
    }

How to draw a dotted line with css?

For example:

hr {
  border:none;
  border-top:1px dotted #f00;
  color:#fff;
  background-color:#fff;
  height:1px;
  width:50%;
}

See also Styling <hr> with CSS.

How do I round to the nearest 0.5?

Multiply by 2, round, then divide by 2

if you want nearest quarter, multiply by 4, divide by 4, etc

Browse and display files in a git repo without cloning

While you have to checkout a repository, you can skip checking out any files with --no-checkout and --depth 1:

$ time git clone --no-checkout --depth 1 https://github.com/torvalds/linux .
Cloning into '.'...
remote: Enumerating objects: 75646, done.
remote: Counting objects: 100% (75646/75646), done.
remote: Compressing objects: 100% (71197/71197), done.
remote: Total 75646 (delta 6176), reused 22237 (delta 3672), pack-reused 0
Receiving objects: 100% (75646/75646), 201.46 MiB | 7.27 MiB/s, done.
Resolving deltas: 100% (6176/6176), done.

real    0m46.117s
user    0m13.412s
sys     0m19.641s

And while there is only a .git directory:

$ ls -al
total 0
drwxr-xr-x   3 root  staff    96 Dec 26 23:57 .
drwxr-xr-x+ 71 root  staff  2272 Dec 27 00:03 ..
drwxr-xr-x  12 root  staff   384 Dec 26 23:58 .git

you can get a directory listing via:

$ git ls-tree --full-name --name-only -r HEAD | head
.clang-format
.cocciconfig
.get_maintainer.ignore
.gitattributes
.gitignore
.mailmap
COPYING
CREDITS
Documentation/.gitignore
Documentation/ABI/README

or get the number of files via:

$ git ls-tree -r HEAD | wc -l
   71259

or get the total file size via:

$ git ls-tree -l -r HEAD | awk '/^[^-]/ {s+=$4} END {print s}'
1006679487

C++ cast to derived class

Think like this:

class Animal { /* Some virtual members */ };
class Dog: public Animal {};
class Cat: public Animal {};


Dog     dog;
Cat     cat;
Animal& AnimalRef1 = dog;  // Notice no cast required. (Dogs and cats are animals).
Animal& AnimalRef2 = cat;
Animal* AnimalPtr1 = &dog;
Animal* AnimlaPtr2 = &cat;

Cat&    catRef1 = dynamic_cast<Cat&>(AnimalRef1);  // Throws an exception  AnimalRef1 is a dog
Cat*    catPtr1 = dynamic_cast<Cat*>(AnimalPtr1);  // Returns NULL         AnimalPtr1 is a dog
Cat&    catRef2 = dynamic_cast<Cat&>(AnimalRef2);  // Works
Cat*    catPtr2 = dynamic_cast<Cat*>(AnimalPtr2);  // Works

// This on the other hand makes no sense
// An animal object is not a cat. Therefore it can not be treated like a Cat.
Animal  a;
Cat&    catRef1 = dynamic_cast<Cat&>(a);    // Throws an exception  Its not a CAT
Cat*    catPtr1 = dynamic_cast<Cat*>(&a);   // Returns NULL         Its not a CAT.

Now looking back at your first statement:

Animal   animal = cat;    // This works. But it slices the cat part out and just
                          // assigns the animal part of the object.
Cat      bigCat = animal; // Makes no sense.
                          // An animal is not a cat!!!!!
Dog      bigDog = bigCat; // A cat is not a dog !!!!

You should very rarely ever need to use dynamic cast.
This is why we have virtual methods:

void makeNoise(Animal& animal)
{
     animal.DoNoiseMake();
}

Dog    dog;
Cat    cat;
Duck   duck;
Chicken chicken;

makeNoise(dog);
makeNoise(cat);
makeNoise(duck);
makeNoise(chicken);

The only reason I can think of is if you stored your object in a base class container:

std::vector<Animal*>  barnYard;
barnYard.push_back(&dog);
barnYard.push_back(&cat);
barnYard.push_back(&duck);
barnYard.push_back(&chicken);

Dog*  dog = dynamic_cast<Dog*>(barnYard[1]); // Note: NULL as this was the cat.

But if you need to cast particular objects back to Dogs then there is a fundamental problem in your design. You should be accessing properties via the virtual methods.

barnYard[1]->DoNoiseMake();

Fatal error: Call to a member function bind_param() on boolean

Another situation that can cause this problem is incorrect casting in your queries.

I know it may sound obvious, but I have run into this by using tablename instead of Tablename. Check your queries, and make sure that you're using the same case as the actual names of the columns in your table.

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

When the user session times out, I send back an HTTP 204 status code. Note that the HTTP 204 status contains no content. On the client-side I do this:

xhr.send(null);
if (xhr.status == 204) 
    Reload();
else 
    dropdown.innerHTML = xhr.responseText;

Here is the Reload() function:

function Reload() {
    var oForm = document.createElement("form");
    document.body.appendChild(oForm);
    oForm.submit();
    }

Converting an int to a binary string representation in Java?

public class Main  {

   public static String toBinary(int n, int l ) throws Exception {
       double pow =  Math.pow(2, l);
       StringBuilder binary = new StringBuilder();
        if ( pow < n ) {
            throw new Exception("The length must be big from number ");
        }
       int shift = l- 1;
       for (; shift >= 0 ; shift--) {
           int bit = (n >> shift) & 1;
           if (bit == 1) {
               binary.append("1");
           } else {
               binary.append("0");
           }
       }
       return binary.toString();
   }

    public static void main(String[] args) throws Exception {
        System.out.println(" binary = " + toBinary(7, 4));
        System.out.println(" binary = " + Integer.toString(7,2));
    }
}

Constructor overload in TypeScript

We can simulate constructor overload using guards

interface IUser {
  name: string;
  lastName: string;
}

interface IUserRaw {
  UserName: string;
  UserLastName: string;
}

function isUserRaw(user): user is IUserRaw {
  return !!(user.UserName && user.UserLastName);
}

class User {
  name: string;
  lastName: string;

  constructor(data: IUser | IUserRaw) {
    if (isUserRaw(data)) {
      this.name = data.UserName;
      this.lastName = data.UserLastName;
    } else {
      this.name = data.name;
      this.lastName = data.lastName;
    }
  }
}

const user  = new User({ name: "Jhon", lastName: "Doe" })
const user2 = new User({ UserName: "Jhon", UserLastName: "Doe" })

Why should you use strncpy instead of strcpy?

strncpy is NOT safer than strcpy, it just trades one type of bugs with another. In C, when handling C strings, you need to know the size of your buffers, there is no way around it. strncpy was justified for the directory thing mentioned by others, but otherwise, you should never use it:

  • if you know the length of your string and buffer, why using strncpy ? It is a waste of computing power at best (adding useless 0)
  • if you don't know the lengths, then you risk silently truncating your strings, which is not much better than a buffer overflow

How to use <md-icon> in Angular Material?

The simplest way today would be to simply request the Material Icons font from Google Fonts, for example in your HTML header tag:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

or in your stylesheet:

@import url(https://fonts.googleapis.com/icon?family=Material+Icons);

and then use as font icon with ligatures as explained in the md-icon directive. For example:

<md-icon aria-label="Menu" class="material-icons">menu</md-icon>

The complete list of icons/ligatures is at https://www.google.com/design/icons/

Fastest way to set all values of an array?

As of Java-8, there are four variants of the setAll method which sets all elements of the specified array, using a provided generator function to compute each element.

Of those four overloads only three of them accept an array of primitives declared as such:





Examples of how to use the aforementioned methods:

// given an index, set the element at the specified index with the provided value
double [] doubles = new double[50];
Arrays.setAll(doubles, index -> 30D);

// given an index, set the element at the specified index with the provided value
int [] ints = new int[50];
Arrays.setAll(ints, index -> 60);

 // given an index, set the element at the specified index with the provided value
long [] longs = new long[50];
Arrays.setAll(longs, index -> 90L);

The function provided to the setAll method receives the element index and returns a value for that index.

you may be wondering how about characters array?

This is where the fourth overload of the setAll method comes into play. As there is no overload that consumes an array of character primitives, the only option we have is to change the declaration of our character array to a type Character[].

If changing the type of the array to Character is not appropriate then you can fall back to the Arrays.fill method.

Example of using the setAll method with Character[]:

// given an index, set the element at the specified index with the provided value
Character[] character = new Character[50];
Arrays.setAll(characters, index -> '+'); 

Although, it's simpler to use the Arrays.fill method rather than the setAll method to set a specific value.

The setAll method has the advantage that you can either set all the elements of the array to have the same value or generate an array of even numbers, odd numbers or any other formula:

e.g.

int[] evenNumbers = new int[10]; 
Arrays.setAll(evenNumbers, i -> i * 2);

There's also several overloads of the parallelSetAll method which is executed in parallel, although it's important to note that the function passed to the parallelSetAll method must be side-effect free.

Conclusion

If your goal is simply to set a specific value for each element of the array then using the Arrays.fill overloads would be the most appropriate option. However, if you want to be more flexible or generate elements on demand then using the Arrays.setAll or Arrays.parallelSetAll (when appropriate) would be the option to go for.

When to use static methods

Whenever you do not want to create an object to call a method in your code just declare that method as static. Since the static method does not need an instance to be called with but the catch here is not all static methods are called by JVM automatically. This privilege is enjoyed only by the main() "public static void main[String... args]" method in java because at Runtime this is the method Signature public "static" void main[] sought by JVM as an entry point to start execution of the code.

Example:

public class Demo
{
   public static void main(String... args) 
   {
      Demo d = new Demo();

      System.out.println("This static method is executed by JVM");

     //Now to call the static method Displ() you can use the below methods:
           Displ(); //By method name itself    
      Demo.Displ(); //By using class name//Recommended
         d.Displ(); //By using instance //Not recommended
   }

   public static void Displ()
   {
      System.out.println("This static method needs to be called explicitly");
   }
} 

Output:- This static method is executed by JVM This static method needs to be called explicitly This static method needs to be called explicitly This static method needs to be called explicitly

Automatically plot different colored lines

You could use a colormap such as HSV to generate a set of colors. For example:

cc=hsv(12);
figure; 
hold on;
for i=1:12
    plot([0 1],[0 i],'color',cc(i,:));
end

MATLAB has 13 different named colormaps ('doc colormap' lists them all).

Another option for plotting lines in different colors is to use the LineStyleOrder property; see Defining the Color of Lines for Plotting in the MATLAB documentation for more information.

how to increase the limit for max.print in R

See ?options:

options(max.print=999999)

How do I remove the first characters of a specific column in a table?

If you have to remove the first few characters that are preceded by a special character like #, this is a good one:

UPDATE tblInvalidID
SET [ColumnName] =stuff(ColumnName, 1, charindex('#', ColumnName), ' ')