Programs & Examples On #Displayattribute

displayname attribute vs display attribute

DisplayName sets the DisplayName in the model metadata. For example:

[DisplayName("foo")]
public string MyProperty { get; set; }

and if you use in your view the following:

@Html.LabelFor(x => x.MyProperty)

it would generate:

<label for="MyProperty">foo</label>

Display does the same, but also allows you to set other metadata properties such as Name, Description, ...

Brad Wilson has a nice blog post covering those attributes.

How to get the Display Name Attribute of an Enum member via MVC Razor code?

I tried doing this as an edit but it was rejected; I can't see why.

The above will throw an exception if you call it with an Enum that has a mix of custom attributes and plain items, e.g.

public enum CommentType
{
    All = 1,
    Rent = 2,
    Insurance = 3,
    [Display(Name="Service Charge")]
    ServiceCharge = 4
}

So I've modified the code ever so slightly to check for custom attributes before trying to access them, and use the name if none are found.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;

public static class EnumHelper<T>
{
    public static IList<T> GetValues(Enum value)
    {
        var enumValues = new List<T>();

        foreach (FieldInfo fi in value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public))
        {
            enumValues.Add((T)Enum.Parse(value.GetType(), fi.Name, false));
        }
        return enumValues;
    }

    public static T Parse(string value)
    {
        return (T)Enum.Parse(typeof(T), value, true);
    }

    public static IList<string> GetNames(Enum value)
    {
        return value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public).Select(fi => fi.Name).ToList();
    }

    public static IList<string> GetDisplayValues(Enum value)
    {
        return GetNames(value).Select(obj => GetDisplayValue(Parse(obj))).ToList();
    }

    private static string lookupResource(Type resourceManagerProvider, string resourceKey)
    {
        foreach (PropertyInfo staticProperty in resourceManagerProvider.GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public))
        {
            if (staticProperty.PropertyType == typeof(System.Resources.ResourceManager))
            {
                System.Resources.ResourceManager resourceManager = (System.Resources.ResourceManager)staticProperty.GetValue(null, null);
                return resourceManager.GetString(resourceKey);
            }
        }

        return resourceKey; // Fallback with the key name
    }

    public static string GetDisplayValue(T value)
    {
        var fieldInfo = value.GetType().GetField(value.ToString());

        var descriptionAttributes = fieldInfo.GetCustomAttributes(
            typeof(DisplayAttribute), false) as DisplayAttribute[];

        if (descriptionAttributes.Any() && descriptionAttributes[0].ResourceType != null)
            return lookupResource(descriptionAttributes[0].ResourceType, descriptionAttributes[0].Name);

        if (descriptionAttributes == null) return string.Empty;
        return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString();
    }
}

Limiting double to 3 decimal places

Doubles don't have decimal places - they're not based on decimal digits to start with. You could get "the closest double to the current value when truncated to three decimal digits", but it still wouldn't be exactly the same. You'd be better off using decimal.

Having said that, if it's only the way that rounding happens that's a problem, you can use Math.Truncate(value * 1000) / 1000; which may do what you want. (You don't want rounding at all, by the sounds of it.) It's still potentially "dodgy" though, as the result still won't really just have three decimal places. If you did the same thing with a decimal value, however, it would work:

decimal m = 12.878999m;
m = Math.Truncate(m * 1000m) / 1000m;
Console.WriteLine(m); // 12.878

EDIT: As LBushkin pointed out, you should be clear between truncating for display purposes (which can usually be done in a format specifier) and truncating for further calculations (in which case the above should work).

How to open specific tab of bootstrap nav tabs on click of a particuler link using jQuery?

May I suggest a php+css solution I used on my site? It's simple and no js problems :)

url to page: <a href="page.php?tab=menu1">link to menu1</a>

<?
$tab = $_GET['tab'];
?>
<ul class="nav nav-tabs">
  <li class="<? if ($tab=='menu1' OR $tab=='menu2') 
{
echo "";
} 
else {
echo "active";
}
?>"><a data-toggle="tab" href="#home">Prodotti</a></li>
  <li class="<? if ($tab=='menu1') 
{
echo "active";
} 
?>"><a data-toggle="tab" href="#menu1">News</a></li>
  <li class="<? if ($tab=='menu2') 
{
echo "active";
} 
?>"><a data-toggle="tab" href="#menu2">Gallery</a></li>
</ul>

<div class="tab-content">
  <div id="home" class="tab-pane fade <? if ($tab=='menu1' OR $tab=='menu2') 
{
echo "";
} 
else {
echo "in active";
}
?>
">
    <h3>Prodotti</h3>
    <p>Contenuto della pagina, zona prodotti</p>
  </div>
  <div id="menu1" class="tab-pane fade <? if ($tab=='menu1') 
{
echo "in active";
} 
?>">
    <h3>News</h3>
    <p>Qui ci saranno le news.</p>
  </div>
  <div id="menu2" class="tab-pane fade <? if ($tab=='menu2') 
{
echo "in active";
} 
?>">
    <h3>Gallery</h3>
    <p>Qui ci sarà la gallery</p>
  </div>
</div>

Hide/Show Action Bar Option Menu Item for different fragments

By setting the Visibility of all items in Menu, the appbar menu or overflow menu will be Hide automatically

Example

 private Menu menu_change_language;
 ...
 ...
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
    ...
    ...
    menu_change_language = menu;
   menu_change_language.findItem(R.id.menu_change_language).setVisible(true);

    return super.onCreateOptionsMenu(menu);
}

Before going to other fragment use bellow code:

if(menu_change_language != null){                 
 menu_change_language.findItem(R.id.menu_change_language)
  .setVisible(false);
}

How to convert String to Date value in SAS?

This code helps:

data final; set final;

first_date = INPUT(compress(char_date),date9.); format first_date date9.;

run;

I personally have tried it on SAS

When to use RDLC over RDL reports?

For VS2008, I believe RDL gives you better editing features than RDLC. For example, I can change the Bold on a selected amount of text in a textbox with RDL, while in RDLC it's is not possible.

RDL: abcd efgh ijklmnop

RDLC: abcd efgh ijklmnop -or- abcd efgh ijklmnop (are your only options)

This is because RDLC is using a earlier namespace/formatting from 2005, while RDL is using 2008. This however will change with VS2010

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

I think that all the answers missed a crucial point:

If you use the Ajax form so that it needs to update itself (and NOT another div outside of the form) then you need to put the containing div OUTSIDE of the form. For example:

 <div id="target">
 @using (Ajax.BeginForm("MyAction", "MyController",
            new AjaxOptions
            {
                HttpMethod = "POST",
                InsertionMode = InsertionMode.Replace,
                UpdateTargetId = "target"
            }))
 {
      <!-- whatever -->
 }
 </div>

Otherwise you will end like @David where the result is displayed in a new page.

Cannot checkout, file is unmerged

In my case, I found that I need the -f option. Such as the following:

git rm -f first_file.txt

to get rid of the "needs merge" error.

Remove Select arrow on IE

In IE9, it is possible with purely a hack as advised by @Spudley. Since you've customized height and width of the div and select, you need to change div:before css to match yours.

In case if it is IE10 then using below css3 it is possible

select::-ms-expand {
    display: none;
}

However if you're interested in jQuery plugin, try Chosen.js or you can create your own in js.

Multithreading in Bash

Bash job control involves multiple processes, not multiple threads.

You can execute a command in background with the & suffix.

You can wait for completion of a background command with the wait command.

You can execute multiple commands in parallel by separating them with |. This provides also a synchronization mechanism, since stdout of a command at left of | is connected to stdin of command at right.

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

Print page numbers on pages when printing html

Try to use https://www.pagedjs.org/. It polyfills page counter, header-/footer-functionality for all major browsers.

@page {
  @bottom-left {
    content: counter(page) ' of ' counter(pages);
  }
}

It's so much more comfortable compared to alternatives like PrinceXML, Antennahouse, WeasyPrince, PDFReactor, etc ...

And it is totally free! No pricing or whatever. It really saved my life!

Removing MySQL 5.7 Completely

First of all, do a backup of your needed databases with mysqldump

Note: If you want to restore later, just backup your relevant databases, and not the WHOLE, because the whole database might actually be the reason you need to purge and reinstall).

In total, do this:

sudo service mysql stop  #or mysqld
sudo killall -9 mysql
sudo killall -9 mysqld
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
sudo deluser -f mysql
sudo rm -rf /var/lib/mysql
sudo apt-get purge mysql-server-core-5.7
sudo apt-get purge mysql-client-core-5.7
sudo rm -rf /var/log/mysql
sudo rm -rf /etc/mysql

All above commands in single line (just copy and paste):

sudo service mysql stop && sudo killall -9 mysql && sudo killall -9 mysqld && sudo apt-get remove --purge mysql-server mysql-client mysql-common && sudo apt-get autoremove && sudo apt-get autoclean && sudo deluser mysql && sudo rm -rf /var/lib/mysql && sudo apt-get purge mysql-server-core-5.7 && sudo apt-get purge mysql-client-core-5.7 && sudo rm -rf /var/log/mysql && sudo rm -rf /etc/mysql

Write variable to file, including name

1) Make the dictionary:

X = {'a': 1}

2) Write to a new file:

file = open('X_Data.py', 'w')
file.write(str(X))
file.close()

Lastly, in the file that you want the variable to be, read that file and make a new variable with the data from the data file:

import ast
file = open('X_Data.py', 'r')
f = file.read()
file.close()
X = ast.literal_eval(f)

npx command not found

check versions of node, npm, npx as given below. if npx is not installed then use npm i -g npx

node -v
npm -v
npx -v

Multiple conditions in WHILE loop

You need to change || to && so that both conditions must be true to enter the loop.

while(myChar != 'n' && myChar != 'N')

Switch statement fall-through...should it be allowed?

In some instances, using fall-throughs is an act of laziness on the part of the programmer - they could use a series of || statements, for example, but instead use a series of 'catch-all' switch cases.

That being said, I've found them to be especially helpful when I know that eventually I'm going to need the options anyway (for example in a menu response), but have not yet implemented all the choices. Likewise, if you're doing a fall-through for both 'a' and 'A', I find it substantially cleaner to use the switch fall-through than a compound if statement.

It's probably a matter of style and how the programmers think, but I'm not generally fond of removing components of a language in the name of 'safety' - which is why I tend towards C and its variants/descendants more than, say, Java. I like being able to monkey-around with pointers and the like, even when I have no "reason" to.

"multiple target patterns" Makefile error

I just want to add, if you get this error because you are using Cygwin make and auto-generated files, you can fix it with the following sed,

sed -e 's@\\\([^ ]\)@/\1@g' -e 's@[cC]:@/cygdrive/c@' -i filename.d

You may need to add more characters than just space to the escape list in the first substitution but you get the idea. The concept here is that /cygdrive/c is an alias for c: that cygwin's make will recognize.

And may as well throw in

-e 's@^ \+@\t@'

just in case you did start with spaces on accident (although I /think/ this will usually be a "missing separator" error).

How to enter special characters like "&" in oracle database?

To Insert values which has got '&' in it. Use the folloiwng code.

Set define off;

Begin

INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', 'Java_22 & Oracle_14');

End ;

And Press F5 from Oracle or Toad Editors.

How do you explicitly set a new property on `window` in TypeScript?

I wanted to use this in an Angular (6) library today and it took me a while to get this to work as expected.

In order for my library to use declarations I had to use the d.ts extention for the file that declares the new properties of the global object.

So in the end, the file ended up with something like:

/path-to-angular-workspace/angular-workspace/projects/angular-library/src/globals.d.ts

Once created, don't forget to expose it in your public_api.ts.

That did it for me. Hope this helps.

Can't create project on Netbeans 8.2

Java SE Development Kit 9 is not compatible with the Netbeans IDE 8.2.

My Solution:

  1. Delete the current JDK 9
  2. Install this previous trust version of JDK: JDK 8
  3. Modify the following file: \Program Files\NetBeans 8.2\etc\netbeans.conf to the given folder path of the newly installed JDK 8: netbeans_jdkhome="C:\Program Files\Java\jdk1.8.0_151" (example)

How to print a query string with parameter values when using Hibernate

Change hibernate.cfg.xml to:

<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>

Include log4j and below entries in "log4j.properties":

log4j.logger.org.hibernate=INFO, hb
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE

log4j.appender.hb=org.apache.log4j.ConsoleAppender
log4j.appender.hb.layout=org.apache.log4j.PatternLayout

How can I pass an Integer class correctly by reference?

The Integer is immutable. You can wrap int in your custom wrapper class.

class WrapInt{
    int value;
}

WrapInt theInt = new WrapInt();

inc(theInt);
System.out.println("main: "+theInt.value);

Set start value for column with autoincrement

You need to set the Identity seed to that value:

CREATE TABLE orders
(
 id int IDENTITY(9586,1)
)

To alter an existing table:

ALTER TABLE orders ALTER COLUMN Id INT IDENTITY (9586, 1);

More info on CREATE TABLE (Transact-SQL) IDENTITY (Property)

C# listView, how do I add items to columns 2, 3 and 4 etc?

You can add items / sub-items to the ListView like:

ListViewItem item = new ListViewItem(new []{"1","2","3","4"});
listView1.Items.Add(item);

But I suspect your problem is with the View Type. Set it in the designer to Details or do the following in code:

listView1.View = View.Details;

Why does Git tell me "No such remote 'origin'" when I try to push to origin?

I'm guessing you didn't run this command after the commit failed so just actually run this to create the remote :

 git remote add origin https://github.com/VijayNew/NewExample.git

And the commit failed because you need to git add some files you want to track.

Sort arrays of primitive types in descending order

Your algorithm is correct. But we can do optimization as follows: While reversing, You may try keeping another variable to reduce backward counter since computing of array.length-(i+1) may take time! And also move declaration of temp outside so that everytime it needs not to be allocated

double temp;

for(int i=0,j=array.length-1; i < (array.length/2); i++, j--) {

     // swap the elements
     temp = array[i];
     array[i] = array[j];
     array[j] = temp;
}

HTML5 iFrame Seamless Attribute

It's not supported correctly yet.

Chrome 31 (and possibly an earlier version) supports some parts of the attribute, but it is not fully supported.

How to apply border radius in IE8 and below IE8 browsers?

Firstly for technical accuracy, border-radius is not a HTML5 feature, it's a CSS3 feature.

The best script I've found to render box shadows & rounded corners in older IE versions is IE-CSS3. It translates CSS3 syntax into VML (an IE-specific Vector language like SVG) and renders them on screen.

It works a lot better on IE7-8 than on IE6, but does support IE6 as well. I didn't think much to PIE when I used it and found that (like HTC) it wasn't really built to be functional.

How to replace a string in an existing file in Perl?

$_='~s/blue/red/g';

Uh, what??

Just

s/blue/red/g;

or, if you insist on using a variable (which is not necessary when using $_, but I just want to show the right syntax):

$_ =~ s/blue/red/g;

Download multiple files with a single action

By far the easiest solution (at least in ubuntu/linux):

  • make a text file with the urls of the files to download (i.e. file.txt)
  • put the 'file.txt' in the directory where you want to download the files
  • open the terminal in the download directory from the previous lin
  • download the files with the command 'wget -i file.txt'

Works like a charm.

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

You should add namespace if you are not using it:

System.Windows.Forms.MessageBox.Show("Some text", "Some title", 
    System.Windows.Forms.MessageBoxButtons.OK, 
    System.Windows.Forms.MessageBoxIcon.Error);

Alternatively, you can add at the begining of your file:

using System.Windows.Forms

and then use (as stated in previous answers):

MessageBox.Show("Some text", "Some title", 
    MessageBoxButtons.OK, MessageBoxIcon.Error);

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application?

Option1:

To set the ASPNETCORE_ENVIRONMENT environment variable in windows,

Command line - setx ASPNETCORE_ENVIRONMENT "Development"

PowerShell - $Env:ASPNETCORE_ENVIRONMENT = "Development"

For other OS refer this - https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments

Option2:

If you want to set ASPNETCORE_ENVIRONMENT using web.config then add aspNetCore like this-

<configuration>
  <!--
    Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
  -->
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath=".\MyApplication.exe" arguments="" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false">
      <environmentVariables>
        <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" />
      </environmentVariables>
    </aspNetCore>
  </system.webServer>
</configuration>

Multi-statement Table Valued Function vs Inline Table Valued Function

Maybe in a very condensed way. ITVF ( inline TVF) : more if u are DB person, is kind of parameterized view, take a single SELECT st

MTVF ( Multi-statement TVF): Developer, creates and load a table variable.

Close Current Tab

Try this:

<script>
    var myWindow = window.open("ANYURL", "MyWindowName", "width=700,height=700");
    this.window.close();
</script>

This worked for me in some cases in Google Chrome 50. It does not seem to work when put inside a javascript function, though.

Get a resource using getResource()

One thing to keep in mind is that the relevant path here is the path relative to the file system location of your class... in your case TestGameTable.class. It is not related to the location of the TestGameTable.java file.
I left a more detailed answer here... where is resource actually located

IE prompts to open or save json result from server

Is above javascript code the one you're using in your web application ? If so - i would like to point few errors in it: firstly - it has an additional '{' sign in definition of 'success' callback function secondly - it has no ')' sign after definition of ajax callback. Valid code should look like:

$.ajax({
        type:'POST',
        data: 'args',
        url: '@Url.Action("PostBack")',
        success: function (data, textStatus, jqXHR) {
                alert(data.message);
            }
    });

try using above code - it gave me 'Yay' alert on all 3 IE versions ( 7,8,9 ).

Should I initialize variable within constructor or outside constructor

I think both are correct programming wise,

But i think your first option is more correct in an object oriented way, because in the constructor is when the object is created, and it is when the variable should initialized.

I think it is the "by the book" convention, but it is open for discussion.

Wikipedia

Can I catch multiple Java exceptions in the same catch clause?

This has been possible since Java 7. The syntax for a multi-catch block is:

try { 
  ...
} catch (IllegalArgumentException | SecurityException | IllegalAccessException |
            NoSuchFieldException e) { 
  someCode();
}

Remember, though, that if all the exceptions belong to the same class hierarchy, you can simply catch that base exception type.

Also note that you cannot catch both ExceptionA and ExceptionB in the same block if ExceptionB is inherited, either directly or indirectly, from ExceptionA. The compiler will complain:

Alternatives in a multi-catch statement cannot be related by subclassing
  Alternative ExceptionB is a subclass of alternative ExceptionA

The fix for this is to only include the ancestor exception in the exception list, as it will also catch exceptions of the descendant type.

Reading a .txt file using Scanner class in Java

  1. You need the specify the exact filename, including the file extension, e.g. 10_Random.txt.
  2. The file needs to be in the same directory as the executable if you want to refer to it without any kind of explicit path.
  3. While we're at it, you need to check for an int before reading an int. It is not safe to check with hasNextLine() and then expect an int with nextInt(). You should use hasNextInt() to check that there actually is an int to grab. How strictly you choose to enforce the one integer per line rule is up to you, of course.

Formatting struct timespec

One way to format it is:

printf("%lld.%.9ld", (long long)ts.tv_sec, ts.tv_nsec);

What does (function($) {})(jQuery); mean?

At the most basic level, something of the form (function(){...})() is a function literal that is executed immediately. What this means is that you have defined a function and you are calling it immediately.

This form is useful for information hiding and encapsulation since anything you define inside that function remains local to that function and inaccessible from the outside world (unless you specifically expose it - usually via a returned object literal).

A variation of this basic form is what you see in jQuery plugins (or in this module pattern in general). Hence:

(function($) {
  ...
})(jQuery);

Which means you're passing in a reference to the actual jQuery object, but it's known as $ within the scope of the function literal.

Type 1 isn't really a plugin. You're simply assigning an object literal to jQuery.fn. Typically you assign a function to jQuery.fn as plugins are usually just functions.

Type 2 is similar to Type 1; you aren't really creating a plugin here. You're simply adding an object literal to jQuery.fn.

Type 3 is a plugin, but it's not the best or easiest way to create one.

To understand more about this, take a look at this similar question and answer. Also, this page goes into some detail about authoring plugins.

Cell color changing in Excel using C#

For text:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

For cell background

[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

how to use json file in html code

You can use JavaScript like... Just give the proper path of your json file...

<!doctype html>
<html>
    <head>
        <script type="text/javascript" src="abc.json"></script>
        <script type="text/javascript" >
            function load() {
                var mydata = JSON.parse(data);
                alert(mydata.length);

                var div = document.getElementById('data');

                for(var i = 0;i < mydata.length; i++)
                {
                    div.innerHTML = div.innerHTML + "<p class='inner' id="+i+">"+ mydata[i].name +"</p>" + "<br>";
                }
            }
        </script>
    </head>
    <body onload="load()">
        <div id="data">

        </div>
    </body>
</html>

Simply getting the data and appending it to a div... Initially printing the length in alert.

Here is my Json file: abc.json

data = '[{"name" : "Riyaz"},{"name" : "Javed"},{"name" : "Arun"},{"name" : "Sunil"},{"name" : "Rahul"},{"name" : "Anita"}]';

Apache SSL Configuration Error (SSL Connection Error)

I encounter this problem, because I have <VirtualHost> defined both in httpd.conf and httpd-ssl.conf.

in httpd.conf, it's defined as

<VirtualHost localhost>

in httpd-ssl.conf, it's defined as

<VirtualHost _default_:443>

The following change solved this problem, add :80 in httpd.conf

<VirtualHost localhost:80>

Make ABC Ordered List Items Have Bold Style

You could do something like this also:

ol {
  font-weight: bold;
}

ol > li > * {
  font-weight: normal;
}

So you have no "style" attributes in your HTML

How-to turn off all SSL checks for postman for a specific site

enter image description here

This steps are used in spring boot with self signed ssl certificate implementation

if SSL turns off then HTTPS call will be worked as expected.

https://localhost:8443/test/hello

These are the steps we have to follow,

  1. Generate self signed ssl certificate
keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650

after key generation has done then copy that file in to the resource foder in your project

  1. add key store properties in applicaiton.properties
server.port: 8443
server.ssl.key-store:classpath:keystore.p12
server.ssl.key-store-password: test123
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat
  1. change your postman ssl verification settings to turn OFF

now verify the url: https://localhost:8443/test/hello

How to print an exception in Python?

Python 3: logging

Instead of using the basic print() function, the more flexible logging module can be used to log the exception. The logging module offers a lot extra functionality, e.g. logging messages into a given log file, logging messages with timestamps and additional information about where the logging happened. (For more information check out the official documentation.)

Logging an exception can be done with the module-level function logging.exception() like so:

import logging

try:
    1/0
except BaseException:
    logging.exception("An exception was thrown!")

Output:

ERROR:root:An exception was thrown!
Traceback (most recent call last):
  File ".../Desktop/test.py", line 4, in <module>
    1/0
ZeroDivisionError: division by zero 

Notes:

  • the function logging.exception() should only be called from an exception handler

  • the logging module should not be used inside a logging handler to avoid a RecursionError (thanks @PrakharPandey)


Alternative log-levels

It's also possible to log the exception with another log-level by using the keyword argument exc_info=True like so:

logging.debug("An exception was thrown!", exc_info=True)
logging.info("An exception was thrown!", exc_info=True)
logging.warning("An exception was thrown!", exc_info=True)

PHP form - on submit stay on same page

The best way to stay on the same page is to post to the same page:

<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">

How to frame two for loops in list comprehension python

The best way to remember this is that the order of for loop inside the list comprehension is based on the order in which they appear in traditional loop approach. Outer most loop comes first, and then the inner loops subsequently.

So, the equivalent list comprehension would be:

[entry for tag in tags for entry in entries if tag in entry]

In general, if-else statement comes before the first for loop, and if you have just an if statement, it will come at the end. For e.g, if you would like to add an empty list, if tag is not in entry, you would do it like this:

[entry if tag in entry else [] for tag in tags for entry in entries]

JFrame.dispose() vs System.exit()

JFrame.dispose() affects only to this frame (release all of the native screen resources used by this component, its subcomponents, and all children). System.exit() affects to entire JVM.

If you want to close all JFrame or all Window (since Frames extend Windows) to terminate the application in an ordered mode, you can do some like this:

Arrays.asList(Window.getWindows()).forEach(e -> e.dispose()); // or JFrame.getFrames()

Detect a finger swipe through JavaScript on the iPhone and Android

I reworked @givanse's solution to function as a React hook. Input is some optional event listeners, output is a functional ref (needs to be functional so the hook can re-run when/if the ref changes).

Also added in vertical/horizontal swipe threshold param, so that small motions don't accidentally trigger the event listeners, but these can be set to 0 to mimic original answer more closely.

Tip: for best performance, the event listener input functions should be memoized.

function useSwipeDetector({
    // Event listeners.
    onLeftSwipe,
    onRightSwipe,
    onUpSwipe,
    onDownSwipe,

    // Threshold to detect swipe.
    verticalSwipeThreshold = 50,
    horizontalSwipeThreshold = 30,
}) {
    const [domRef, setDomRef] = useState(null);
    const xDown = useRef(null);
    const yDown = useRef(null);

    useEffect(() => {
        if (!domRef) {
            return;
        }

        function handleTouchStart(evt) {
            const [firstTouch] = evt.touches;
            xDown.current = firstTouch.clientX;
            yDown.current = firstTouch.clientY;
        };

        function handleTouchMove(evt) {
            if (!xDown.current || !yDown.current) {
                return;
            }

            const [firstTouch] = evt.touches;
            const xUp = firstTouch.clientX;
            const yUp = firstTouch.clientY;
            const xDiff = xDown.current - xUp;
            const yDiff = yDown.current - yUp;

            if (Math.abs(xDiff) > Math.abs(yDiff)) {/*most significant*/
                if (xDiff > horizontalSwipeThreshold) {
                    if (onRightSwipe) onRightSwipe();
                } else if (xDiff < -horizontalSwipeThreshold) {
                    if (onLeftSwipe) onLeftSwipe();
                }
            } else {
                if (yDiff > verticalSwipeThreshold) {
                    if (onUpSwipe) onUpSwipe();
                } else if (yDiff < -verticalSwipeThreshold) {
                    if (onDownSwipe) onDownSwipe();
                }
            }
        };

        function handleTouchEnd() {
            xDown.current = null;
            yDown.current = null;
        }

        domRef.addEventListener("touchstart", handleTouchStart, false);
        domRef.addEventListener("touchmove", handleTouchMove, false);
        domRef.addEventListener("touchend", handleTouchEnd, false);

        return () => {
            domRef.removeEventListener("touchstart", handleTouchStart);
            domRef.removeEventListener("touchmove", handleTouchMove);
            domRef.removeEventListener("touchend", handleTouchEnd);
        };
    }, [domRef, onLeftSwipe, onRightSwipe, onUpSwipe, onDownSwipe, verticalSwipeThreshold, horizontalSwipeThreshold]);

    return (ref) => setDomRef(ref);
};

replace NULL with Blank value or Zero in sql server

Different ways to replace NULL in sql server

Replacing NULL value using:

1. ISNULL() function

2. COALESCE() function

3. CASE Statement

SELECT Name as EmployeeName, ISNULL(Bonus,0) as EmployeeBonus from tblEmployee

SELECT Name as EmployeeName, COALESCE(Bonus, 0) as EmployeeBonus 
FROM tblEmployee

SELECT Name as EmployeeName, CASE WHEN Bonus IS NULL THEN 0 
ELSE Bonus  END as EmployeeBonus 
FROM  tblEmployee

MySql Inner Join with WHERE clause

You are using two WHERE clauses but only one is allowed. Use it like this:

SELECT table1.f_id FROM table1
INNER JOIN table2 ON table2.f_id = table1.f_id
WHERE
  table1.f_com_id = '430'
  AND table1.f_status = 'Submitted'
  AND table2.f_type = 'InProcess'

How to read response headers in angularjs?

The response headers in case of cors remain hidden. You need to add in response headers to direct the Angular to expose headers to javascript.

// From server response headers :
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, 
Content-Type, Accept, Authorization, X-Custom-header");
header("Access-Control-Expose-Headers: X-Custom-header");
header("X-Custom-header: $some data");

var data = res.headers.get('X-Custom-header');

Source : https://github.com/angular/angular/issues/5237

pandas groupby sort within groups

Here's other example of taking top 3 on sorted order, and sorting within the groups:

In [43]: import pandas as pd                                                                                                                                                       

In [44]:  df = pd.DataFrame({"name":["Foo", "Foo", "Baar", "Foo", "Baar", "Foo", "Baar", "Baar"], "count_1":[5,10,12,15,20,25,30,35], "count_2" :[100,150,100,25,250,300,400,500]})

In [45]: df                                                                                                                                                                        
Out[45]: 
   count_1  count_2  name
0        5      100   Foo
1       10      150   Foo
2       12      100  Baar
3       15       25   Foo
4       20      250  Baar
5       25      300   Foo
6       30      400  Baar
7       35      500  Baar


### Top 3 on sorted order:
In [46]: df.groupby(["name"])["count_1"].nlargest(3)                                                                                                                               
Out[46]: 
name   
Baar  7    35
      6    30
      4    20
Foo   5    25
      3    15
      1    10
dtype: int64


### Sorting within groups based on column "count_1":
In [48]: df.groupby(["name"]).apply(lambda x: x.sort_values(["count_1"], ascending = False)).reset_index(drop=True)
Out[48]: 
   count_1  count_2  name
0       35      500  Baar
1       30      400  Baar
2       20      250  Baar
3       12      100  Baar
4       25      300   Foo
5       15       25   Foo
6       10      150   Foo
7        5      100   Foo

Python - add PYTHONPATH during command line module run

You may try this to execute a function inside your script

python -c "import sys; sys.path.append('/your/script/path'); import yourscript; yourscript.yourfunction()"

Date only from TextBoxFor()

Just add next to your model.

[DataType(DataType.Date)]
public string dtArrivalDate { get; set; }

"Android library projects cannot be launched"?

our project surely is configured as "library" thats why you get the message : "Android library projects cannot be launched."

right-click in your project and select Properties. In the Properties window -> "Android" -> uncheck the option "is Library" and apply -> Click "ok" to close the properties window.

jQuery If DIV Doesn't Have Class "x"

jQuery has the hasClass() function that returns true if any element in the wrapped set contains the specified class

if (!$(this).hasClass("selected")) {
    //do stuff
}

Take a look at my example of use

  • If you hover over a div, it fades as normal speed to 100% opacity if the div does not contain the 'selected' class
  • If you hover out of a div, it fades at slow speed to 30% opacity if the div does not contain the 'selected' class
  • Clicking the button adds 'selected' class to the red div. The fading effects no longer work on the red div

Here is the code for it

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<title>Sandbox</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css" media="screen">
body { background-color: #FFF; font: 16px Helvetica, Arial; color: #000; }
</style>


<!-- jQuery code here -->
<script type="text/javascript">
$(function() {

$('#myButton').click(function(e) {
$('#div2').addClass('selected');
});

$('.thumbs').bind('click',function(e) { alert('You clicked ' + e.target.id ); } );

$('.thumbs').hover(fadeItIn, fadeItOut);


});

function fadeItIn(e) {
if (!$(e.target).hasClass('selected')) 
 { 
    $(e.target).fadeTo('normal', 1.0); 
  } 
}

function fadeItOut(e) { 
  if (!$(e.target).hasClass('selected'))
  { 
    $(e.target).fadeTo('slow', 0.3); 
 } 
}
</script>


</head>
<body>
<div id="div1" class="thumbs" style=" background-color: #0f0; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both;"> 
One div with a thumbs class
</div>
<div id="div2" class="thumbs" style=" background-color: #f00; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both;">
Another one with a thumbs class
</div>
<input type="button" id="myButton" value="add 'selected' class to red div" />
</body>
</html>

EDIT:

this is just a guess, but are you trying to achieve something like this?

  • Both divs start at 30% opacity
  • Hovering over a div fades to 100% opacity, hovering out fades back to 30% opacity. Fade effects only work on elements that don't have the 'selected' class
  • Clicking a div adds/removes the 'selected' class

jQuery Code is here-

$(function() {

$('.thumbs').bind('click',function(e) { $(e.target).toggleClass('selected'); } );
$('.thumbs').hover(fadeItIn, fadeItOut);
$('.thumbs').css('opacity', 0.3);

});

function fadeItIn(e) {
if (!$(e.target).hasClass('selected')) 
 { 
    $(e.target).fadeTo('normal', 1.0); 
  } 
}

function fadeItOut(e) { 
  if (!$(e.target).hasClass('selected'))
  { 
    $(e.target).fadeTo('slow', 0.3); 
 } 
}

<div id="div1" class="thumbs" style=" background-color: #0f0; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both; cursor:pointer;"> 
One div with a thumbs class
</div>
<div id="div2" class="thumbs" style=" background-color: #f00; margin: 10px; padding: 10px; width: 100px; height: 50px; clear: both; cursor:pointer;">
Another one with a thumbs class
</div>

What does "if (rs.next())" mean?

The next() method (offcial doc here) simply move the pointer of the result rows set to the next row (if it can). Anyway you can read this from the offcial doc as well:

Moves the cursor down one row from its current position.

This method return true if there's another row or false otherwise.

Checkbox value true/false

To return true or false depending on whether a checkbox is checked or not, I use this in JQuery

let checkState = $("#checkboxId").is(":checked") ? "true" : "false";

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

I encountered similar problem recently. The fix is to set the display property of the li items in the ordered list to list-item, and not display block, and ensure that the display property of ol is not list-item. i.e

li { display: list-item;}

With this, the html parser sees all li as the list item and assign the appropriate value to it, and sees the ol, as an inline-block or block element based on your settings, and doesn't try to assign any count value to it.

OS X Terminal UTF-8 issues

Check whether nano was actually built with UTF-8 support, using nano --version. Here it is on Cygwin:

nano --version
 GNU nano version 2.2.5 (compiled 21:04:20, Nov  3 2010)
 (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
 2008, 2009 Free Software Foundation, Inc.
 Email: [email protected]    Web: http://www.nano-editor.org/
 Compiled options: --enable-color --enable-extra --enable-multibuffer
 --enable-nanorc --enable-utf8

Note the last bit.

Regex for string not ending with given suffix

Anything that matches something ending with a --- .*a$ So when you match the regex, negate the condition or alternatively you can also do .*[^a]$ where [^a] means anything which is not a

Does 'position: absolute' conflict with Flexbox?

You have to give width:100% to parent to center the text.

_x000D_
_x000D_
 .parent {_x000D_
   display: flex;_x000D_
   justify-content: center;_x000D_
   position: absolute;_x000D_
   width:100%_x000D_
 }
_x000D_
<div class="parent">_x000D_
  <div class="child">text</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

If you also need to centre align vertically, give height:100% and align-itens: center

.parent {
   display: flex;
   justify-content: center;
   align-items: center;
   position: absolute;
   width:100%;
   height: 100%;
 }

PHP json_encode json_decode UTF-8

  header('Content-Type: application/json; charset=utf-8');

Visualizing decision tree in scikit-learn

Alternatively, you could try using pydot for producing the png file from dot:

...
tree.export_graphviz(dtreg, out_file='tree.dot') #produces dot file

import pydot
dotfile = StringIO()
tree.export_graphviz(dtreg, out_file=dotfile)
pydot.graph_from_dot_data(dotfile.getvalue()).write_png("dtree2.png")
...

Overwriting my local branch with remote branch

What I do when I mess up my local branch is I just rename my broken branch, and check out/branch the upstream branch again:

git branch -m branch branch-old
git fetch remote
git checkout -b branch remote/branch

Then if you're sure you don't want anything from your old branch, remove it:

git branch -D branch-old

But usually I leave the old branch around locally, just in case I had something in there.

Cannot issue data manipulation statements with executeQuery()

When executing DML statement , you should use executeUpdate/execute rather than executeQuery.

Here is a brief comparison :

executeQueryVSexecuteUpdateVSexecute

Proper usage of Java -D command-line parameters

That should be:

java -Dtest="true" -jar myApplication.jar

Then the following will return the value:

System.getProperty("test");

The value could be null, though, so guard against an exception using a Boolean:

boolean b = Boolean.parseBoolean( System.getProperty( "test" ) );

Note that the getBoolean method delegates the system property value, simplifying the code to:

if( Boolean.getBoolean( "test" ) ) {
   // ...
}

Eclipse: Frustration with Java 1.7 (unbound library)

To set JDK you can watch this video : how to set JDK . Then when you'll have JDK:

  1. Right click on build path and select "Build Path"
  2. Choose "Configure Build Path"
  3. Click on "JRE System Library [JavaSE-1.7] (unbound)"
  4. Edit it
  5. Choose "Alternate JRE"
  6. Click on "Installed JREs.." button
  7. Press Add
  8. Choose to add "Standard VM"
  9. Choose JRE Home directory - usually it is locates in "C:\Program Files\Java\jre7" directory
  10. Press "Finish"
  11. Re-check newly appeared "Jre7": Verify that now when you edit "JRE System Library [JavaSE-1.7]" "Alternate JRE" is chosen for jre7.

Return sql rows where field contains ONLY non-alphanumeric characters

This will not work correctly, e.g. abcÑxyz will pass thru this as it has a,b,c... you need to work with Collate or check each byte.

Why does visual studio 2012 not find my tests?

A problem I've found is that tests don't get found in the Test Explorer (nothing shows up) if the solution is running off a network drive / network location / shared drive

You can fix this by adding an environment variable.

COMPLUS_LoadFromRemoteSources and set its value to 1

C# loop - break vs. continue

All have given a very good explanation. I am still posting my answer just to give an example if that can help.

// break statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        break; // It will force to come out from the loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}

Here is the output:

0[Printed] 1[Printed] 2[Printed]

So 3[Printed] & 4[Printed] will not be displayed as there is break when i == 3

//continue statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        continue; // It will take the control to start point of loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}

Here is the output:

0[Printed] 1[Printed] 2[Printed] 4[Printed]

So 3[Printed] will not be displayed as there is continue when i == 3

How to insert table values from one database to another database?

Mostly we need this type of query in migration script

INSERT INTO  db1.table1(col1,col2,col3,col4)
SELECT col5,col6,col7,col8
  FROM db1.table2

In this query column count must be same in both table

What's the fastest way to delete a large folder in Windows?

and to delete a lot of folders, you could also create a batch file with the command spdenne posted.

1) make a text file that has the following contents replacing the folder names in quotes with your folder names:

rmdir /s /q "My Apps"  
rmdir /s /q "My Documents"  
rmdir /s /q "My Pictures"  
rmdir /s /q "My Work Files"

2) save the batch file with a .bat extension (for example deletefiles.bat)
3) open a command prompt (Start > Run > Cmd) and execute the batch file. you can do this like so from the command prompt (substituting X for your drive letter):

X:  
deletefiles.bat

Putting a simple if-then-else statement on one line

Moreover, you can still use the "ordinary" if syntax and conflate it into one line with a colon.

if i > 3: print("We are done.")

or

field_plural = None
if field_plural is not None: print("insert into testtable(plural) '{0}'".format(field_plural)) 

PLS-00103: Encountered the symbol "CREATE"

For me / had to be in a new line.

For example

create type emp_t;/

didn't work

but

create type emp_t;

/

worked.

ToList().ForEach in Linq

As xanatos said, this is a misuse of ForEach.

If you are going to use linq to handle this, I would do it like this:

var departments = employees.SelectMany(x => x.Departments);
foreach (var item in departments)
{
    item.SomeProperty = null;
}
collection.AddRange(departments);

However, the Loop approach is more readable and therefore more maintainable.

How to get first two characters of a string in oracle query?

take a look here

SELECT SUBSTR('Take the first four characters', 1, 4) FIRST_FOUR FROM DUAL;

Could not find folder 'tools' inside SDK

This can also happen due to the bad unzipping process of SDK.It Happend to me. Dont use inbuilt windows unzip process. use WINRAR software for unzipping sdk

How to set enum to null

Color? color = null;

or you can use

Color? color = new Color?();

example where assigning null wont work

color = x == 5 ? Color.Red : x == 9 ? Color.Black : null ; 

so you can use :

 color = x == 5 ? Color.Red : x == 9 ? Color.Black : new Color?(); 

Using a global variable with a thread

Well, running example:

WARNING! NEVER DO THIS AT HOME/WORK! Only in classroom ;)

Use semaphores, shared variables, etc. to avoid rush conditions.

from threading import Thread
import time

a = 0  # global variable


def thread1(threadname):
    global a
    for k in range(100):
        print("{} {}".format(threadname, a))
        time.sleep(0.1)
        if k == 5:
            a += 100


def thread2(threadname):
    global a
    for k in range(10):
        a += 1
        time.sleep(0.2)


thread1 = Thread(target=thread1, args=("Thread-1",))
thread2 = Thread(target=thread2, args=("Thread-2",))

thread1.start()
thread2.start()

thread1.join()
thread2.join()

and the output:

Thread-1 0
Thread-1 1
Thread-1 2
Thread-1 2
Thread-1 3
Thread-1 3
Thread-1 104
Thread-1 104
Thread-1 105
Thread-1 105
Thread-1 106
Thread-1 106
Thread-1 107
Thread-1 107
Thread-1 108
Thread-1 108
Thread-1 109
Thread-1 109
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110
Thread-1 110

If the timing were right, the a += 100 operation would be skipped:

Processor executes at T a+100 and gets 104. But it stops, and jumps to next thread Here, At T+1 executes a+1 with old value of a, a == 4. So it computes 5. Jump back (at T+2), thread 1, and write a=104 in memory. Now back at thread 2, time is T+3 and write a=5 in memory. Voila! The next print instruction will print 5 instead of 104.

VERY nasty bug to be reproduced and caught.

String.contains in Java

Thinking of a string as a set of characters, in mathematics the empty set is always a subset of any set.

CSS flexbox not working in IE10

Flex layout modes are not (fully) natively supported in IE yet. IE10 implements the "tween" version of the spec which is not fully recent, but still works.

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes

This CSS-Tricks article has some advice on cross-browser use of flexbox (including IE): http://css-tricks.com/using-flexbox/

edit: after a bit more research, IE10 flexbox layout mode implemented current to the March 2012 W3C draft spec: http://www.w3.org/TR/2012/WD-css3-flexbox-20120322/

The most current draft is a year or so more recent: http://dev.w3.org/csswg/css-flexbox/

How to find out if you're using HTTPS without $_SERVER['HTTPS']

If your are using Apache you may always count on

$_SERVER["REQUEST_SCHEME"]

to verify the scheme of the URL requested. But, as mentioned in other answers, it is prudent to verify other parameters before assuming SSL is really being used.

How to print something when running Puppet client?

If you want to notify user with different type of messages like information, debug, error, warning, alerts, critical and emergency messages then use ‘loglevel’ metaparameter in puppet resources.

With the use of loglevel you can use the same resources for different type of error messages.

e.g for producing debug messages you can use it as,

 notify {"debug message":
      loglevel => debug,
    }

MySQL Insert query doesn't work with WHERE clause

You can't combine a WHERE clause with a VALUES clause. You have two options as far as I am aware-

  1. INSERT specifying values

    INSERT INTO Users(weight, desiredWeight) 
    VALUES (160,145)
    
  2. INSERT using a SELECT statement

    INSERT INTO Users(weight, desiredWeight) 
    SELECT weight, desiredWeight 
    FROM AnotherTable 
    WHERE id = 1
    

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

I renamed the .m2 directory, this didn't help yet, so I installed the newest sdk/jdk and restarted eclipse. This worked.

It seems an SDK was needed and I only had installed a JRE.

Which is weird, because eclipse worked on the same machine for a different older project.

I imported a second maven project, and Run/maven install did only complete after restarting eclipse. So maybe just a restart of eclipse was necessary.

Importing yet another project, and had to do maven install twice before it worked even though I had restarted eclipse.

How to disable submit button once it has been clicked?

I did the trick. When set timeout, it works perfectly and sending all values.

    $(document).ready(function () {
        document.getElementById('btnSendMail').onclick = function () {
            setTimeout(function () {
                document.getElementById('btnSendMail').value = 'Sending…';
                document.getElementById('btnSendMail').disabled = true;
            }, 850);
        }
    });

How to redirect stdout to both file and console with scripting?

I got the way to redirect the out put to console as well as to a text file as well simultaneously:

te = open('log.txt','w')  # File where you need to keep the logs

class Unbuffered:

   def __init__(self, stream):

       self.stream = stream

   def write(self, data):

       self.stream.write(data)
       self.stream.flush()
       te.write(data)    # Write the data of stdout here to a text file as well



sys.stdout=Unbuffered(sys.stdout)

Printing newlines with print() in R

You can also use a combination of cat and paste0

cat(paste0("File not supplied.\n", "Usage: ./program F=filename"))

I find this to be more useful when incorporating variables into the printout. For example:

file <- "myfile.txt"
cat(paste0("File not supplied.\n", "Usage: ./program F=", file))

How can I find out the current route in Rails?

Should you also need the parameters:

current_fullpath = request.env['ORIGINAL_FULLPATH']
# If you are browsing http://example.com/my/test/path?param_n=N 
# then current_fullpath will point to "/my/test/path?param_n=N"

And remember you can always call <%= debug request.env %> in a view to see all the available options.

CSS "and" and "or"

To select properties a AND b of a X element:

X[a][b]

To select properties a OR b of a X element:

X[a],X[b]

typeof !== "undefined" vs. != null

You can also use the void operator to obtain an undefined value:

if (input !== void 0) {
    // do stuff    
}

(And yes, as noted in another answer, this will throw an error if the variable was not declared, but this case can often be ruled out either by code inspection, or by code refactoring, e.g. using window.input !== void 0 for testing global variables or adding var input.)

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

Here are some real-world examples of the types of relationships:

One-to-one (1:1)

A relationship is one-to-one if and only if one record from table A is related to a maximum of one record in table B.

To establish a one-to-one relationship, the primary key of table B (with no orphan record) must be the secondary key of table A (with orphan records).

For example:

CREATE TABLE Gov(
    GID number(6) PRIMARY KEY, 
    Name varchar2(25), 
    Address varchar2(30), 
    TermBegin date,
    TermEnd date
); 

CREATE TABLE State(
    SID number(3) PRIMARY KEY,
    StateName varchar2(15),
    Population number(10),
    SGID Number(4) REFERENCES Gov(GID), 
    CONSTRAINT GOV_SDID UNIQUE (SGID)
);

INSERT INTO gov(GID, Name, Address, TermBegin) 
values(110, 'Bob', '123 Any St', '1-Jan-2009');

INSERT INTO STATE values(111, 'Virginia', 2000000, 110);

One-to-many (1:M)

A relationship is one-to-many if and only if one record from table A is related to one or more records in table B. However, one record in table B cannot be related to more than one record in table A.

To establish a one-to-many relationship, the primary key of table A (the "one" table) must be the secondary key of table B (the "many" table).

For example:

CREATE TABLE Vendor(
    VendorNumber number(4) PRIMARY KEY,
    Name varchar2(20),
    Address varchar2(20),
    City varchar2(15),
    Street varchar2(2),
    ZipCode varchar2(10),
    Contact varchar2(16),
    PhoneNumber varchar2(12),
    Status varchar2(8),
    StampDate date
);

CREATE TABLE Inventory(
    Item varchar2(6) PRIMARY KEY,
    Description varchar2(30),
    CurrentQuantity number(4) NOT NULL,
    VendorNumber number(2) REFERENCES Vendor(VendorNumber),
    ReorderQuantity number(3) NOT NULL
);

Many-to-many (M:M)

A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa.

To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.

CREATE TABLE Class(
    ClassID varchar2(10) PRIMARY KEY, 
    Title varchar2(30),
    Instructor varchar2(30), 
    Day varchar2(15), 
    Time varchar2(10)
);

CREATE TABLE Student(
    StudentID varchar2(15) PRIMARY KEY, 
    Name varchar2(35),
    Major varchar2(35), 
    ClassYear varchar2(10), 
    Status varchar2(10)
);  

CREATE TABLE ClassStudentRelation(
    StudentID varchar2(15) NOT NULL,
    ClassID varchar2(14) NOT NULL,
    FOREIGN KEY (StudentID) REFERENCES Student(StudentID), 
    FOREIGN KEY (ClassID) REFERENCES Class(ClassID),
    UNIQUE (StudentID, ClassID)
);

Get month name from Date

Shorter version:

_x000D_
_x000D_
const monthNames = ["January", "February", "March", "April", "May", "June",_x000D_
  "July", "August", "September", "October", "November", "December"_x000D_
];_x000D_
_x000D_
const d = new Date();_x000D_
document.write("The current month is " + monthNames[d.getMonth()]);
_x000D_
_x000D_
_x000D_

Note (2019-03-08) - This answer by me which I originally wrote in 2009 is outdated. See David Storey's answer for a better solution.

MySQL "incorrect string value" error when save unicode string in Django

You can change the collation of your text field to UTF8_general_ci and the problem will be solved.

Notice, this cannot be done in Django.

How to detect iPhone 5 (widescreen devices)?

if ((int)[[UIScreen mainScreen] bounds].size.height == 568)
{
    // This is iPhone 5 screen
} else {
    // This is iPhone 4 screen
}

PHP Date Format to Month Name and Year

I think your date data should look like 2013-08-14.

<?php
 $yrdata= strtotime('2013-08-14');
    echo date('M-Y', $yrdata);
 ?>
// Output is Aug-2013

How to open a second activity on click of button in android app

Replace the below line code:

import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener{
   Button button;
    @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=(Button)findViewById(R.id.button1);
        button.setOnClickListener(this);
      }
       public void onClick(View v) {
        if(v.getId==R.id.button1){
      Intent i = new Intent(FromActivity.this, ToActivity.class);
               startActivity(i);
            }
        }
     }

Add the below lines in your manifest file:

   <activity android:name="com.packagename.FromActivity"></activity>
   <activity android:name="com.packagename.ToActivity"></activity>

matplotlib: colorbars and its text labels

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

demo

Accessing attributes from an AngularJS directive

See section Attributes from documentation on directives.

observing interpolated attributes: Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.

No restricted globals

Use react-router-dom library.

From there, import useLocation hook if you're using functional components:

import { useLocation } from 'react-router-dom';

Then append it to a variable:

Const location = useLocation();

You can then use it normally:

location.pathname

P.S: the returned location object has five properties only:

{ hash: "", key: "", pathname: "/" search: "", state: undefined__, }

Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

Many mobile devices have resolutions so high that it's hard to distinguish between them and much larger screens. There are two ways to deal with this problem:

Use the following HTML code to scale the pixels (grouping smaller pixels into groups the size of the unit pixel - 96dpi, so px units will have the same physical size on all screens). Note that this will affect the scale of pretty much everything in your website, but this is generally the way to go when making sites mobile-friendly.

<meta name="viewport" content="width=device-width, initial-scale=1">

Alternatively, measuring the screen width in @media queries using cm instead of px units can tell you if you're dealing with a physically small screen regardless of resolution.

How do I convert NSMutableArray to NSArray?

you try this code---

NSMutableArray *myMutableArray = [myArray mutableCopy];

and

NSArray *myArray = [myMutableArray copy];

Remove padding or margins from Google Charts

I am quite late but any user searching for this can get help from it. Inside the options you can pass a new parameter called chartArea.

        var options = {
        chartArea:{left:10,top:20,width:"100%",height:"100%"}
    };

Left and top options will define the amount of padding from left and top. Hope this will help.

How can I create a carriage return in my C# string

myString += Environment.NewLine;

myString = myString + Environment.NewLine;

Could not find the main class, program will exit

  1. JAVA_HOME variable must be set, to point to the prog files/java/version???/bin
  2. open squirrel-sql.bat file with some text editor and see if the JAVA_HOME variable there is the same as the one in your enviroment variable
  3. change it if it doesn't match....and than run bat file again

did you specify the right host or port? error on Kubernetes

I have a smae issue. in my scenario there is kubernetes API server is not responding. so check you kubernetes API server and controller as well as.

how to get curl to output only http response body (json) and no other headers etc

I was executing a get request an also want to see just the response and nothing else, seems like magic is done with -silent,-s option.

From the curl man page:

-s, --silent Silent or quiet mode. Don't show progress meter or error messages. Makes Curl mute. It will still output the data you ask for, potentially even to the terminal/stdout unless you redirect it.

Below the examples:

curl -s "http://host:8080/some/resource"
curl -silent "http://host:8080/some/resource"

Using custom headers

curl -s -H "Accept: application/json" "http://host:8080/some/resource")

Using POST method with a header

curl -s -X POST -H "Content-Type: application/json" "http://host:8080/some/resource") -d '{ "myBean": {"property": "value"}}'

You can also customize the output for specific values with -w, below the options I use to get just response codes of the curl:

curl -s -o /dev/null -w "%{http_code}" "http://host:8080/some/resource"

What is 'PermSize' in Java?

A quick definition of the "permanent generation":

"The permanent generation is used to hold reflective data of the VM itself such as class objects and method objects. These reflective objects are allocated directly into the permanent generation, and it is sized independently from the other generations." [ref]

In other words, this is where class definitions go (and this explains why you may get the message OutOfMemoryError: PermGen space if an application loads a large number of classes and/or on redeployment).

Note that PermSize is additional to the -Xmx value set by the user on the JVM options. But MaxPermSize allows for the JVM to be able to grow the PermSize to the amount specified. Initially when the VM is loaded, the MaxPermSize will still be the default value (32mb for -client and 64mb for -server) but will not actually take up that amount until it is needed. On the other hand, if you were to set BOTH PermSize and MaxPermSize to 256mb, you would notice that the overall heap has increased by 256mb additional to the -Xmx setting.

Laravel migration default value

You can simple put the default value using default(). See the example

 $table->enum('is_approved', array('0','1'))->default('0');

I have used enum here and the default value is 0.

How to add facebook share button on my website?

For Facebook share with an image without an API and using a # to deep link into a sub page, the trick was to share the image as picture=

The variable mainUrl would be http://yoururl.com/

var d1 = $('.targ .t1').text();
var d2 = $('.targ .t2').text();
var d3 = $('.targ .t3').text();
var d4 = $('.targ .t4').text();
var descript_ = d1 + ' ' + d2 + ' ' + d3 + ' ' + d4;
var descript = encodeURIComponent(descript_);

var imgUrl_ = 'path/to/mypic_'+id+'.jpg';
var imgUrl = mainUrl + encodeURIComponent(imgUrl_);

var shareLink = mainUrl + encodeURIComponent('mypage.html#' + id);

var fbShareLink = shareLink + '&picture=' + imgUrl + '&description=' + descript;
var twShareLink = 'text=' + descript + '&url=' + shareLink;

// facebook
$(".my-btn .facebook").off("tap click").on("tap click",function(){
  var fbpopup = window.open("https://www.facebook.com/sharer/sharer.php?u=" + fbShareLink, "pop", "width=600, height=400, scrollbars=no");
  return false;
});

// twitter
$(".my-btn .twitter").off("tap click").on("tap click",function(){
  var twpopup = window.open("http://twitter.com/intent/tweet?" + twShareLink , "pop", "width=600, height=400, scrollbars=no");
  return false;
});

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

Change the group permission for the folder

sudo chown -R w3cert /home/w3cert/.composer/cache/repo/https---packagist.org

and the Files folder too

sudo chown -R w3cert /home/w3cert/.composer/cache/files/

I'm assuming w3cert is your username, if not change the 4th parameter to your username.

If the problem still persists try

sudo chown -R w3cert /home/w3cert/.composer

Now, there is a chance that you won't be able to create your app directory, if that happens do the same for your html folder or the folder you are trying to create your laravel project in.

Hope this helps.

How to display svg icons(.svg files) in UI using React Component?

if you have .svg or an image locally. first you have to install the loader needed for svg and file-loader for images. Then you have to import your icon or image first for example:

import logo from './logos/myLogo.svg' ;
import image from './images/myimage.png';

const temp = (
     <div>
         <img src={logo} />
         <img src={image} />
     </div>
);

ReactDOM.render(temp,document.getElementByID("app"));

Happy Coding :")

resources from react website and worked for me after many searches: https://create-react-app.dev/docs/adding-images-fonts-and-files/

How do I sort a dictionary by value?

You can create an "inverted index", also

from collections import defaultdict
inverse= defaultdict( list )
for k, v in originalDict.items():
    inverse[v].append( k )

Now your inverse has the values; each value has a list of applicable keys.

for k in sorted(inverse):
    print k, inverse[k]

Angular 4/5/6 Global Variables

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

Index.html

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

Component or anything else in Angular

..near the top right after imports:

declare const myTest: any;

...later:

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

How to do scanf for single char in C

This works for me try it out

int main(){
char c;
scanf(" %c",&c);
printf("%c",c);
return 0;
}

Check if Python Package is installed

Is there any chance to use the snippets given below? When I run this code, it returns "module pandas is not installed"

a = "pandas"

try:
    import a
    print("module ",a," is installed")
except ModuleNotFoundError:
    print("module ",a," is not installed")

But when I run the code given below:

try:
    import pandas
    print("module is installed")
except ModuleNotFoundError:
    print("module is not installed")

It returns "module pandas is installed".

What is the difference between them?

Error in file(file, "rt") : cannot open the connection

I got my R code file from a friend and was not able to run read.csv command but If I copy the same command(read.csv ) to a new R script file, it ran fine.

Below command was not running in R code file shared by my friend, working directory,file name etc were all correct because If I created a new R script file and ran below command ,it worked.

           df <- read.csv("file.csv",header=TRUE,stringsAsFactors = FALSE,strip.white = 
           TRUE,sep = ',')

issue/resolution: I right clicked the R code file and unblocked the file and click save button and issue got resolved. I your R code file is in Downloads folder in windows , then move to some other folder.

enter image description here

How to pass argument to Makefile from command line?

Here is a generic working solution based on @Beta's

I'm using GNU Make 4.1 with SHELL=/bin/bash atop my Makefile, so YMMV!

This allows us to accept extra arguments (by doing nothing when we get a job that doesn't match, rather than throwing an error).

%:
    @:

And this is a macro which gets the args for us:

args = `arg="$(filter-out $@,$(MAKECMDGOALS))" && echo $${arg:-${1}}`

Here is a job which might call this one:

test:
    @echo $(call args,defaultstring)

The result would be:

$ make test
defaultstring
$ make test hi
hi

Note! You might be better off using a "Taskfile", which is a bash pattern that works similarly to make, only without the nuances of Maketools. See https://github.com/adriancooney/Taskfile

Drop data frame columns by name

Here is a dplyr way to go about it:

#df[ -c(1,3:6, 12) ]  # original
df.cut <- df %>% select(-col.to.drop.1, -col.to.drop.2, ..., -col.to.drop.6)  # with dplyr::select()

I like this because it's intuitive to read & understand without annotation and robust to columns changing position within the data frame. It also follows the vectorized idiom using - to remove elements.

How to use terminal commands with Github?

You can't push into other people's repositories. This is because push permanently gets code into their repository, which is not cool.

What you should do, is to ask them to pull from your repository. This is done in GitHub by going to the other repository and sending a "pull request".

There is a very informative article on the GitHub's help itself: https://help.github.com/articles/using-pull-requests


To interact with your own repository, you have the following commands. I suggest you start reading on Git a bit more for these instructions (lots of materials online).

To add new files to the repository or add changed files to staged area:

$ git add <files>

To commit them:

$ git commit

To commit unstaged but changed files:

$ git commit -a

To push to a repository (say origin):

$ git push origin

To push only one of your branches (say master):

$ git push origin master

To fetch the contents of another repository (say origin):

$ git fetch origin

To fetch only one of the branches (say master):

$ git fetch origin master

To merge a branch with the current branch (say other_branch):

$ git merge other_branch

Note that origin/master is the name of the branch you fetched in the previous step from origin. Therefore, updating your master branch from origin is done by:

$ git fetch origin master
$ git merge origin/master

You can read about all of these commands in their manual pages (either on your linux or online), or follow the GitHub helps:

How to find out the server IP address (using JavaScript) that the browser is connected to?

Fairly certain this cannot be done. However you could use your preferred server-side language to print the server's IP to the client, and then use it however you like. For example, in PHP:

<script type="text/javascript">
    var ip = "<?php echo $_SERVER['SERVER_ADDR']; ?>";
    alert(ip);
</script>

This depends on your server's security setup though - some may block this.

How can I get client information such as OS and browser

Update: The project is EOL and not maintained anymore. He recommends switching to the Browscap project.

You can use the bitwalker useragentutils library: https://github.com/HaraldWalker/user-agent-utils. It will provide you information about the Browser (name, type, version, manufacturer, etc.) and about the OperatingSystem. A good thing about it is that it is maintained. Access the link that I have provided to see the Maven dependency that you need to add to you project in order to use it.

See below sample code that returns the browser name and browser version.

    UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
    Browser browser = userAgent.getBrowser();

    String browserName = browser.getName();
    //or 
    // String browserName = browser.getGroup().getName();
    Version browserVersion = userAgent.getBrowserVersion();
    System.out.println("The user is using browser " + browserName + " - version " + browserVersion);

Fullscreen Activity in Android?

Inside styles.xml...

<!-- No action bar -->
<style name="NoActonBar" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Theme customization. -->
    <item name="colorPrimary">#000</item>
    <item name="colorPrimaryDark">#444</item>
    <item name="colorAccent">#999</item>
    <item name="android:windowFullscreen">true</item>
</style>

This worked for me. Hope it'll help you.

What's the quickest way to multiply multiple cells by another number?

Select Product from formula bar in your answer cell.

Select cells you want to multiply.

Scanner method to get a char

sc.next().charat(0).........is the method of entering character by user based on the number entered at the run time

example: sc.next().charat(2)------------>>>>>>>>

SQL Format as of Round off removing decimals

use ROUND () (See examples ) function in sql server

select round(11.6,0)

result:

12.0

ex2:

select round(11.4,0)

result:

11.0

if you don't want the decimal part, you could do

select cast(round(11.6,0) as int)

How to disable copy/paste from/to EditText

In addition to the setCustomSelectionActionModeCallback, and disabled long-click solutions, it's necessary to prevent the PASTE/REPLACE menus from appearing when the text selection handle is clicked, as per the image below:

Text selection handle with paste menu

The solution lies in preventing PASTE/REPLACE menu from appearing in the show() method of the (non-documented) android.widget.Editor class. Before the menu appears, a check is done to if (!canPaste && !canSuggest) return;. The two methods that are used as the basis to set these variables are both in the EditText class:

A more complete answer is available here.

jQuery adding 2 numbers from input fields

Adding strings concatenates them:

> "1" + "1"
"11"

You have to parse them into numbers first:

/* parseFloat is used here. 
 * Because of it's not known that 
 * whether the number has fractional places.
 */

var a = parseFloat($('#a').val()),
    b = parseFloat($('#b').val());

Also, you have to get the values from inside of the click handler:

$("submit").on("click", function() {
   var a = parseInt($('#a').val(), 10),
       b = parseInt($('#b').val(), 10);
});

Otherwise, you're using the values of the textboxes from when the page loads.

How to run .NET Core console app from the command line

With dotnetcore3.0 you can package entire solution into a single-file executable using PublishSingleFile property

-p:PublishSingleFile=True

Source Single-file executables

An example of Self Contained, Release OSX executable:

dotnet publish -c Release -r osx-x64 -p:PublishSingleFile=True --self-contained True

An example of Self Contained, Debug Linux 64bit executable:

dotnet publish -c Debug -r linux-x64 -p:PublishSingleFile=True --self-contained True

Linux build is independed of distribution and I have found them working on Ubuntu 18.10, CentOS 7.7, and Amazon Linux 2.

A Self Contained executable includes Dotnet Runtime and Runtime does not require to be installed on a target machine. The published executables are saved under:

<ProjectDir>/bin/<Release or Debug>/netcoreapp3.0/<target-os>/publish/ on Linux, OSX and

<ProjectDir>\bin\<Release or Debug>\netcoreapp3.0\<target-os>\publish\ on Windows.

Integer value comparison

Although you could certainly use the compareTo method on an Integer instance, it's not clear when reading the code, so you should probably avoid doing so.

Java allows you to use autoboxing (see http://java.sun.com/j2se/1.5.0/docs/guide/language/autoboxing.html) to compare directly with an int, so you can do:

if (count > 0) { }

And the Integer instance count gets automatically converted to an int for the comparison.

If you're having trouble understanding this, check out the link above, or imagine it's doing this:

if (count.intValue() > 0) { }

What is the difference between a candidate key and a primary key?

First you have to know what is a determinant? the determinant is an attribute that used to determine another attribute in the same table. SO the determinant must be a candidate key. And you can have more than one determinant. But primary key is used to determine the whole record and you can have only one primary key. Both primary and candidate key can consist of one or more attributes

adding multiple entries to a HashMap at once in one statement

Based on solution, presented by @Dakusan (the class defining to extend the HashMap), I did it this way:

  public static HashMap<String,String> SetHash(String...pairs) {
     HashMap<String,String> rtn = new HashMap<String,String>(pairs.length/2);
     for ( int n=0; n < pairs.length; n+=2 ) rtn.put(pairs[n], pairs[n + 1]);
    return rtn; 
  }

.. and using it this way:

HashMap<String,String> hm = SetHash( "one","aa", "two","bb", "tree","cc");

(Not sure if there is any disadvantages in that way (I am not a java developer, just has to do some task in java), but it works and seems to me comfortable.)

How do I change the hover over color for a hover over table in Bootstrap?

.table-hover tbody tr:hover td {
    background: #ffffff;
}

Increase heap size in Java

Yes. You Can.

You can increase your heap memory to 75% of physical memory (6 GB Heap) or higher.

Since You are using 64bit you can increase your heap size to your desired amount. In Case you are using 32bit it is limited to 4GB.

$ java -Xms512m -Xmx6144m JavaApplication

Sets you with initial heap size to 512mb and maximum heapsize to 6GB.

Hope it Helps.. :)

Bootstrap 3 unable to display glyphicon properly

For me placing my fonts folder as per location specified in bootstrap.css solved the problem

Mostly its fonts folder should be in parent directory of bootstrap.css file .

I faced this problem , and researching many answers , if anyone still in 2015 faces this problem then its either a CSS problem , or location mismatch for files .

The bug has already been solved by bootstrap

How do I copy a folder from remote to local using scp?

In case you run into "Too many authentication failures", specify the exact SSH key you have added to your severs ssh server:

scp -r -i /path/to/local/key [email protected]:/path/to/folder /your/local/target/dir

How to install latest version of Node using Brew

Sometimes brew update fails on me because one package doesn't download properly. So you can just upgrade a specific library like this:

brew upgrade node

https://gist.github.com/3005832

How to convert an array to a string in PHP?

PHP has a built-in function implode to assign array values to string. Use it like this:

$str = implode(",", $array);

How can I get city name from a latitude and longitude point?

Here's a modern solution using a promise:

function getAddress (latitude, longitude) {
    return new Promise(function (resolve, reject) {
        var request = new XMLHttpRequest();

        var method = 'GET';
        var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude + ',' + longitude + '&sensor=true';
        var async = true;

        request.open(method, url, async);
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    var data = JSON.parse(request.responseText);
                    var address = data.results[0];
                    resolve(address);
                }
                else {
                    reject(request.status);
                }
            }
        };
        request.send();
    });
};

And call it like this:

getAddress(lat, lon).then(console.log).catch(console.error);

The promise returns the address object in 'then' or the error status code in 'catch'

Table Naming Dilemma: Singular vs. Plural Names

I am of the firm belief that in an Entity Relation Diagram, the entity should be reflected with a singular name, similar to a class name being singular. Once instantiated, the name reflects its instance. So with databases, the entity when made into a table (a collection of entities or records) is plural. Entity, User is made into table Users. I would agree with others who suggested maybe the name User could be improved to Employee or something more applicable to your scenario.

This then makes more sense in a SQL statement because you are selecting from a group of records and if the table name is singular, it doesn't read well.

error C2220: warning treated as error - no 'object' file generated

The error says that a warning was treated as an error, therefore your problem is a warning message! The object file is then not created because there was an error. So you need to check your warnings and fix them.

In case you don't know how to find them: Open the Error List (View > Error List) and click on Warning.

Select folder dialog WPF

If you don't want to use Windows Forms nor edit manifest files, I came up with a very simple hack using WPF's SaveAs dialog for actually selecting a directory.

No using directive needed, you may simply copy-paste the code below !

It should still be very user-friendly and most people will never notice.

The idea comes from the fact that we can change the title of that dialog, hide files, and work around the resulting filename quite easily.

It is a big hack for sure, but maybe it will do the job just fine for your usage...

In this example I have a textbox object to contain the resulting path, but you may remove the related lines and use a return value if you wish...

// Create a "Save As" dialog for selecting a directory (HACK)
var dialog = new Microsoft.Win32.SaveFileDialog();
dialog.InitialDirectory = textbox.Text; // Use current value for initial dir
dialog.Title = "Select a Directory"; // instead of default "Save As"
dialog.Filter = "Directory|*.this.directory"; // Prevents displaying files
dialog.FileName = "select"; // Filename will then be "select.this.directory"
if (dialog.ShowDialog() == true) {
    string path = dialog.FileName;
    // Remove fake filename from resulting path
    path = path.Replace("\\select.this.directory", "");
    path = path.Replace(".this.directory", "");
    // If user has changed the filename, create the new directory
    if (!System.IO.Directory.Exists(path)) {
        System.IO.Directory.CreateDirectory(path);
    }
    // Our final value is in path
    textbox.Text = path;
}

The only issues with this hack are :

  • Acknowledge button still says "Save" instead of something like "Select directory", but in a case like mines I "Save" the directory selection so it still works...
  • Input field still says "File name" instead of "Directory name", but we can say that a directory is a type of file...
  • There is still a "Save as type" dropdown, but its value says "Directory (*.this.directory)", and the user cannot change it for something else, works for me...

Most people won't notice these, although I would definitely prefer using an official WPF way if microsoft would get their heads out of their asses, but until they do, that's my temporary fix.

Script parameters in Bash

Use the variables "$1", "$2", "$3" and so on to access arguments. To access all of them you can use "$@", or to get the count of arguments $# (might be useful to check for too few or too many arguments).

How to convert an Array to a Set in Java

Java 8:

String[] strArray = {"eins", "zwei", "drei", "vier"};

Set<String> strSet = Arrays.stream(strArray).collect(Collectors.toSet());
System.out.println(strSet);
// [eins, vier, zwei, drei]

How to delete a workspace in Perforce (using p4v)?

It could also be done without a visual client with the following small script.

$ cat ~/bin/pdel

#!/bin/sh

#Todo: add error handling

( p4 -c $1 client -o | perl -pne 's/\blocked\s//' | p4 -c $1  client -i ) && p4 client -d $1

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

I'm not sure for JPA 1.0 but you can pass a Collection in JPA 2.0:

String qlString = "select item from Item item where item.name IN :names"; 
Query q = em.createQuery(qlString, Item.class);

List<String> names = Arrays.asList("foo", "bar");

q.setParameter("names", names);
List<Item> actual = q.getResultList();

assertNotNull(actual);
assertEquals(2, actual.size());

Tested with EclipseLInk. With Hibernate 3.5.1, you'll need to surround the parameter with parenthesis:

String qlString = "select item from Item item where item.name IN (:names)";

But this is a bug, the JPQL query in the previous sample is valid JPQL. See HHH-5126.

Using Cookie in Asp.Net Mvc 4

Try using Response.SetCookie(), because Response.Cookies.Add() can cause multiple cookies to be added, whereas SetCookie will update an existing cookie.

Make git automatically remove trailing whitespace before committing

For Sublime Text users.

Set following properly in you Setting-User configuration.

"trim_trailing_white_space_on_save": true

Using the star sign in grep

The "star sign" is only meaningful if there is something in front of it. If there isn't the tool (grep in this case) may just treat it as an error. For example:

'*xyz'    is meaningless
'a*xyz'   means zero or more occurrences of 'a' followed by xyz

Reset/remove CSS styles for element only

There are two ideas here being confused:

  1. The first idea is about "returning" styles back to a browser's UA style sheet value set (the style sheet that comes with the browser on install that defines what each element looks like). Each browser defines its own styles as to how elements should look by default. This idea is about returning all page styles back to each browsers native element styles.
  2. The second idea is about "resetting" all default browser styles to a common look and feel shared by all browsers. People build special "reset" sheets to try and align all the browser elements to a common agreed on style, universally. This has nothing to do with a browsers default UA styles and more about "cleaning up" and aligning all browsers to a common base style. This is an additive process only.

Those are two very different concepts people here are confusing.

Because each browser often had default, out-of-the-box element and layout styles that looked slightly different, people came up with the idea of the "reset" or "reboot" style sheet to align all the browsers BEFORE applying custom CSS. Bootstrap now does this, for example. But that had nothing to do with people wanting to return to the browser's default look and feel.

The problem was not the building of these custom "reset" style sheets, it is figuring out what the default CSS was for each browser and each element BEFORE any styles were applied. Most found out you cant rebuild an existing clean cascade until you "clear out" all styles already applied. But how to get back to the default browser styling?

For some this meant going beyond returning the elements to the browsers UA style sheet that comes with the browser. Many wanted to reset back to "initial" property values which has NOTHING to do with the browser's default style, but really the properties defaults. This is dangerous as in the case of "display" pushes block level elements back to "inline" and breaks table layouts and other things.

So I do NOT agree with users here using "initial" to reset anything or custom reset classes that change every property back to some arbitrary base value set.

A better solution to me has always been to attempt to try and return all core element styling back to the browser's UA style sheet values, which is what all our end-users are using anyway. If you are creating a new website, you don't have to do this. You start with the browser's default styles and add to them. Its only after you've added third-party CSS products, or found yourself with complicated CSS cascades you want to figure out how to return to the browser default style sheet values.

For this reason, I'm for creating your own "reset" sheet to reset all the elements to one common style first that's shared by all old and new browsers as a first step. You then have a solid framework that's much easier to revert to without going back to the browser defaults. You are simply building on a reset common core set of element style values. Once build your own "reset" sheet, one that ADDS not ALTERS the browsers UA styles, you have a site that's very easy to modify.

The only problem remaining then is when you have a site that does NOT have such a reset sheet, or have that complex third party CSS and need to try and return to the browser UA styles. How do you do that?

I realize Internet Explorer has forced us too manually reset every property to get back to any sort of reset. But pushing those property values all back to "initial" destroys the browser UA style sheet values completely! BAD IDEA! A better way is to simply use "all:revert" for non-IE browsers on every element using a wildcard, and "inherit" only for a handful of inherited root-level properties found in the "html" and "body" elements that affect all inheriting children in the page. (see below). I'm NOT for these huge resets of properties using "initial" or going back to some imaginary standard we assume all browsers or IE will use. For starters "initial" has poor support in IE and doesn't reset values to element defaults, only property defaults. But its also pointless if you are going to create a reset sheet to align all elements to a common style. In that case its pointless to clear out styles and start over.

So here is my simple solution that in most cases does enough to reset what text-based values sift down into IE from the root and use "all:revert" for all non-IE browsers to force non-inherited values back to the browser's UA style sheet completely, giving you a true restart. This does not interfere with higher level classes and styles layered over your element styles, which should always be the goal anyway. Its why I'm NOT for these custom reset classes which is tedious and unnecessary and doesn't return the element to its browser UA style anyway. Notice the slightly more selective selectors below which would write over, for example, Bootstrap's "reboot" style values, returning them to the browser default styles. These would not reset element styles on elements for IE, of course, but for non-IE browsers and most inheritable text styling it would return elements in most agents to the UA style sheets that come with browsers:

:root, html {
    display: block;
    font-family: inherit;
    font-size: inherit;
    font-weight: inherit;
    line-height: inherit;
    -webkit-text-size-adjust: inherit;
    -webkit-tap-highlight-color: inherit;
    all: revert;
}

html body {
    display: block;
    font-family: inherit;
    font-size: inherit;
    font-weight: inherit;
    line-height: inherit;
    margin: inherit;
    padding: inherit;
    color: inherit;
    text-align: inherit;
    background-color: inherit;
    background: inherit;
    all: revert;
}

html body * {
    /* IE elements under body would not be affected by this, but if needed you could add custom elements with property resets as needed to this sheet. */
    all: revert;
}

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

I think you are after this:

CONVERT(datetime, date_as_string, 103)

Notice, that datetime hasn't any format. You think about its presentation. To get the data of datetime in an appropriate format you can use

CONVERT(varchar, date_as_datetime, 103)

How to autoplay HTML5 mp4 video on Android?

In Android 4.1 and 4.2, I use the following code.

    evt.initMouseEvent( "click", true,true,window,0,0,0,0,0,false,false,false,false,0, true );
    var v = document.getElementById("video");
    v.dispatchEvent(evt);

where html is

    <video id="video" src="sample.mp4" poster="image.jpg" controls></video>

This works well. But In Android 4.4, it does not work.

increase font size of hyperlink text html

Your font tag is not correct, so it won't work in some browsers. The px unit is used with CSS, not HTML attributes. The font tag should look like this:

<font size="100">

Well, actually it shouldn't be there at all. The font tag is deprecated, you should use CSS to style the content, like you do already with the text-decoration:

<a href="selectTopic?html" style="font-size: 100px; text-decoration: none">HTML 5</a>

To separate the content from the styling, you should of course work towards putting the CSS in a style sheet rather than as inline style attributes. That way you can apply one style to several elements without having to put the same style attribute in all of them.

Example:

<a href="selectTopic?html" class="topic">HTML 5</a>

CSS:

.topic { font-size: 100px; text-decoration: none; }

Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start

In case your app is run on httpS, make sure you put right values under the following properties:

server.ssl.key-store-password=
server.ssl.key-alias=

I got the same error when I put the wrong values here

How can I get a count of the total number of digits in a number?

It depends what exactly you want to do with the digits. You can iterate through the digits starting from the last to the first one like this:

int tmp = number;
int lastDigit = 0;
do
{
    lastDigit = tmp / 10;
    doSomethingWithDigit(lastDigit);
    tmp %= 10;
} while (tmp != 0);

How to build and run Maven projects after importing into Eclipse IDE

1.Update project

Right Click on your project maven > update project

2.Build project

Right Click on your project again. run as > Maven build

If you have not created a “Run configuration” yet, it will open a new configuration with some auto filled values.

You can change the name. "Base directory" will be a auto filled value for you. Keep it as it is. Give maven command to ”Goals” fields.

i.e, “clean install” for building purpose

Click apply

Click run.

3.Run project on tomcat

Right Click on your project again. run as > Run-Configuration. It will open Run-Configuration window for you.

Right Click on “Maven Build” from the right side column and Select “New”. It will open a blank configuration for you.

Change the name as you want. For the base directory field you can choose values using 3 buttons(workspace,FileSystem,Variables). You can also copy and paste the auto generated value from previously created Run-configuration. Give the Goals as “tomcat:run”. Click apply. Click run.

If you want to get more clear idea with snapshots use the following link.

Build and Run Maven project in Eclipse

(I hope this answer will help someone come after the topic of the question)

ASP.NET file download from server

protected void DescargarArchivo(string strRuta, string strFile)
{
    FileInfo ObjArchivo = new System.IO.FileInfo(strRuta);
    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + strFile);
    Response.AddHeader("Content-Length", ObjArchivo.Length.ToString());
    Response.ContentType = "application/pdf";
    Response.WriteFile(ObjArchivo.FullName);
    Response.End();


}

For loop example in MySQL

While loop syntax example in MySQL:

delimiter //

CREATE procedure yourdatabase.while_example()
wholeblock:BEGIN
  declare str VARCHAR(255) default '';
  declare x INT default 0;
  SET x = 1;

  WHILE x <= 5 DO
    SET str = CONCAT(str,x,',');
    SET x = x + 1;
  END WHILE;

  select str;
END//

Which prints:

mysql> call while_example();
+------------+
| str        |
+------------+
| 1,2,3,4,5, |
+------------+

REPEAT loop syntax example in MySQL:

delimiter //

CREATE procedure yourdb.repeat_loop_example()
wholeblock:BEGIN
  DECLARE x INT;
  DECLARE str VARCHAR(255);
  SET x = 5;
  SET str = '';

  REPEAT
    SET str = CONCAT(str,x,',');
    SET x = x - 1;
    UNTIL x <= 0
  END REPEAT;

  SELECT str;
END//

Which prints:

mysql> call repeat_loop_example();
+------------+
| str        |
+------------+
| 5,4,3,2,1, |
+------------+

FOR loop syntax example in MySQL:

delimiter //

CREATE procedure yourdatabase.for_loop_example()
wholeblock:BEGIN
  DECLARE x INT;
  DECLARE str VARCHAR(255);
  SET x = -5;
  SET str = '';

  loop_label: LOOP
    IF x > 0 THEN
      LEAVE loop_label;
    END IF;
    SET str = CONCAT(str,x,',');
    SET x = x + 1;
    ITERATE loop_label;
  END LOOP;

  SELECT str;

END//

Which prints:

mysql> call for_loop_example();
+-------------------+
| str               |
+-------------------+
| -5,-4,-3,-2,-1,0, |
+-------------------+
1 row in set (0.00 sec)

Do the tutorial: http://www.mysqltutorial.org/stored-procedures-loop.aspx

If I catch you pushing this kind of MySQL for-loop constructs into production, I'm going to shoot you with the foam missile launcher. You can use a pipe wrench to bang in a nail, but doing so makes you look silly.

Update TextView Every Second

It would be better if you just used an AsyncTask running using a Timer something like this

 Timer LAIATT = new Timer();
    TimerTask LAIATTT = new TimerTask()
    {
        @Override
        public void run()
        {
            LoadAccountInformationAsyncTask LAIAT = new LoadAccountInformationAsyncTask();
            LAIAT.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    };
    LAIATT.schedule(LAIATTT, 0, 1000);

Changing image sizes proportionally using CSS?

This help me to make the image 150% with ease.

.img-popup img {
  transform: scale(1.5);
}

Get the first N elements of an array?

In the current order? I'd say array_slice(). Since it's a built in function it will be faster than looping through the array while keeping track of an incrementing index until N.

Do copyright dates need to be updated?

Copyright should be up to the date of publish.

So, if it's a static content (such as the Times article you linked to), it should probably be statically copyrighted.

If it's dynamically generated content, it should be copyrighted to the current year

ScrollTo function in AngularJS

I used andrew joslin's answer, which works great but triggered an angular route change, which created a jumpy looking scroll for me. If you want to avoid triggering a route change,

myApp.directive('scrollOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, $elm, attrs) {
      var idToScroll = attrs.href;
      $elm.on('click', function(event) {
        event.preventDefault();
        var $target;
        if (idToScroll) {
          $target = $(idToScroll);
        } else {
          $target = $elm;
        }
        $("body").animate({scrollTop: $target.offset().top}, "slow");
        return false;
      });
    }
  }
});

Two submit buttons in one form

I think you should be able to read the name/value in your GET array. I think that the button that wasn't clicked wont appear in that list.

python: how to identify if a variable is an array or a scalar

I am surprised that such a basic question doesn't seem to have an immediate answer in python. It seems to me that nearly all proposed answers use some kind of type checking, that is usually not advised in python and they seem restricted to a specific case (they fail with different numerical types or generic iteratable objects that are not tuples or lists).

For me, what works better is importing numpy and using array.size, for example:

>>> a=1
>>> np.array(a)
Out[1]: array(1)

>>> np.array(a).size
Out[2]: 1

>>> np.array([1,2]).size
Out[3]: 2

>>> np.array('125')
Out[4]: 1

Note also:

>>> len(np.array([1,2]))

Out[5]: 2

but:

>>> len(np.array(a))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-f5055b93f729> in <module>()
----> 1 len(np.array(a))

TypeError: len() of unsized object

Map to String in Java

Use Object#toString().

String string = map.toString();

That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

How to measure time elapsed on Javascript?

var seconds = 0;
setInterval(function () {
  seconds++;
}, 1000);

There you go, now you have a variable counting seconds elapsed. Since I don't know the context, you'll have to decide whether you want to attach that variable to an object or make it global.

Set interval is simply a function that takes a function as it's first parameter and a number of milliseconds to repeat the function as it's second parameter.

You could also solve this by saving and comparing times.

EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.

Regex pattern inside SQL Replace function?

For those looking for a performant and easy solution and are willing to enable CLR:

create database TestSQLFunctions
go
use TestSQLFunctions
go
alter database TestSQLFunctions set trustworthy on

EXEC sp_configure 'clr enabled', 1
RECONFIGURE WITH OVERRIDE
go

CREATE ASSEMBLY [SQLFunctions]
AUTHORIZATION [dbo]
FROM 0x4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000504500004C0103004BE8B85F0000000000000000E00022200B013000000800000006000000000000C2270000002000000040000000000010002000000002000004000000000000000600000000000000008000000002000000000000030060850000100000100000000010000010000000000000100000000000000000000000702700004F000000004000009803000000000000000000000000000000000000006000000C00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000080000000000000000000000082000004800000000000000000000002E74657874000000C8070000002000000008000000020000000000000000000000000000200000602E72737263000000980300000040000000040000000A0000000000000000000000000000400000402E72656C6F6300000C0000000060000000020000000E00000000000000000000000000004000004200000000000000000000000000000000A4270000000000004800000002000500682000000807000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003A022D02022A020304281000000A2A1E02281100000A2A0042534A4201000100000000000C00000076342E302E33303331390000000005006C00000018020000237E000084020000CC02000023537472696E6773000000005005000004000000235553005405000010000000234755494400000064050000A401000023426C6F620000000000000002000001471500000900000000FA0133001600000100000013000000020000000200000003000000110000000F00000001000000030000000000CA01010000000000060025014F02060092014F02060044001D020F006F02000006006C00E20106000801E2010600D400E20106007901E20106004501E20106005E01E20106008300E2010600580030020600360030020600B700E20106009E00B0010600AA02DB010A00F300FC010A001F00FC010E00C3027E02000000000100000000000100010001001000C3029D0241000100010050200000000096002E001A0001005F2000000000861817020600040000000100BD0200000200F40100000300B102090017020100110017020600190017020A0029001702100031001702100039001702100041001702100049001702100051001702100059001702100061001702150069001702100071001702100079001702100089001702060099002E001A0081001702060020007B0010012E000B002A002E00130033002E001B0052002E0023005B002E002B006D002E0033006D002E003B006D002E0043005B002E004B0073002E0053006D002E005B006D002E0063008B002E006B00B5002E007300C2000480000001000000000000000000000000009D020000040000000000000000000000210016000000000004000000000000000000000021000A00000000000400000000000000000000002100DB010000000000000000003C4D6F64756C653E0053797374656D2E44617461006D73636F726C696200446174614163636573734B696E64005265706C61636500477569644174747269627574650044656275676761626C6541747472696275746500436F6D56697369626C6541747472696275746500417373656D626C795469746C6541747472696275746500417373656D626C7954726164656D61726B417474726962757465005461726765744672616D65776F726B41747472696275746500417373656D626C7946696C6556657273696F6E41747472696275746500417373656D626C79436F6E66696775726174696F6E4174747269627574650053716C46756E6374696F6E41747472696275746500417373656D626C794465736372697074696F6E41747472696275746500436F6D70696C6174696F6E52656C61786174696F6E7341747472696275746500417373656D626C7950726F6475637441747472696275746500417373656D626C79436F7079726967687441747472696275746500417373656D626C79436F6D70616E794174747269627574650052756E74696D65436F6D7061746962696C6974794174747269627574650053797374656D2E52756E74696D652E56657273696F6E696E670053514C46756E6374696F6E732E646C6C0053797374656D0053797374656D2E5265666C656374696F6E007061747465726E004D6963726F736F66742E53716C5365727665722E536572766572002E63746F720053797374656D2E446961676E6F73746963730053797374656D2E52756E74696D652E496E7465726F7053657276696365730053797374656D2E52756E74696D652E436F6D70696C6572536572766963657300446562756767696E674D6F6465730053797374656D2E546578742E526567756C617245787072657373696F6E730053514C46756E6374696F6E73004F626A656374007265706C6163656D656E7400696E70757400526567657800000000000000003A1617E607071B47B964858BCD87458B00042001010803200001052001011111042001010E04200101020600030E0E0E0E08B77A5C561934E0890801000800000000001E01000100540216577261704E6F6E457863657074696F6E5468726F7773010801000200000000001101000C53514C46756E6374696F6E73000005010000000017010012436F7079726967687420C2A920203230323000002901002434346436386231632D393735312D343938612D396665352D32316666333934303738303900000C010007312E302E302E3000004D01001C2E4E45544672616D65776F726B2C56657273696F6E3D76342E352E320100540E144672616D65776F726B446973706C61794E616D65142E4E4554204672616D65776F726B20342E352E32808F010001005455794D6963726F736F66742E53716C5365727665722E5365727665722E446174614163636573734B696E642C2053797374656D2E446174612C2056657273696F6E3D342E302E302E302C2043756C747572653D6E65757472616C2C205075626C69634B6579546F6B656E3D623737613563353631393334653038390A4461746141636365737301000000000000982700000000000000000000B2270000002000000000000000000000000000000000000000000000A4270000000000000000000000005F436F72446C6C4D61696E006D73636F7265652E646C6C0000000000FF25002000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001001000000018000080000000000000000000000000000001000100000030000080000000000000000000000000000001000000000048000000584000003C03000000000000000000003C0334000000560053005F00560045005200530049004F004E005F0049004E0046004F0000000000BD04EFFE00000100000001000000000000000100000000003F000000000000000400000002000000000000000000000000000000440000000100560061007200460069006C00650049006E0066006F00000000002400040000005400720061006E0073006C006100740069006F006E00000000000000B0049C020000010053007400720069006E006700460069006C00650049006E0066006F0000007802000001003000300030003000300034006200300000001A000100010043006F006D006D0065006E007400730000000000000022000100010043006F006D00700061006E0079004E0061006D006500000000000000000042000D000100460069006C0065004400650073006300720069007000740069006F006E0000000000530051004C00460075006E006300740069006F006E00730000000000300008000100460069006C006500560065007200730069006F006E000000000031002E0030002E0030002E003000000042001100010049006E007400650072006E0061006C004E0061006D0065000000530051004C00460075006E006300740069006F006E0073002E0064006C006C00000000004800120001004C006500670061006C0043006F007000790072006900670068007400000043006F0070007900720069006700680074002000A90020002000320030003200300000002A00010001004C006500670061006C00540072006100640065006D00610072006B00730000000000000000004A00110001004F0072006900670069006E0061006C00460069006C0065006E0061006D0065000000530051004C00460075006E006300740069006F006E0073002E0064006C006C00000000003A000D000100500072006F0064007500630074004E0061006D00650000000000530051004C00460075006E006300740069006F006E00730000000000340008000100500072006F006400750063007400560065007200730069006F006E00000031002E0030002E0030002E003000000038000800010041007300730065006D0062006C0079002000560065007200730069006F006E00000031002E0030002E0030002E0030000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000C000000C43700000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
WITH PERMISSION_SET = SAFE

go

CREATE FUNCTION RegexReplace(
    @input nvarchar(max),
    @pattern nvarchar(max),
    @replacement nvarchar(max)
) RETURNS nvarchar  (max)
AS EXTERNAL NAME SQLFunctions.[SQLFunctions.Regex].Replace; 

go

-- outputs This is a test 
select dbo.RegexReplace('This is a test 12345','[0-9]','')

Content of the DLL: enter image description here

Is std::vector copying the objects with a push_back?

From C++11 onwards, all the standard containers (std::vector, std::map, etc) support move semantics, meaning that you can now pass rvalues to standard containers and avoid a copy:

// Example object class.
class object
{
private:
    int             m_val1;
    std::string     m_val2;

public:
    // Constructor for object class.
    object(int val1, std::string &&val2) :
        m_val1(val1),
        m_val2(std::move(val2))
    {

    }
};

std::vector<object> myList;

// #1 Copy into the vector.
object foo1(1, "foo");
myList.push_back(foo1);

// #2 Move into the vector (no copy).
object foo2(1024, "bar");
myList.push_back(std::move(foo2));

// #3 Move temporary into vector (no copy).
myList.push_back(object(453, "baz"));

// #4 Create instance of object directly inside the vector (no copy, no move).
myList.emplace_back(453, "qux");

Alternatively you can use various smart pointers to get mostly the same effect:

std::unique_ptr example

std::vector<std::unique_ptr<object>> myPtrList;

// #5a unique_ptr can only ever be moved.
auto pFoo = std::make_unique<object>(1, "foo");
myPtrList.push_back(std::move(pFoo));

// #5b unique_ptr can only ever be moved.
myPtrList.push_back(std::make_unique<object>(1, "foo"));

std::shared_ptr example

std::vector<std::shared_ptr<object>> objectPtrList2;

// #6 shared_ptr can be used to retain a copy of the pointer and update both the vector
// value and the local copy simultaneously.
auto pFooShared = std::make_shared<object>(1, "foo");
objectPtrList2.push_back(pFooShared);
// Pointer to object stored in the vector, but pFooShared is still valid.

Why do you need to put #!/bin/bash at the beginning of a script file?

It is called a shebang. It consists of a number sign and an exclamation point character (#!), followed by the full path to the interpreter such as /bin/bash. All scripts under UNIX and Linux execute using the interpreter specified on a first line.

How can I resize an image using Java?

Java Advanced Imaging is now open source, and provides the operations you need.

Good MapReduce examples

From time to time I present MR concepts to people. I find processing tasks familiar to people and then map them to the MR paradigm.

Usually I take two things:

  1. Group By / Aggregations. Here the advantage of the shuffling stage is clear. An explanation that shuffling is also distributed sort + an explanation of distributed sort algorithm also helps.

  2. Join of two tables. People working with DB are familiar with the concept and its scalability problem. Show how it can be done in MR.

What is so bad about singletons?

The singleton pattern is not a problem in itself. The problem is that the pattern is often used by people developing software with object-oriented tools without having a solid grasp of OO concepts. When singletons are introduced in this context they tend to grow into unmanageable classes that contain helper methods for every little use.

Singletons are also a problem from a testing perspective. They tend to make isolated unit-tests difficult to write. Inversion of control (IoC) and dependency injection are patterns meant to overcome this problem in an object-oriented manner that lends itself to unit testing.

In a garbage collected environment singletons can quickly become an issue with regard to memory management.

There is also the multi-threaded scenario where singletons can become a bottleneck as well as a synchronization issue.

What is the error "Every derived table must have its own alias" in MySQL?

I think it's asking you to do this:

SELECT ID
FROM (SELECT ID,
             msisdn 
      FROM (SELECT * FROM TT2) as myalias
     ) as anotheralias;

But why would you write this query in the first place?

How to automatically generate a stacktrace when my program crashes

Look at:

man 3 backtrace

And:

#include <exeinfo.h>
int backtrace(void **buffer, int size);

These are GNU extensions.

What is callback in Android?

CallBack Interface are used for Fragment to Fragment communication in android.

Refer here for your understanding.

GitLab git user password

After adding the new SSH Key in GitLab, check if you have "git" group included in SSHD AllowGroups (for Debian /etc/ssh/sshd_config). If not, add it and restart sshd (systemctl restart ssh).

Test it with ssh -vT [email protected] as suggested above.

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

As ams said above, don't take a pointer to a member of a struct that's packed. This is simply playing with fire. When you say __attribute__((__packed__)) or #pragma pack(1), what you're really saying is "Hey gcc, I really know what I'm doing." When it turns out that you do not, you can't rightly blame the compiler.

Perhaps we can blame the compiler for it's complacency though. While gcc does have a -Wcast-align option, it isn't enabled by default nor with -Wall or -Wextra. This is apparently due to gcc developers considering this type of code to be a brain-dead "abomination" unworthy of addressing -- understandable disdain, but it doesn't help when an inexperienced programmer bumbles into it.

Consider the following:

struct  __attribute__((__packed__)) my_struct {
    char c;
    int i;
};

struct my_struct a = {'a', 123};
struct my_struct *b = &a;
int c = a.i;
int d = b->i;
int *e __attribute__((aligned(1))) = &a.i;
int *f = &a.i;

Here, the type of a is a packed struct (as defined above). Similarly, b is a pointer to a packed struct. The type of of the expression a.i is (basically) an int l-value with 1 byte alignment. c and d are both normal ints. When reading a.i, the compiler generates code for unaligned access. When you read b->i, b's type still knows it's packed, so no problem their either. e is a pointer to a one-byte-aligned int, so the compiler knows how to dereference that correctly as well. But when you make the assignment f = &a.i, you are storing the value of an unaligned int pointer in an aligned int pointer variable -- that's where you went wrong. And I agree, gcc should have this warning enabled by default (not even in -Wall or -Wextra).

How to print colored text to the terminal?

On Windows you can use module 'win32console' (available in some Python distributions) or module 'ctypes' (Python 2.5 and up) to access the Win32 API.

To see complete code that supports both ways, see the color console reporting code from Testoob.

ctypes example:

import ctypes

# Constants from the Windows API
STD_OUTPUT_HANDLE = -11
FOREGROUND_RED    = 0x0004 # text color contains red.

def get_csbi_attributes(handle):
    # Based on IPython's winconsole.py, written by Alexander Belchenko
    import struct
    csbi = ctypes.create_string_buffer(22)
    res = ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, csbi)
    assert res

    (bufx, bufy, curx, cury, wattr,
    left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
    return wattr


handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
reset = get_csbi_attributes(handle)

ctypes.windll.kernel32.SetConsoleTextAttribute(handle, FOREGROUND_RED)
print "Cherry on top"
ctypes.windll.kernel32.SetConsoleTextAttribute(handle, reset)

Import SQL file by command line in Windows 7

To import database from dump file use:

mysql -u UserName -p Password DatabaseName < FileName.sql 

In wamp

C:\wamp\bin\mysql\mysql5.0.51b\bin>mysql mysql -uroot -p DatabaseName < FileName.sql 

Find a file with a certain extension in folder

Look at the System.IO.Directory class and the static method GetFiles. It has an overload that accepts a path and a search pattern. Example:

 string[] files = System.IO.Directory.GetFiles(path, "*.txt");

How to force open links in Chrome not download them?

Great question.

It can be achieved via an extension:

"This SqlTransaction has completed; it is no longer usable."... configuration error?

I had this recently after refactoring in a new connection manager. A new routine accepted a transaction so it could be run as part of a batch, problem was with a using block:

public IEnumerable<T> Query<T>(IDbTransaction transaction, string command, dynamic param = null)
{
  using (transaction.Connection)
  {
    using (transaction)
    {
      return transaction.Connection.Query<T>(command, new DynamicParameters(param), transaction, commandType: CommandType.StoredProcedure);
    }
  }
}

It looks as though the outer using was closing the underlying connection thus any attempts to commit or rollback the transaction threw up the message "This SqlTransaction has completed; it is no longer usable."

I removed the usings added a covering test and the problem went away.

public IEnumerable<T> Query<T>(IDbTransaction transaction, string command, dynamic param = null)
{
  return transaction.Connection.Query<T>(command, new DynamicParameters(param), transaction, commandType: CommandType.StoredProcedure);
}

Check for anything that might be closing the connection while inside the context of a transaction.

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

Well for me the problem got resolved by adding the jars in my APACHE/TOMCAT/lib folder ! .

How do I write stderr to a file while using "tee" with a pipe?

I'm assuming you want to still see STDERR and STDOUT on the terminal. You could go for Josh Kelley's answer, but I find keeping a tail around in the background which outputs your log file very hackish and cludgy. Notice how you need to keep an exra FD and do cleanup afterward by killing it and technically should be doing that in a trap '...' EXIT.

There is a better way to do this, and you've already discovered it: tee.

Only, instead of just using it for your stdout, have a tee for stdout and one for stderr. How will you accomplish this? Process substitution and file redirection:

command > >(tee -a stdout.log) 2> >(tee -a stderr.log >&2)

Let's split it up and explain:

> >(..)

>(...) (process substitution) creates a FIFO and lets tee listen on it. Then, it uses > (file redirection) to redirect the STDOUT of command to the FIFO that your first tee is listening on.

Same thing for the second:

2> >(tee -a stderr.log >&2)

We use process substitution again to make a tee process that reads from STDIN and dumps it into stderr.log. tee outputs its input back on STDOUT, but since its input is our STDERR, we want to redirect tee's STDOUT to our STDERR again. Then we use file redirection to redirect command's STDERR to the FIFO's input (tee's STDIN).

See http://mywiki.wooledge.org/BashGuide/InputAndOutput

Process substitution is one of those really lovely things you get as a bonus of choosing bash as your shell as opposed to sh (POSIX or Bourne).


In sh, you'd have to do things manually:

out="${TMPDIR:-/tmp}/out.$$" err="${TMPDIR:-/tmp}/err.$$"
mkfifo "$out" "$err"
trap 'rm "$out" "$err"' EXIT
tee -a stdout.log < "$out" &
tee -a stderr.log < "$err" >&2 &
command >"$out" 2>"$err"

How to do a subquery in LINQ?

Ok, here's a basic join query that gets the correct records:

   int[] selectedRolesArr = GetSelectedRoles();
    if( selectedRolesArr != null && selectedRolesArr.Length > 0 ) 
    {

    //this join version requires the use of distinct to prevent muliple records
        //being returned for users with more than one company role.
    IQueryable retVal = (from u in context.Users
                        join c in context.CompanyRolesToUsers
                          on u.Id equals c.UserId
                        where u.LastName.Contains( "fra" ) &&
                            selectedRolesArr.Contains( c.CompanyRoleId )
                        select  u).Distinct();
}

But here's the code that most easily integrates with the algorithm that we already had in place:

int[] selectedRolesArr = GetSelectedRoles(); 
if ( useAnd ) 
       { 
          predicateAnd = predicateAnd.And( u => (from c in context.CompanyRolesToUsers 
                       where selectedRolesArr.Contains(c.CompanyRoleId) 
                       select c.UserId).Contains(u.Id)); 
        } 
        else 
        { 
           predicateOr = predicateOr.Or( u => (from c in context.CompanyRolesToUsers 
                          where selectedRolesArr.Contains(c.CompanyRoleId) 
                         select c.UserId).Contains(u.Id) ); 
        } 

which is thanks to a poster at the LINQtoSQL forum

Jquery Ajax Posting json to webservice

I have encountered this one too and this is my solution.

If you are encountering an invalid json object exception when parsing data, even though you know that your json string is correct, stringify the data you received in your ajax code before parsing it to JSON:

$.post(CONTEXT+"servlet/capture",{
        yesTransactionId : yesTransactionId, 
        productOfferId : productOfferId
        },
        function(data){
            try{
                var trimData = $.trim(JSON.stringify(data));
                var obj      = $.parseJSON(trimData);
                if(obj.success == 'true'){ 
                    //some codes ...

how to print json data in console.log

To output an object to the console, you have to stringify the object first:

success:function(data){
     console.log(JSON.stringify(data));
}

Reset Excel to default borders

In case anyone still needs the VBA way of doing this:

The properties, assuming you selected something, are:

With Selection
    .interior.pattern = xlNone
    .Borders(xl<side>).Linestyle = xlNone
End Selection

Where <side> can be for example DiagonalDown or EdgeTop, so

-> Selection.Borders(xlEdgeTop).Linestyle = xlNone

would reset the Top Edge.

How to switch between hide and view password

In very simple form:

private fun updatePasswordVisibility(editText: AppCompatEditText) {
        if (editText.transformationMethod is PasswordTransformationMethod) {
            editText.transformationMethod = null
        } else {
            editText.transformationMethod = PasswordTransformationMethod()
        }
        editText.setSelection(editText.length())
    }

Hope it helps.

How to uncheck checkbox using jQuery Uniform library

checkbox that act like radio btn

$(".checkgroup").live('change',function() { var previous=this.checked; $(".checkgroup).attr("checked", false); $(this).attr("checked", previous); });

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Happy coding..

SQL Server - NOT IN

SELECT  *  FROM Table1 
WHERE MAKE+MODEL+[Serial Number]  not in
    (select make+model+[serial number] from Table2 
     WHERE make+model+[serial number] IS NOT NULL)

That worked for me, where make+model+[serial number] was one field name

What exactly is Spring Framework for?

Very short summarized, I will say that Spring is the "glue" in your application. It's used to integrate different frameworks and your own code.