Programs & Examples On #Uitoolbar

A toolbar is a control that displays one or more buttons, called toolbar items. A toolbar momentarily highlights or does not change the appearance of an item when tapped.

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

I found that using the following, simple code did the trick (requires custom image in bundle):

// Creates a back button instead of default behaviour (displaying title of previous screen)
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_arrow.png"]
                                                                   style:UIBarButtonItemStyleBordered
                                                                  target:self
                                                                  action:@selector(backAction)];

    tipsDetailViewController.navigationItem.leftBarButtonItem = backButton;
    [backButton release];

How do I show/hide a UIBarButtonItem?

It is possible to hide a button in place without changing its width or removing it from the bar. If you set the style to plain, remove the title, and disable the button, it will disappear. To restore it, just reverse your changes.

-(void)toggleBarButton:(bool)show
{
    if (show) {
        btn.style = UIBarButtonItemStyleBordered;
        btn.enabled = true;
        btn.title = @"MyTitle";
    } else {
        btn.style = UIBarButtonItemStylePlain;
        btn.enabled = false;
        btn.title = nil;
    }
}

How do I determine file encoding in OS X?

Synalyze It! allows to compare text or bytes in all encodings the ICU library offers. Using that feature you usually see immediately which code page makes sense for your data.

Pandas DataFrame column to list

You can use the Series.to_list method.

For example:

import pandas as pd

df = pd.DataFrame({'a': [1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9],
                   'b': [3, 5, 6, 2, 4, 6, 7, 8, 7, 8, 9]})

print(df['a'].to_list())

Output:

[1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9]

To drop duplicates you can do one of the following:

>>> df['a'].drop_duplicates().to_list()
[1, 3, 5, 7, 4, 6, 8, 9]
>>> list(set(df['a'])) # as pointed out by EdChum
[1, 3, 4, 5, 6, 7, 8, 9]

Calling a function from a string in C#

A slight tangent -- if you want to parse and evaluate an entire expression string which contains (nested!) functions, consider NCalc (http://ncalc.codeplex.com/ and nuget)

Ex. slightly modified from the project documentation:

// the expression to evaluate, e.g. from user input (like a calculator program, hint hint college students)
var exprStr = "10 + MyFunction(3, 6)";
Expression e = new Expression(exprString);

// tell it how to handle your custom function
e.EvaluateFunction += delegate(string name, FunctionArgs args) {
        if (name == "MyFunction")
            args.Result = (int)args.Parameters[0].Evaluate() + (int)args.Parameters[1].Evaluate();
    };

// confirm it worked
Debug.Assert(19 == e.Evaluate());

And within the EvaluateFunction delegate you would call your existing function.

When creating a service with sc.exe how to pass in context parameters?

sc create <servicename> binpath= "<pathtobinaryexecutable>" [option1] [option2] [optionN]

The trick is to leave a space after the = in your create statement, and also to use " " for anything containing special characters or spaces.

It is advisable to specify a Display Name for the service as well as setting the start setting to auto so that it starts automatically. You can do this by specifying DisplayName= yourdisplayname and start= auto in your create statement.

Here is an example:

C:\Documents and Settings\Administrator> sc create asperacentral 
binPath= "C:\Program Files\Aspera\Enterprise Server\bin\Debug\asperacentral.exe" 
DisplayName= "Aspera Central" 
start= auto

If this worked you should see:

[SC] CreateService SUCCESS

UPDATE 1

http://support.microsoft.com/kb/251192

How to run a script at a certain time on Linux?

The at command exists specifically for this purpose (unlike cron which is intended for scheduling recurring tasks).

at $(cat file) </path/to/script

How to get html to print return value of javascript function?

if you really wanted to do that you could then do

<script type="text/javascript">
    document.write(produceMessage())
</script>

Wherever in the document you want the message.

Maven plugin not using Eclipse's proxy settings

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">

     <proxies>
       <proxy>
          <active>true</active>
          <protocol>http</protocol>
          <host>proxy.somewhere.com</host>
          <port>8080</port>
          <username>proxyuser</username>
          <password>somepassword</password>
          <nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts>
        </proxy>
      </proxies>

    </settings>

Window > Preferences > Maven > User Settings

enter image description here

CSS Animation onClick

You just use the :active pseudo-class. This is set when you click on any element.

.classname:active {
    /* animation css */
}

The following classes could not be instantiated: - android.support.v7.widget.Toolbar

Find styles.xml in app/res/values folder.

Parent attribute of the style could be missing "Base". It should start as

<style name="AppTheme" parent="Base.Theme.AppCompat...

How to return a resolved promise from an AngularJS Service using $q?

Return your promise , return deferred.promise.
It is the promise API that has the 'then' method.

https://docs.angularjs.org/api/ng/service/$q

Calling resolve does not return a promise it only signals the promise that the promise is resolved so it can execute the 'then' logic.

Basic pattern as follows, rinse and repeat
http://plnkr.co/edit/fJmmEP5xOrEMfLvLWy1h?p=preview

<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.3.0-beta.5" 
        src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script src="script.js"></script>
</head>

<body>

<div ng-controller="test">
  <button ng-click="test()">test</button>
</div>
<script>
  var app = angular.module("app",[]);

  app.controller("test",function($scope,$q){

    $scope.$test = function(){
      var deferred = $q.defer();
      deferred.resolve("Hi");
      return deferred.promise;
    };

    $scope.test=function(){
      $scope.$test()
      .then(function(data){
        console.log(data);
      });
    }      
  });

  angular.bootstrap(document,["app"]);

</script>

Can someone explain __all__ in Python?

Explain __all__ in Python?

I keep seeing the variable __all__ set in different __init__.py files.

What does this do?

What does __all__ do?

It declares the semantically "public" names from a module. If there is a name in __all__, users are expected to use it, and they can have the expectation that it will not change.

It also will have programmatic affects:

import *

__all__ in a module, e.g. module.py:

__all__ = ['foo', 'Bar']

means that when you import * from the module, only those names in the __all__ are imported:

from module import *               # imports foo and Bar

Documentation tools

Documentation and code autocompletion tools may (in fact, should) also inspect the __all__ to determine what names to show as available from a module.

__init__.py makes a directory a Python package

From the docs:

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable.

So the __init__.py can declare the __all__ for a package.

Managing an API:

A package is typically made up of modules that may import one another, but that are necessarily tied together with an __init__.py file. That file is what makes the directory an actual Python package. For example, say you have the following files in a package:

package
+-- __init__.py
+-- module_1.py
+-- module_2.py

Let's create these files with Python so you can follow along - you could paste the following into a Python 3 shell:

from pathlib import Path

package = Path('package')
package.mkdir()

(package / '__init__.py').write_text("""
from .module_1 import *
from .module_2 import *
""")

package_module_1 = package / 'module_1.py'
package_module_1.write_text("""
__all__ = ['foo']
imp_detail1 = imp_detail2 = imp_detail3 = None
def foo(): pass
""")

package_module_2 = package / 'module_2.py'
package_module_2.write_text("""
__all__ = ['Bar']
imp_detail1 = imp_detail2 = imp_detail3 = None
class Bar: pass
""")

And now you have presented a complete api that someone else can use when they import your package, like so:

import package
package.foo()
package.Bar()

And the package won't have all the other implementation details you used when creating your modules cluttering up the package namespace.

__all__ in __init__.py

After more work, maybe you've decided that the modules are too big (like many thousands of lines?) and need to be split up. So you do the following:

package
+-- __init__.py
+-- module_1
¦   +-- foo_implementation.py
¦   +-- __init__.py
+-- module_2
    +-- Bar_implementation.py
    +-- __init__.py

First make the subpackage directories with the same names as the modules:

subpackage_1 = package / 'module_1'
subpackage_1.mkdir()
subpackage_2 = package / 'module_2'
subpackage_2.mkdir()

Move the implementations:

package_module_1.rename(subpackage_1 / 'foo_implementation.py')
package_module_2.rename(subpackage_2 / 'Bar_implementation.py')

create __init__.pys for the subpackages that declare the __all__ for each:

(subpackage_1 / '__init__.py').write_text("""
from .foo_implementation import *
__all__ = ['foo']
""")
(subpackage_2 / '__init__.py').write_text("""
from .Bar_implementation import *
__all__ = ['Bar']
""")

And now you still have the api provisioned at the package level:

>>> import package
>>> package.foo()
>>> package.Bar()
<package.module_2.Bar_implementation.Bar object at 0x7f0c2349d210>

And you can easily add things to your API that you can manage at the subpackage level instead of the subpackage's module level. If you want to add a new name to the API, you simply update the __init__.py, e.g. in module_2:

from .Bar_implementation import *
from .Baz_implementation import *
__all__ = ['Bar', 'Baz']

And if you're not ready to publish Baz in the top level API, in your top level __init__.py you could have:

from .module_1 import *       # also constrained by __all__'s
from .module_2 import *       # in the __init__.py's
__all__ = ['foo', 'Bar']     # further constraining the names advertised

and if your users are aware of the availability of Baz, they can use it:

import package
package.Baz()

but if they don't know about it, other tools (like pydoc) won't inform them.

You can later change that when Baz is ready for prime time:

from .module_1 import *
from .module_2 import *
__all__ = ['foo', 'Bar', 'Baz']

Prefixing _ versus __all__:

By default, Python will export all names that do not start with an _. You certainly could rely on this mechanism. Some packages in the Python standard library, in fact, do rely on this, but to do so, they alias their imports, for example, in ctypes/__init__.py:

import os as _os, sys as _sys

Using the _ convention can be more elegant because it removes the redundancy of naming the names again. But it adds the redundancy for imports (if you have a lot of them) and it is easy to forget to do this consistently - and the last thing you want is to have to indefinitely support something you intended to only be an implementation detail, just because you forgot to prefix an _ when naming a function.

I personally write an __all__ early in my development lifecycle for modules so that others who might use my code know what they should use and not use.

Most packages in the standard library also use __all__.

When avoiding __all__ makes sense

It makes sense to stick to the _ prefix convention in lieu of __all__ when:

  • You're still in early development mode and have no users, and are constantly tweaking your API.
  • Maybe you do have users, but you have unittests that cover the API, and you're still actively adding to the API and tweaking in development.

An export decorator

The downside of using __all__ is that you have to write the names of functions and classes being exported twice - and the information is kept separate from the definitions. We could use a decorator to solve this problem.

I got the idea for such an export decorator from David Beazley's talk on packaging. This implementation seems to work well in CPython's traditional importer. If you have a special import hook or system, I do not guarantee it, but if you adopt it, it is fairly trivial to back out - you'll just need to manually add the names back into the __all__

So in, for example, a utility library, you would define the decorator:

import sys

def export(fn):
    mod = sys.modules[fn.__module__]
    if hasattr(mod, '__all__'):
        mod.__all__.append(fn.__name__)
    else:
        mod.__all__ = [fn.__name__]
    return fn

and then, where you would define an __all__, you do this:

$ cat > main.py
from lib import export
__all__ = [] # optional - we create a list if __all__ is not there.

@export
def foo(): pass

@export
def bar():
    'bar'

def main():
    print('main')

if __name__ == '__main__':
    main()

And this works fine whether run as main or imported by another function.

$ cat > run.py
import main
main.main()

$ python run.py
main

And API provisioning with import * will work too:

$ cat > run.py
from main import *
foo()
bar()
main() # expected to error here, not exported

$ python run.py
Traceback (most recent call last):
  File "run.py", line 4, in <module>
    main() # expected to error here, not exported
NameError: name 'main' is not defined

How to read all of Inputstream in Server Socket JAVA

int c;
    String raw = "";
    do {
        c = inputstream.read();
        raw+=(char)c;
    } while(inputstream.available()>0);

InputStream.available() shows the available bytes only after one byte is read, hence do .. while

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

How to force a checkbox and text on the same line?

You can wrap the label around the input:

 **<label for="a"><input type="checkbox" id="a">a</label>**

This worked for me.

Encrypting & Decrypting a String in C#

You may be looking for the ProtectedData class, which encrypts data using the user's logon credentials.

Connecting to Oracle Database through C#?

Using Nuget

  1. Right click Project, select Manage NuGet packages...
  2. Select the Browse tab, search for Oracle and install Oracle.ManagedDataAccess

Oracle NuGet package

  1. In code use the following command (Ctrl+. to automatically add the using directive).

  2. Note the different DataSource string which in comparison to Java is different.

    // create connection
    OracleConnection con = new OracleConnection();
    
    // create connection string using builder
    OracleConnectionStringBuilder ocsb = new OracleConnectionStringBuilder();
    ocsb.Password = "autumn117";
    ocsb.UserID = "john";
    ocsb.DataSource = "database.url:port/databasename";
    
    // connect
    con.ConnectionString = ocsb.ConnectionString;
    con.Open();
    Console.WriteLine("Connection established (" + con.ServerVersion + ")");
    

How to set default font family in React Native?

Super late to this thread but here goes.

TLDR; Add the following block in your AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

 ....
    // HERE: replace "Verlag" with your font
  [[UILabel appearance] setFont:[UIFont fontWithName:@"Verlag" size:17.0]];
  ....
}

Walkthrough of the whole flow.

A few ways you can do this outside of using a plugin like react-native-global-props so Ill walk you though step by step.

Adding fonts to platforms.

How to add the font to IOS project

First let's create a location for our assets. Let's make the following directory at our root.

```

ios/
static/
       fonts/

```

Now let's add a "React Native" NPM in our package.json

  "rnpm": {
    "static": [
   "./static/fonts/"
    ]
  }

Now we can run "react-native link" to add our assets to our native apps.

Verifying or doing manually.

That should add your font names into the projects .plist (for VS code users run code ios/*/Info.plist to confirm)

Here let's assume Verlag is the font you added, it should look something like this:

     <dict>
   <plist>
      .....
      <key>UIAppFonts</key>
      <array>
         <string>Verlag Bold Italic.otf</string>
         <string>Verlag Book Italic.otf</string>
         <string>Verlag Light.otf</string>
         <string>Verlag XLight Italic.otf</string>
         <string>Verlag XLight.otf</string>
         <string>Verlag-Black.otf</string>
         <string>Verlag-BlackItalic.otf</string>
         <string>Verlag-Bold.otf</string>
         <string>Verlag-Book.otf</string>
         <string>Verlag-LightItalic.otf</string>
      </array>
      ....    
</dict>
</plist>

Now that you mapped them, now let's make sure they are actually there and being loaded (this is also how you'd do it manually).

Go to "Build Phase" > "Copy Bundler Resource", If it didn't work you'll a manually add under them here.

1_uuz0__3kx2vvguz37bhvya

Get Font Names (recognized by XCode)

First open your XCode logs, like:

XXXX

Then you can add the following block in your AppDelegate.m to log the names of the Fonts and the Font Family.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    .....


  for (NSString* family in [UIFont familyNames])
  {
    NSLog(@"%@", family);
    for (NSString* name in [UIFont fontNamesForFamilyName: family])
    {
      NSLog(@" %@", name);
    }
  }

  ...
}

Once you run you should find your fonts if loaded correctly, here we found ours in logs like this:

2018-05-07 10:57:04.194127-0700 MyApp[84024:1486266] Verlag
2018-05-07 10:57:04.194266-0700 MyApp[84024:1486266]  Verlag-Book
2018-05-07 10:57:04.194401-0700 MyApp[84024:1486266]  Verlag-BlackItalic
2018-05-07 10:57:04.194516-0700 MyApp[84024:1486266]  Verlag-BoldItalic
2018-05-07 10:57:04.194616-0700 MyApp[84024:1486266]  Verlag-XLight
2018-05-07 10:57:04.194737-0700 MyApp[84024:1486266]  Verlag-Bold
2018-05-07 10:57:04.194833-0700 MyApp[84024:1486266]  Verlag-Black
2018-05-07 10:57:04.194942-0700 MyApp[84024:1486266]  Verlag-XLightItalic
2018-05-07 10:57:04.195170-0700 MyApp[84024:1486266]  Verlag-LightItalic
2018-05-07 10:57:04.195327-0700 MyApp[84024:1486266]  Verlag-BookItalic
2018-05-07 10:57:04.195510-0700 MyApp[84024:1486266]  Verlag-Light

So now we know it loaded the Verlag family and are the fonts inside that family

  • Verlag-Book
  • Verlag-BlackItalic
  • Verlag-BoldItalic
  • Verlag-XLight
  • Verlag-Bold
  • Verlag-Black
  • Verlag-XLightItalic
  • Verlag-LightItalic
  • Verlag-BookItalic
  • Verlag-Light

These are now the case sensitive names we can use in our font family we can use in our react native app.

Got -'em now set default font.

Then to set a default font to add your font family name in your AppDelegate.m with this line

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

 ....
    // ADD THIS LINE (replace "Verlag" with your font)

  [[UILabel appearance] setFont:[UIFont fontWithName:@"Verlag" size:17.0]];
  ....
}

Done.

Python - TypeError: 'int' object is not iterable

Your problem is with this line:

number4 = list(cow[n])

It tries to take cow[n], which returns an integer, and make it a list. This doesn't work, as demonstrated below:

>>> a = 1
>>> list(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>

Perhaps you meant to put cow[n] inside a list:

number4 = [cow[n]]

See a demonstration below:

>>> a = 1
>>> [a]
[1]
>>>

Also, I wanted to address two things:

  1. Your while-statement is missing a : at the end.
  2. It is considered very dangerous to use input like that, since it evaluates its input as real Python code. It would be better here to use raw_input and then convert the input to an integer with int.

To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use sum:

>>> a = 137
>>> a = str(a)
>>> # This way is more common and preferred
>>> sum(int(x) for x in a)
11
>>> # But this also works
>>> sum(map(int, a))
11
>>>

'Found the synthetic property @panelState. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'

The animation should be applied on the specific component.

EX : Using animation directive in other component and provided in another.

CompA --- @Component ({



animations : [animation] }) CompA --- @Component ({



animations : [animation] <=== this should be provided in used component })

How to make Java 6, which fails SSL connection with "SSL peer shut down incorrectly", succeed like Java 7?

Remove "SSLv2ClientHello" from the enabled protocols on the client SSLSocket or HttpsURLConnection.

Bootstrap Navbar toggle button not working

Wasted several hours only to realize that viewport meta was missing from my code. Adding here just in case some one else misses it out.

As soon as I added this, the toggle started working fine.

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

Remove all spaces from a string in SQL Server

This does the trick of removing the spaces on the strings:

UPDATE
    tablename
SET
    columnname = replace(columnname, ' ', '');

The following artifacts could not be resolved: javax.jms:jms:jar:1.1

Log4 version 1.2.17 automatically resolves the issue as it has depency on geronimo-jms. I got the same issue with log4j- 1.2.15 version.


Added with more around the issue


using 1.2.17 resolved the issue during the compile time but the server(Karaf) was using 1.2.15 version thus creating conflict at run time. Thus I had to switch back to 1.2.15.

The JMS and JMX api were available for me at the runtime thus i did not import the J2ee api.

what i did was I used the compile time dependency on 1.2.17 but removed it at the runtime.

            <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
....
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
                                                          <Import-Package>!org.apache.log4j.*,*</Import-Package>

.....

How to get the filename without the extension in Java?

Here is the consolidated list order by my preference.

Using apache commons

import org.apache.commons.io.FilenameUtils;

String fileNameWithoutExt = FilenameUtils.getBaseName(fileName);
                          
                           OR

String fileNameWithOutExt = FilenameUtils.removeExtension(fileName);

Using Google Guava (If u already using it)

import com.google.common.io.Files;
String fileNameWithOutExt = Files.getNameWithoutExtension(fileName);

Files.getNameWithoutExtension

Or using Core Java

1)

String fileName = file.getName();
int pos = fileName.lastIndexOf(".");
if (pos > 0 && pos < (fileName.length() - 1)) { // If '.' is not the first or last character.
    fileName = fileName.substring(0, pos);
}
if (fileName.indexOf(".") > 0) {
   return fileName.substring(0, fileName.lastIndexOf("."));
} else {
   return fileName;
}
private static final Pattern ext = Pattern.compile("(?<=.)\\.[^.]+$");

public static String getFileNameWithoutExtension(File file) {
    return ext.matcher(file.getName()).replaceAll("");
}

Liferay API

import com.liferay.portal.kernel.util.FileUtil; 
String fileName = FileUtil.stripExtension(file.getName());

How to extract the nth word and count word occurrences in a MySQL string?

I don't think such a thing is possible. You can use SUBSTRING function to extract the part you want.

Truncate Two decimal places without rounding

It would be more useful to have a full function for real-world usage of truncating a decimal in C#. This could be converted to a Decimal extension method pretty easy if you wanted:

public decimal TruncateDecimal(decimal value, int precision)
{
    decimal step = (decimal)Math.Pow(10, precision);
    decimal tmp = Math.Truncate(step * value);
    return tmp / step;
}

If you need VB.NET try this:

Function TruncateDecimal(value As Decimal, precision As Integer) As Decimal
    Dim stepper As Decimal = Math.Pow(10, precision)
    Dim tmp As Decimal = Math.Truncate(stepper * value)
    Return tmp / stepper
End Function

Then use it like so:

decimal result = TruncateDecimal(0.275, 2);

or

Dim result As Decimal = TruncateDecimal(0.275, 2)

Convert String to Float in Swift

In swift 4

let Totalname = "10.0" //Now it is in string

let floatVal  = (Totalname as NSString).floatValue //Now converted to float

Adding image inside table cell in HTML

There are some syntax errors on your HTML.

First, the URL of the image needs to point to an address on the public Internet. The users viewing your page won't have your hard drive, so pointing to a file on your local hard drive cannot work. Replace C:\Pics with the actual URL of the image, not a path on development machine filesystem. If you want to be absolutely sure, use a different computer and paste the img tag src attribute value to the address bar of the browser. If it works there, then you're good. Do not that the path can be relative and still valid, but then it needs to be relative to the public URL of the web page it's embedded in.

Second, the <title> tag. You need to add this tag if you need a title on the browser, and you can't format it.

The third error, if about the <th> tag, you have to add this header inside a <tr> tag, because <th> needs a row (create by <tr>).

Another thing is, you don't need all colspan you did.

I tried to do a valid html as you need. Take a look:

<!DOCTYPE html> 
<html>
<head>
    <title>CAR APPLICATION</title>
</head>
<body>
    <center>
        <h1>CAR APPLICATION</h1>
    </center>

    <table border="5" bordercolor="red" align="center">
        <tr>
            <th colspan="3">SONAKSHI RAINA 10B ROLL No:-32</th> 
        </tr>
        <tr>
            <th>Name</th>
            <th>Origin</th>
            <th>Photo</th>
        </tr>
        <tr>
            <td>Bugatti Veyron Super Sport</td>
            <td>Molsheim, Alsace, France</td>
                    <!-- considering it is on the same folder that .html file -->
            <td><img src="H.gif" alt="" border=3 height=100 width=100></img></td>
        </tr>
        <tr>
            <td>SSC Ultimate Aero TT  TopSpeed</td>
            <td>United States</td>
            <td border=3 height=100 width=100>Photo1</td>
        </tr>
        <tr>
            <td>Koenigsegg CCX</td>
            <td>Ängelholm, Sweden</td>
            <td border=4 height=100 width=300>Photo1</td>
        </tr>
        <tr>
            <td>Saleen S7</td>
            <td>Irvine, California, United States</td>
            <td border=3 height=100 width=100>Photo1</td>
        </tr>
        <tr>
            <td> McLaren F1</td>
            <td>Surrey, England</td>
            <td border=3 height=100 width=100>Photo1</td>
        </tr>
        <tr>
            <td>Ferrari Enzo</td>
            <td>Maranello, Italy</td>
            <td border=3 height=100 width=100>Photo1</td>
        </tr>
        <tr>
            <td> Pagani Zonda F Clubsport</td>
            <td>Modena, Italy</td>
            <td border=3 height=100 width=100>Photo1</td>
        </tr>
    </table>
</body>
<html>

PostgreSQL Error: Relation already exists

There should be no single quotes here 'A'. Single quotes are for string literals: 'some value'.
Either use double quotes to preserve the upper case spelling of "A":

CREATE TABLE "A" ...

Or don't use quotes at all:

CREATE TABLE A ...

which is identical to

CREATE TABLE a ...

because all unquoted identifiers are folded to lower case automatically in PostgreSQL.


You could avoid problems with the index name completely by using simpler syntax:

CREATE TABLE csd_relationship (
    csd_relationship_id serial PRIMARY KEY,
    type_id integer NOT NULL,
    object_id integer NOT NULL
);

Does the same as your original query, only it avoids naming conflicts automatically. It picks the next free identifier automatically. More about the serial type in the manual.

Making HTML page zoom by default

A better solution is not to make your page dependable on zoom settings. If you set limits like the one you are proposing, you are limiting accessibility. If someone cannot read your text well, they just won't be able to change that. I would use proper CSS to make it look nice in any zoom.

If your really insist, take a look at this question on how to detect zoom level using JavaScript (nightmare!): How to detect page zoom level in all modern browsers?

Best practices for SQL varchar column length

In a sense you're right, although anything lower than 2^8 characters will still register as a byte of data.

If you account for the base character that leaves anything with a VARCHAR < 255 as consuming the same amount of space.

255 is a good baseline definition unless you particularly wish to curtail excessive input.

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

By Timestamp, I presume you mean java.sql.Timestamp. You will notice that this class has a constructor that accepts a long argument. You can parse this using the DateFormat class:

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("23/09/2007");
long time = date.getTime();
new Timestamp(time);

.NET Global exception handler in console application

If you have a single-threaded application, you can use a simple try/catch in the Main function, however, this does not cover exceptions that may be thrown outside of the Main function, on other threads, for example (as noted in other comments). This code demonstrates how an exception can cause the application to terminate even though you tried to handle it in Main (notice how the program exits gracefully if you press enter and allow the application to exit gracefully before the exception occurs, but if you let it run, it terminates quite unhappily):

static bool exiting = false;

static void Main(string[] args)
{
   try
   {
      System.Threading.Thread demo = new System.Threading.Thread(DemoThread);
      demo.Start();
      Console.ReadLine();
      exiting = true;
   }
   catch (Exception ex)
   {
      Console.WriteLine("Caught an exception");
   }
}

static void DemoThread()
{
   for(int i = 5; i >= 0; i--)
   {
      Console.Write("24/{0} =", i);
      Console.Out.Flush();
      Console.WriteLine("{0}", 24 / i);
      System.Threading.Thread.Sleep(1000);
      if (exiting) return;
   }
}

You can receive notification of when another thread throws an exception to perform some clean up before the application exits, but as far as I can tell, you cannot, from a console application, force the application to continue running if you do not handle the exception on the thread from which it is thrown without using some obscure compatibility options to make the application behave like it would have with .NET 1.x. This code demonstrates how the main thread can be notified of exceptions coming from other threads, but will still terminate unhappily:

static bool exiting = false;

static void Main(string[] args)
{
   try
   {
      System.Threading.Thread demo = new System.Threading.Thread(DemoThread);
      AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
      demo.Start();
      Console.ReadLine();
      exiting = true;
   }
   catch (Exception ex)
   {
      Console.WriteLine("Caught an exception");
   }
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
   Console.WriteLine("Notified of a thread exception... application is terminating.");
}

static void DemoThread()
{
   for(int i = 5; i >= 0; i--)
   {
      Console.Write("24/{0} =", i);
      Console.Out.Flush();
      Console.WriteLine("{0}", 24 / i);
      System.Threading.Thread.Sleep(1000);
      if (exiting) return;
   }
}

So in my opinion, the cleanest way to handle it in a console application is to ensure that every thread has an exception handler at the root level:

static bool exiting = false;

static void Main(string[] args)
{
   try
   {
      System.Threading.Thread demo = new System.Threading.Thread(DemoThread);
      demo.Start();
      Console.ReadLine();
      exiting = true;
   }
   catch (Exception ex)
   {
      Console.WriteLine("Caught an exception");
   }
}

static void DemoThread()
{
   try
   {
      for (int i = 5; i >= 0; i--)
      {
         Console.Write("24/{0} =", i);
         Console.Out.Flush();
         Console.WriteLine("{0}", 24 / i);
         System.Threading.Thread.Sleep(1000);
         if (exiting) return;
      }
   }
   catch (Exception ex)
   {
      Console.WriteLine("Caught an exception on the other thread");
   }
}

TSQL select into Temp table from dynamic sql

DECLARE @count_ser_temp int;
DECLARE @TableName AS VARCHAR(100)
SELECT @TableName = 'TableTemporal'

EXECUTE ('CREATE VIEW vTemp AS
    SELECT *
    FROM ' + @TableTemporal)
SELECT TOP 1 * INTO #servicios_temp  FROM vTemp

DROP VIEW vTemp

-- Contar la cantidad de registros de la tabla temporal
SELECT @count_ser_temp = COUNT(*) FROM #servicios_temp;

-- Recorro los registros de la tabla temporal 
WHILE @count_ser_temp > 0
 BEGIN
 END
END

How to restore SQL Server 2014 backup in SQL Server 2008

Pretty old question... but I had the same problem today and solved with script, a little bit slow and complex but worked. I did this:

Let's start from the source DB (SQL 2014) right click on the database you would like to backup -> Generate Scripts -> "Script entire database and all database objet" (or u can select only some table if u want) -> the most important step is in the "Set Scripting Options" tab, here you have to click on "Advanced" and look for the option "Script for Server version" and in my case I could select everything from SQL 2005, also pay attention to the option "Types of data to script" I advice "Schema and data" and also Script Triggers and Script Full-text Indexes (if you need, it's false by default) and finally click ok and next. Should look like this:

Set Scripting Options

Now transfer your generated script into your SQL 2008, open it and last Important Step: You must change mdf and ldf location!!

That's all folks, happy F5!! :D

Merging two CSV files using Python

When I'm working with csv files, I often use the pandas library. It makes things like this very easy. For example:

import pandas as pd

a = pd.read_csv("filea.csv")
b = pd.read_csv("fileb.csv")
b = b.dropna(axis=1)
merged = a.merge(b, on='title')
merged.to_csv("output.csv", index=False)

Some explanation follows. First, we read in the csv files:

>>> a = pd.read_csv("filea.csv")
>>> b = pd.read_csv("fileb.csv")
>>> a
   title  stage    jan    feb
0   darn  3.001  0.421  0.532
1     ok  2.829  1.036  0.751
2  three  1.115  1.146  2.921
>>> b
   title    mar    apr    may       jun  Unnamed: 5
0   darn  0.631  1.321  0.951    1.7510         NaN
1     ok  1.001  0.247  2.456    0.3216         NaN
2  three  0.285  1.283  0.924  956.0000         NaN

and we see there's an extra column of data (note that the first line of fileb.csv -- title,mar,apr,may,jun, -- has an extra comma at the end). We can get rid of that easily enough:

>>> b = b.dropna(axis=1)
>>> b
   title    mar    apr    may       jun
0   darn  0.631  1.321  0.951    1.7510
1     ok  1.001  0.247  2.456    0.3216
2  three  0.285  1.283  0.924  956.0000

Now we can merge a and b on the title column:

>>> merged = a.merge(b, on='title')
>>> merged
   title  stage    jan    feb    mar    apr    may       jun
0   darn  3.001  0.421  0.532  0.631  1.321  0.951    1.7510
1     ok  2.829  1.036  0.751  1.001  0.247  2.456    0.3216
2  three  1.115  1.146  2.921  0.285  1.283  0.924  956.0000

and finally write this out:

>>> merged.to_csv("output.csv", index=False)

producing:

title,stage,jan,feb,mar,apr,may,jun
darn,3.001,0.421,0.532,0.631,1.321,0.951,1.751
ok,2.829,1.036,0.751,1.001,0.247,2.456,0.3216
three,1.115,1.146,2.921,0.285,1.283,0.924,956.0

Animate background image change with jQuery

I don't think this can be done using jQuery's animate function because the background image does not have the necessary CSS properties to do such fading. jQuery can only utilize what the browser makes possible. (jQuery experts, correct me if I'm wrong of course.)

I guess you would have to work around this by not using genuine background-images, but div elements containing the image, positioned using position: absolute (or fixed) and z-index for stacking. You would then animate those divs.

Python JSON serialize a Decimal object

From the JSON Standard Document, as linked in json.org:

JSON is agnostic about the semantics of numbers. In any programming language, there can be a variety of number types of various capacities and complements, fixed or floating, binary or decimal. That can make interchange between different programming languages difficult. JSON instead offers only the representation of numbers that humans use: a sequence of digits. All programming languages know how to make sense of digit sequences even if they disagree on internal representations. That is enough to allow interchange.

So it's actually accurate to represent Decimals as numbers (rather than strings) in JSON. Bellow lies a possible solution to the problem.

Define a custom JSON encoder:

import json


class CustomJsonEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, Decimal):
            return float(obj)
        return super(CustomJsonEncoder, self).default(obj)

Then use it when serializing your data:

json.dumps(data, cls=CustomJsonEncoder)

As noted from comments on the other answers, older versions of python might mess up the representation when converting to float, but that's not the case anymore.

To get the decimal back in Python:

Decimal(str(value))

This solution is hinted in Python 3.0 documentation on decimals:

To create a Decimal from a float, first convert it to a string.

Close pre-existing figures in matplotlib when running from eclipse

See Bi Rico's answer for the general Eclipse case.

For anybody - like me - who lands here because you have lots of windows and you're struggling to close them all, just killing python can be effective, depending on your circumstances. It probably works under almost any circumstances - including with Eclipse.

I just spawned 60 plots from emacs (I prefer that to eclipse) and then I thought my script had exited. Running close('all') in my ipython window did not work for me because the plots did not come from ipython, so I resorted to looking for running python processes.

When I killed the interpreter running the script, then all 60 plots were closed - e.g.,

$ ps aux | grep python
rsage    11665  0.1  0.6 649904 109692 ?       SNl  10:54   0:03 /usr/bin/python3 /usr/bin/update-manager --no-update --no-focus-on-map
rsage    12111  0.9  0.5 390956 88212 pts/30   Sl+  11:08   0:17 /usr/bin/python /usr/bin/ipython -pylab
rsage    12410 31.8  2.4 576640 406304 pts/33  Sl+  11:38   0:06 python3 ../plot_motor_data.py
rsage    12431  0.0  0.0   8860   648 pts/32   S+   11:38   0:00 grep python

$ kill 12410

Note that I did not kill my ipython/pylab, nor did I kill the update manager (killing the update manager is probably a bad idea)...

How do I convert this list of dictionaries to a csv file?

this is when you have one dictionary list:

import csv
with open('names.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

In my case these two issue occurs in some cases like when I am trying to display the progress dialog in an activity that is not in the foreground. So, I dismiss the progress dialog in onPause of the activity lifecycle. And the issue is resolved.

Cannot start this animator on a detached view! reveal effect BUG

ANSWER: Cannot start this animator on a detached view! reveal effect

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!

ANSWER: Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

@Override
protected void onPause() {
    super.onPause();
    dismissProgressDialog();

}

private void dismissProgressDialog() {
    if(progressDialog != null && progressDialog.isShowing())
        progressDialog.dismiss();
}

How do I make flex box work in safari?

display: flex;
display: -webkit-box;

did it for me. Also there were two display: flex; on the same element from different classes. So I removed the other one.

Read a file in Node.js

Run this code, it will fetch data from file and display in console

function fileread(filename)
{            
   var contents= fs.readFileSync(filename);
   return contents;
}        
var fs =require("fs");  // file system        
var data= fileread("abc.txt");
//module.exports.say =say;
//data.say();
console.log(data.toString());

How do I make a new line in swift

"\n" is not working everywhere!

For example in email, it adds the exact "\n" into the text instead of a new line if you use it in the custom keyboard like: textDocumentProxy.insertText("\n")

There are another newLine characters available but I can't just simply paste them here (Because they make a new lines).

using this extension:

extension CharacterSet {
    var allCharacters: [Character] {
        var result: [Character] = []
        for plane: UInt8 in 0...16 where self.hasMember(inPlane: plane) {
            for unicode in UInt32(plane) << 16 ..< UInt32(plane + 1) << 16 {
                if let uniChar = UnicodeScalar(unicode), self.contains(uniChar) {
                    result.append(Character(uniChar))
                }
            }
        }
        return result
    }
}

you can access all characters in any CharacterSet. There is a character set called newlines. Use one of them to fulfill your requirements:

let newlines = CharacterSet.newlines.allCharacters
for newLine in newlines {
    print("Hello World \(newLine) This is a new line")
}

Then store the one you tested and worked everywhere and use it anywhere. Note that you can't relay on the index of the character set. It may change.

But most of the times "\n" just works as expected.

val() vs. text() for textarea

The best way to set/get the value of a textarea is the .val(), .value method.

.text() internally uses the .textContent (or .innerText for IE) method to get the contents of a <textarea>. The following test cases illustrate how text() and .val() relate to each other:

var t = '<textarea>';
console.log($(t).text('test').val());             // Prints test
console.log($(t).val('too').text('test').val());  // Prints too
console.log($(t).val('too').text());              // Prints nothing
console.log($(t).text('test').val('too').val());  // Prints too

console.log($(t).text('test').val('too').text()); // Prints test

The value property, used by .val() always shows the current visible value, whereas text()'s return value can be wrong.

Installing Homebrew on OS X

Open Terminal and put below command.
Install:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Uninstall:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

Once install complete after entering brew commands:

brew install wget
brew install node
brew install watchman
...
...

Boolean Field in Oracle

A working example to implement the accepted answer by adding a "Boolean" column to an existing table in an oracle database (using number type):

ALTER TABLE my_table_name ADD (
my_new_boolean_column number(1) DEFAULT 0 NOT NULL
CONSTRAINT my_new_boolean_column CHECK (my_new_boolean_column in (1,0))
);

This creates a new column in my_table_name called my_new_boolean_column with default values of 0. The column will not accept NULL values and restricts the accepted values to either 0 or 1.

Scale image to fit a bounding box

This helped me:

.img-class {
  width: <img width>;
  height: <img height>;
  content: url('/path/to/img.png');
}

Then on the element (you can use javascript or media queries to add responsiveness):

<div class='img-class' style='transform: scale(X);'></div>

Hope this helps!

How to Use -confirm in PowerShell

Here's a solution I've used, similiar to Ansgar Wiechers' solution;

$title = "Lorem"
$message = "Ipsum"

$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "This means Yes"
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "This means No"

$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

$result = $host.ui.PromptForChoice($title, $message, $Options, 0)

Switch ($result)
     {
          0 { "You just said Yes" }
          1 { "You just said No" }
     }

How to see the values of a table variable at debug time in T-SQL?

This project https://github.com/FilipDeVos/sp_select has a stored procedure sp_select which allows for selecting from a temp table.

Usage:

exec sp_select 'tempDb..#myTempTable'

While debugging a stored procedure you can open a new tab and run this command to see the contents of the temp table.

Lombok added but getters and setters not recognized in Intellij IDEA

Goto Setting->Plugin->Search for "Lombok Plugin" -> It will show results. Install Lombok Plugin from the list and Restart Intellij

Convert array values from string to int?

My solution is casting each value with the help of callback function:

$ids = array_map( function($value) { return (int)$value; }, $ids )

Tensorflow image reading & display

(Can't comment, not enough reputation, but here is a modified version that worked for me)

To @HamedMP error about the No default session is registered you can use InteractiveSession to get rid of this error: https://www.tensorflow.org/versions/r0.8/api_docs/python/client.html#InteractiveSession

And to @NumesSanguis issue with Image.show, you can use the regular PIL .show() method because fromarray returns an image object.

I do both below (note I'm using JPEG instead of PNG):

import tensorflow as tf
import numpy as np
from PIL import Image

filename_queue = tf.train.string_input_producer(['my_img.jpg']) #  list of files to read

reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)

my_img = tf.image.decode_jpeg(value) # use png or jpg decoder based on your files.

init_op = tf.initialize_all_variables()
sess = tf.InteractiveSession()
with sess.as_default():
    sess.run(init_op)

# Start populating the filename queue.

coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)

for i in range(1): #length of your filename list
  image = my_img.eval() #here is your image Tensor :) 

Image.fromarray(np.asarray(image)).show()

coord.request_stop()
coord.join(threads)

Java Strings: "String s = new String("silly");"

Strings are special in Java - they're immutable, and string constants are automatically turned into String objects.

There's no way for your SomeStringClass cis = "value" example to apply to any other class.

Nor can you extend String, because it's declared as final, meaning no sub-classing is allowed.

Open Url in default web browser

In React 16.8+, using functional components, you would do

import React from 'react';
import { Button, Linking } from 'react-native';

const ExternalLinkBtn = (props) => {
  return <Button
            title={props.title}
            onPress={() => {
                Linking.openURL(props.url)
                .catch(err => {
                    console.error("Failed opening page because: ", err)
                    alert('Failed to open page')
                })}}
          />
}

export default function exampleUse() {
  return (
    <View>
      <ExternalLinkBtn title="Example Link" url="https://example.com" />
    </View>
  )
}

Find location of a removable SD card

Just simply use this:

String primary_sd = System.getenv("EXTERNAL_STORAGE");
if(primary_sd != null)
    Log.i("EXTERNAL_STORAGE", primary_sd);
String secondary_sd = System.getenv("SECONDARY_STORAGE");
if(secondary_sd != null)
    Log.i("SECONDARY_STORAGE", secondary_sd)

How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

For my project, I have a requirement to be able to build to both x86 and x64. The problem with this is that whenever you add references while using one, then it complains when you build the other.

My solution is to manually edit the *.csproj files so that lines like these:

<Reference Include="MyLibrary.MyNamespace, Version=1.0.0.0, Culture=neutral, processorArchitecture=x86"/>

<Reference Include="MyLibrary.MyNamespace, Version=1.0.0.0, Culture=neutral, processorArchitecture=AMD64"/>

<Reference Include="MyLibrary.MyNamespace, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL"/>

get changed to this:

<Reference Include="MyLibrary.MyNamespace, Version=1.0.0.0, Culture=neutral"/>

How to present UIActionSheet iOS Swift?

Update for Swift 3:

// Create the AlertController and add its actions like button in ActionSheet
let actionSheetController = UIAlertController(title: "Please select", message: "Option to select", preferredStyle: .actionSheet)

let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
    print("Cancel")
}
actionSheetController.addAction(cancelActionButton)

let saveActionButton = UIAlertAction(title: "Save", style: .default) { action -> Void in
    print("Save")
}
actionSheetController.addAction(saveActionButton)

let deleteActionButton = UIAlertAction(title: "Delete", style: .default) { action -> Void in
    print("Delete")
}
actionSheetController.addAction(deleteActionButton)
self.present(actionSheetController, animated: true, completion: nil)

Random word generator- Python

There are a number of dictionary files available online - if you're on linux, a lot of (all?) distros come with an /etc/dictionaries-common/words file, which you can easily parse (words = open('/etc/dictionaries-common/words').readlines(), eg) for use.

Android, canvas: How do I clear (delete contents of) a canvas (= bitmaps), living in a surfaceView?

Try to remove the view at onPause() of an activity and add onRestart()

LayoutYouAddedYourView.addView(YourCustomView); LayoutYouAddedYourView.removeView(YourCustomView);

The moment you add your view, onDraw() method would get called.

YourCustomView, is a class which extends the View class.

how to activate a textbox if I select an other option in drop down box

Below is the core JavaScript you need to write:

<html> 
<head>  
<script type="text/javascript">
function CheckColors(val){
 var element=document.getElementById('color');
 if(val=='pick a color'||val=='others')
   element.style.display='block';
 else  
   element.style.display='none';
}

</script> 
</head>
<body>
  <select name="color" onchange='CheckColors(this.value);'> 
    <option>pick a color</option>  
    <option value="red">RED</option>
    <option value="blue">BLUE</option>
    <option value="others">others</option>
  </select>
<input type="text" name="color" id="color" style='display:none;'/>
</body>
</html>

What is the use of a cursor in SQL Server?

Cursors are a mechanism to explicitly enumerate through the rows of a result set, rather than retrieving it as such.

However, while they may be more comfortable to use for programmers accustomed to writing While Not RS.EOF Do ..., they are typically a thing to be avoided within SQL Server stored procedures if at all possible -- if you can write a query without the use of cursors, you give the optimizer a much better chance to find a fast way to implement it.

In all honesty, I've never found a realistic use case for a cursor that couldn't be avoided, with the exception of a few administrative tasks such as looping over all indexes in the catalog and rebuilding them. I suppose they might have some uses in report generation or mail merges, but it's probably more efficient to do the cursor-like work in an application that talks to the database, letting the database engine do what it does best -- set manipulation.

Implicit function declarations in C

Implicit declarations are not valid in C.

C99 removed this feature (present in C89).

gcc chooses to only issue a warning by default with -std=c99 but a compiler has the right to refuse to translate such a program.

Is it possible to put CSS @media rules inline?

No, @media rules and media queries cannot exist in inline style attributes as they can only contain property: value declarations. As the spec puts it:

The value of the style attribute must match the syntax of the contents of a CSS declaration block

The only way to apply styles to an element only in certain media is with a separate rule in your stylesheet, which means you'll need to come up with a selector for it.

A dummy span selector would look like this, but if you're targeting a very specific element you will need a more specific selector:

span { background-image: url(particular_ad.png); }

@media (max-width: 300px) {
    span { background-image: url(particular_ad_small.png); }
}

How to access random item in list?

I needed to more item instead of just one. So, I wrote this:

public static TList GetSelectedRandom<TList>(this TList list, int count)
       where TList : IList, new()
{
    var r = new Random();
    var rList = new TList();
    while (count > 0 && list.Count > 0)
    {
        var n = r.Next(0, list.Count);
        var e = list[n];
        rList.Add(e);
        list.RemoveAt(n);
        count--;
    }

    return rList;
}

With this, you can get elements how many you want as randomly like this:

var _allItems = new List<TModel>()
{
    // ...
    // ...
    // ...
}

var randomItemList = _allItems.GetSelectedRandom(10); 

Android Studio not showing modules in project structure

Go to File->Project Structure-> Project Settings -> Modules.

Click on the green colored + and add new module. select Application module and set the content root to your project module.

Click next and then finish.

Reference

Which data structures and algorithms book should I buy?

Introduction to Algorithms by Cormen et. al. is a standard introductory algorithms book, and is used by many universities, including my own. It has pretty good coverage and is very approachable.

And anything by Robert Sedgewick is good too.

Wampserver icon not going green fully, mysql services not starting up?

I had the same issue, to resolve it I added the following line to my.ini

innodb_force_recovery = 1

Error in contrasts when defining a linear model in R

This is a variation to the answer provided by @Metrics and edited by @Max Ghenis...

l <- sapply(iris, function(x) is.factor(x))
m <- iris[,l]

n <- sapply( m, function(x) { y <- summary(x)/length(x)
len <- length(y[y<0.005 | y>0.995])
cbind(len,t(y))} )

drop_cols_df <- data.frame(var = names(l[l]), 
                           status = ifelse(as.vector(t(n[1,]))==0,"NODROP","DROP" ),
                           level1 = as.vector(t(n[2,])),
                           level2 = as.vector(t(n[3,])))

Here, after identifying factor variables, the second sapply computes what percent of records belong to each level / category of the variable. Then it identifies number of levels over 99.5% or below 0.5% incidence rate (my arbitrary thresholds).

It then goes on to return the number of valid levels and the incidence rate of each level in each categorical variable.

Variables with zero levels crossing the thresholds should not be dropped, while the other should be dropped from the linear model.

The last data frame makes viewing the results easy. It's hard coded for this data set since all factor variables are binomial. This data frame can be made generic easily enough.

What's the best way to store co-ordinates (longitude/latitude, from Google Maps) in SQL Server?

If you are just going to substitute it into a URL I suppose one field would do - so you can form a URL like

http://maps.google.co.uk/maps?q=12.345678,12.345678&z=6

but as it is two pieces of data I would store them in separate fields

Convert hex string (char []) to int?

Or if you want to have your own implementation, I wrote this quick function as an example:

/**
 * hex2int
 * take a hex string and convert it to a 32bit number (max 8 hex digits)
 */
uint32_t hex2int(char *hex) {
    uint32_t val = 0;
    while (*hex) {
        // get current character then increment
        uint8_t byte = *hex++; 
        // transform hex character to the 4bit equivalent number, using the ascii table indexes
        if (byte >= '0' && byte <= '9') byte = byte - '0';
        else if (byte >= 'a' && byte <='f') byte = byte - 'a' + 10;
        else if (byte >= 'A' && byte <='F') byte = byte - 'A' + 10;    
        // shift 4 to make space for new digit, and add the 4 bits of the new digit 
        val = (val << 4) | (byte & 0xF);
    }
    return val;
}

Bootstrap 3 dropdown select

Try this:

<div class="form-group">
     <label class="control-label" for="Company">Company</label>
     <select id="Company" class="form-control" name="Company">
         <option value="small">small</option>
         <option value="medium">medium</option>
         <option value="large">large</option>
     </select> 
 </div>

The type or namespace name 'Objects' does not exist in the namespace 'System.Data'

You need to add a reference to the .NET assembly System.Data.Entity.dll.

Get hostname of current request in node.js Express

First of all, before providing an answer I would like to be upfront about the fact that by trusting headers you are opening the door to security vulnerabilities such as phishing. So for redirection purposes, don't use values from headers without first validating the URL is authorized.

Then, your operating system hostname might not necessarily match the DNS one. In fact, one IP might have more than one DNS name. So for HTTP purposes there is no guarantee that the hostname assigned to your machine in your operating system configuration is useable.

The best choice I can think of is to obtain your HTTP listener public IP and resolve its name via DNS. See the dns.reverse method for more info. But then, again, note that an IP might have multiple names associated with it.

How to use zIndex in react-native

I believe there are different ways to do this based on what you need exactly, but one way would be to just put both Elements A and B inside Parent A.

    <View style={{ position: 'absolute' }}>    // parent of A
        <View style={{ zIndex: 1 }} />  // element A
        <View style={{ zIndex: 1 }} />  // element A
        <View style={{ zIndex: 0, position: 'absolute' }} />  // element B
    </View>

How to change the text of a label?

try this

$("label").html(your value); or $("label").text(your value);

Fatal error: Call to undefined function mysql_connect() in C:\Apache\htdocs\test.php on line 2

I had the similar issue. I solved it the following way after a number of attempts to follow the pieces of advice in the forums. I am reposting the solution because it could be helpful for others.

I am running Windows 7 (Apache 2.2 & PHP 5.2.17 & MySQL 5.0.51a), the syntax in the file "httpd.conf" (C:\Program Files (x86)\Apache Software Foundation\Apache2.2\conf\httpd.conf) was sensitive to slashes. You can check if "php.ini" is read from the right directory. Just type in your browser "localhost/index.php". The code of index.php is the following:

<?php echo phpinfo(); ?>

There is the row (not far from the top) called "Loaded Configuration File". So, if there is nothing added, then the problem could be that your "php.ini" is not read, even you uncommented (extension=php_mysql.dll and extension=php_mysqli.dll). So, in order to make it work I did the following step. I needed to change from

PHPIniDir 'c:\PHP\'

to

PHPIniDir 'c:\PHP'

Pay the attention that the last slash disturbed everything!

Now the row "Loaded Configuration File" gets "C:\PHP\php.ini" after refreshing "localhost/index.php" (before I restarted Apache2.2) as well as mysql block is there. MySQL and PHP are working together!

What is the instanceof operator in JavaScript?

I think it's worth noting that instanceof is defined by the use of the "new" keyword when declaring the object. In the example from JonH;

var color1 = new String("green");
color1 instanceof String; // returns true
var color2 = "coral";
color2 instanceof String; // returns false (color2 is not a String object)

What he didn't mention is this;

var color1 = String("green");
color1 instanceof String; // returns false

Specifying "new" actually copied the end state of the String constructor function into the color1 var, rather than just setting it to the return value. I think this better shows what the new keyword does;

function Test(name){
    this.test = function(){
        return 'This will only work through the "new" keyword.';
    }
    return name;
}

var test = new Test('test');
test.test(); // returns 'This will only work through the "new" keyword.'
test // returns the instance object of the Test() function.

var test = Test('test');
test.test(); // throws TypeError: Object #<Test> has no method 'test'
test // returns 'test'

Using "new" assigns the value of "this" inside the function to the declared var, while not using it assigns the return value instead.

Reading my own Jar's Manifest

Why are you including the getClassLoader step? If you say "this.getClass().getResource()" you should be getting resources relative to the calling class. I've never used ClassLoader.getResource(), though from a quick look at the Java Docs it sounds like that will get you the first resource of that name found in any current classpath.

batch script - run command on each file in directory

Actually this is pretty easy since Windows Vista. Microsoft added the command FORFILES

in your case

forfiles /p c:\directory /m *.xls /c "cmd /c ssconvert @file @fname.xlsx"

the only weird thing with this command is that forfiles automatically adds double quotes around @file and @fname. but it should work anyway

Sending a JSON to server and retrieving a JSON in return, without JQuery

Sending and receiving data in JSON format using POST method

// Sending and receiving data in JSON format using POST method
//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
var data = JSON.stringify({"email": "[email protected]", "password": "101010"});
xhr.send(data);

Sending and receiving data in JSON format using GET method

// Sending a receiving data in JSON format using GET method
//      
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "[email protected]", "password": "101010"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var json = JSON.parse(xhr.responseText);
        console.log(json.email + ", " + json.password);
    }
};
xhr.send();

Handling data in JSON format on the server-side using PHP

<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>

The limit of the length of an HTTP Get request is dependent on both the server and the client (browser) used, from 2kB - 8kB. The server should return 414 (Request-URI Too Long) status if an URI is longer than the server can handle.

Note Someone said that I could use state names instead of state values; in other words I could use xhr.readyState === xhr.DONE instead of xhr.readyState === 4 The problem is that Internet Explorer uses different state names so it's better to use state values.

What's the difference between isset() and array_key_exists()?

The PHP function array_key_exists() determines if a particular key, or numerical index, exists for an element of an array. However, if you want to determine if a key exists and is associated with a value, the PHP language construct isset() can tell you that (and that the value is not null). array_key_exists()cannot return information about the value of a key/index.

How do you do block comments in YAML?

In .gitlab-ci.yml file following works::

To comment out a block (multiline): Select the whole block section > Ctrl K C

To uncomment already commented out block (multiline): Select the whole block section > Ctrl K U

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

I was getting this problem when using IBM RSA 9.6.1 when building a brand new development machine. The problem for me ended up being because of HTTPS on the Global Maven repository. My solution was to create a Maven settings.xml that forced it to use HTTP.

The key to me was that the central repository was empty when I exploded it under Maven Repositories -- > Global Repositories

Using the following settings file worked for me:

<settings>
  <activeProfiles>
    <!--make the profile active all the time -->
    <activeProfile>insecurecentral</activeProfile>
  </activeProfiles>
  <profiles>
    <profile>
      <id>insecurecentral</id>
      <!--Override the repository (and pluginRepository) "central" from the Maven Super POM -->
      <repositories>
        <repository>
          <id>central</id>
          <url>http://repo.maven.apache.org/maven2</url>
          <releases>
            <enabled>true</enabled>
          </releases>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <id>central</id>
          <url>http://repo.maven.apache.org/maven2</url>
          <releases>
            <enabled>true</enabled>
          </releases>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  </profiles>
</settings>

I got the idea from this stackoverflow question.

jQuery if div contains this text, replace that part of the text

You can use the text method and pass a function that returns the modified text, using the native String.prototype.replace method to perform the replacement:

?$(".text_div").text(function () {
    return $(this).text().replace("contains", "hello everyone"); 
});?????

Here's a working example.

Remove specific characters from a string in Python

You could use the re module's regular expression replacement. Using the ^ expression allows you to pick exactly what you want from your string.

    import re
    text = "This is absurd!"
    text = re.sub("[^a-zA-Z]","",text) # Keeps only Alphabets
    print(text)

Output to this would be "Thisisabsurd". Only things specified after the ^ symbol will appear.

wkhtmltopdf: cannot connect to X server

Expanding on Timothy's answer...

If you're a web developer looking to use wkhtmltopdf as part of your web app, you can simply install it into your /usr/bin/ folder like so:

cd /usr/bin/
curl -C - -O http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.11.0_rc1-static-i386.tar.bz2
tar -xvjf wkhtmltopdf-0.11.0_rc1-static-i386.tar.bz2
mv wkhtmltopdf-i386 wkhtmltopdf

You can now run it anywhere using wkhtmltopdf.

I personally use the Snappy library in PHP. Here is an example of how easy it is to create a PDF:

<?php

// Create new PDF
$pdf = new \Knp\Snappy\Pdf('wkhtmltopdf');

// Set output header
header('Content-Type: application/pdf');

// Generate PDF from HTML
echo $pdf->getOutputFromHtml('<h1>Title</h1><p>Your content goes here.</p>');

How To Set A JS object property name from a variable

You'll have to use [] notation to set keys dynamically.

var jsonVariable = {};
for(i=1; i<3; i++) {        
 var jsonKey  = i+'name';
 jsonVariable[jsonKey] = 'name1';

}

Now in ES6 you can use object literal syntax to create object keys dynamically, just wrap the variable in []

var key  = i + 'name';
data = {
    [key] : 'name1',
}

Format timedelta to string

You can just convert the timedelta to a string with str(). Here's an example:

import datetime
start = datetime.datetime(2009,2,10,14,00)
end   = datetime.datetime(2009,2,10,16,00)
delta = end-start
print(str(delta))
# prints 2:00:00

Delete specific line from a text file?

No rocket scien code require .Hope this simple and short code will help.

List linesList = File.ReadAllLines("myFile.txt").ToList();            
linesList.RemoveAt(0);
File.WriteAllLines("myFile.txt"), linesList.ToArray());

OR use this

public void DeleteLinesFromFile(string strLineToDelete)
    {
        string strFilePath = "Provide the path of the text file";
        string strSearchText = strLineToDelete;
        string strOldText;
        string n = "";
        StreamReader sr = File.OpenText(strFilePath);
        while ((strOldText = sr.ReadLine()) != null)
        {
            if (!strOldText.Contains(strSearchText))
            {
                n += strOldText + Environment.NewLine;
            }
        }
        sr.Close();
        File.WriteAllText(strFilePath, n);
    }

Disable Copy or Paste action for text box?

Check this fiddle.

 $('#email').bind("cut copy paste",function(e) {
     e.preventDefault();
 });

You need to bind what should be done on cut, copy and paste. You prevent default behavior of the action.

You can find a detailed explanation here.

Could not establish secure channel for SSL/TLS with authority '*'

Ensure you run Visual Studio as an administrator.

How to increase heap size for jBoss server

Edit the following entry in the run.conf file. But if you have multiple JVMs running on the same JBoss, you might want to run it via command line argument of -Xms2g -Xmx4g (or whatever your preferred start/max memory settings are.

if [ "x$JAVA_OPTS" = "x" ]; then
    JAVA_OPTS="-Xms2g -Xmx4g -XX:MaxPermSize=256m -Dorg.jboss.resolver.warning=true

Simple Digit Recognition OCR in OpenCV-Python

OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.

Data Used


This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.

Below is the implementation.




import numpy as np
import cv2
   
      
# Read the image
image = cv2.imread('digits.png')
  
# gray scale conversion
gray_img = cv2.cvtColor(image,
                        cv2.COLOR_BGR2GRAY)
  
# We will divide the image
# into 5000 small dimensions 
# of size 20x20
divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))
  
# Convert into Numpy array
# of size (50,100,20,20)
NP_array = np.array(divisions)
   
# Preparing train_data
# and test_data.
# Size will be (2500,20x20)
train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)
  
# Size will be (2500,20x20)
test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)
  
# Create 10 different labels 
# for each type of digit
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = np.repeat(k,250)[:,np.newaxis]
   
# Initiate kNN classifier
knn = cv2.ml.KNearest_create()
  
# perform training of data
knn.train(train_data,
          cv2.ml.ROW_SAMPLE, 
          train_labels)
   
# obtain the output from the
# classifier by specifying the
# number of neighbors.
ret, output ,neighbours,
distance = knn.findNearest(test_data, k = 3)
   
# Check the performance and
# accuracy of the classifier.
# Compare the output with test_labels
# to find out how many are wrong.
matched = output==test_labels
correct_OP = np.count_nonzero(matched)
   
#Calculate the accuracy.
accuracy = (correct_OP*100.0)/(output.size)
   
# Display accuracy.
print(accuracy)


Output

91.64


Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).

1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file.

It contains a letter, along with 16 features of that letter.

And this SOF helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers. (Although I didn't understand some of the features at the end)

2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.

So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)

I took the below image for my training data:

enter image description here

(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).

To prepare the data for training, I made a small code in OpenCV. It does the following things:

  1. It loads the image.
  2. Selects the digits (obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
  3. Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in the box.
  4. Once the corresponding digit key is pressed, it resizes this box to 10x10 and saves all 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses).
  5. Then save both the arrays in separate .txt files.

At the end of the manual classification of digits, all the digits in the training data (train.png) are labeled manually by ourselves, image will look like below:

enter image description here

Below is the code I used for the above purpose (of course, not so clean):

import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                responses.append(int(chr(key)))
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Now we enter in to training and testing part.

For the testing part, I used the below image, which has the same type of letters I used for the training phase.

enter image description here

For training we do as follows:

  1. Load the .txt files we already saved earlier
  2. create an instance of the classifier we are using (it is KNearest in this case)
  3. Then we use KNearest.train function to train the data

For testing purposes, we do as follows:

  1. We load the image used for testing
  2. process the image as earlier and extract each digit using contour methods
  3. Draw a bounding box for it, then resize it to 10x10, and store its pixel values in an array as done earlier.
  4. Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognizes the correct digit.)

I included last two steps (training and testing) in single code below:

import cv2
import numpy as np

#######   training part    ############### 
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

And it worked, below is the result I got:

enter image description here


Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.

But anyway, this is a good start to go for beginners (I hope so).

popup form using html/javascript/css

Look at easiest example to create popup using css and javascript.

  1. Create HREF link using HTML.
  2. Create a popUp by HTML and CSS
  3. Write CSS
  4. Call JavaScript mehod

See the full example at this link http://makecodeeasy.blogspot.in/2012/07/popup-in-java-script-and-css.html

Are SSL certificates bound to the servers ip address?

Most SSL certificates are bound to the hostname of the machine and not the ip address.

You might get a better answer if you ask this question on serverfault.com

Inheritance and init method in Python

A simple change in Num2 class like this:

super().__init__(num) 

It works in python3.

class Num:
        def __init__(self,num):
                self.n1 = num

class Num2(Num):
        def __init__(self,num):
                super().__init__(num)
                self.n2 = num*2
        def show(self):
                print (self.n1,self.n2)

mynumber = Num2(8)
mynumber.show()

In Flask, What is request.args and how is it used?

According to the flask.Request.args documents.

flask.Request.args
A MultiDict with the parsed contents of the query string. (The part in the URL after the question mark).

So the args.get() is method get() for MultiDict, whose prototype is as follows:

get(key, default=None, type=None)

Update:
In newer version of flask (v1.0.x and v1.1.x), flask.Request.args is an ImmutableMultiDict(an immutable MultiDict), so the prototype and specific method above is still valid.

C - freeing structs

Simple answer : free(testPerson) is enough .

Remember you can use free() only when you have allocated memory using malloc, calloc or realloc.

In your case you have only malloced memory for testPerson so freeing that is sufficient.

If you have used char * firstname , *last surName then in that case to store name you must have allocated the memory and that's why you had to free each member individually.

Here is also a point it should be in the reverse order; that means, the memory allocated for elements is done later so free() it first then free the pointer to object.

Freeing each element you can see the demo shown below:

typedef struct Person
{
char * firstname , *last surName;
}Person;
Person *ptrobj =malloc(sizeof(Person)); // memory allocation for struct
ptrobj->firstname = malloc(n); // memory allocation for firstname
ptrobj->surName = malloc(m); // memory allocation for surName

.
. // do whatever you want

free(ptrobj->surName);
free(ptrobj->firstname);
free(ptrobj);

The reason behind this is, if you free the ptrobj first, then there will be memory leaked which is the memory allocated by firstname and suName pointers.

jQuery check/uncheck radio button onclick

DiegoP,

I was having the same trouble, until I realized that the check on the box doesnt go off until the attribute is removed. That means even if checked value is made false, it will remain there.

Hence use the removeAttr() function and remove the checked attrib and it WILL DEFINITELY WORK.

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

I know this is an old question, but I had the same problem and solved it thanks to this answer.

I use Putty regularly and have never had any problems. I use and have always used public key authentication. Today I could not connect again to my server, without changing any settings.

Then I saw the answer and remembered that I inadvertently ran chmod 777 . in my user's home directory. I connected from somewhere else and simply ran chmod 755 ~. Everything was back to normal instantly, I didn't even have to restart sshd.

I hope I saved some time from someone

scp from Linux to Windows

Try this, it really works.

$ scp username@from_host_ip:/home/ubuntu/myfile /cygdrive/c/Users/Anshul/Desktop

And for copying all files

$ scp -r username@from_host_ip:/home/ubuntu/ *. * /cygdrive/c/Users/Anshul/Desktop

How to convert Blob to String and String to Blob in java

To convert Blob to String in Java:

byte[] bytes = baos.toByteArray();//Convert into Byte array
String blobString = new String(bytes);//Convert Byte Array into String

How to convert date into this 'yyyy-MM-dd' format in angular 2

You can also use formatDate

let formattedDt = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ssZZZZZ', 'en_US')

How to make a Generic Type Cast function

ConvertValue( System.Object o ), then you can branch out by o.GetType() result and up-cast o to the types to work with the value.

How to prepare a Unity project for git?

On the Unity Editor open your project and:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository (only if Unity ver < 4.5)
  2. Switch to Visible Meta Files in Edit ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Edit ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save Scene and Project from File menu.
  5. Quit Unity and then you can delete the Library and Temp directory in the project directory. You can delete everything but keep the Assets and ProjectSettings directory.

If you already created your empty git repo on-line (eg. github.com) now it's time to upload your code. Open a command prompt and follow the next steps:

cd to/your/unity/project/folder

git init

git add *

git commit -m "First commit"

git remote add origin [email protected]:username/project.git

git push -u origin master

You should now open your Unity project while holding down the Option or the Left Alt key. This will force Unity to recreate the Library directory (this step might not be necessary since I've seen Unity recreating the Library directory even if you don't hold down any key).

Finally have git ignore the Library and Temp directories so that they won’t be pushed to the server. Add them to the .gitignore file and push the ignore to the server. Remember that you'll only commit the Assets and ProjectSettings directories.

And here's my own .gitignore recipe for my Unity projects:

# =============== #
# Unity generated #
# =============== #
Temp/
Obj/
UnityGenerated/
Library/
Assets/AssetStoreTools*

# ===================================== #
# Visual Studio / MonoDevelop generated #
# ===================================== #
ExportedObj/
*.svd
*.userprefs
*.csproj
*.pidb
*.suo
*.sln
*.user
*.unityproj
*.booproj

# ============ #
# OS generated #
# ============ #
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db

HTML5 Email Validation

Using HTML 5,Just make the input email like :

_x000D_
_x000D_
<input type="email"/>
_x000D_
_x000D_
_x000D_

When the user hovers over the input box, they will a tooltip instructing them to enter a valid email. However, Bootstrap forms have a much better Tooltip message to tell the user to enter an email address and it pops up the moment the value entered does not match a valid email.

How do I sort a table in Excel if it has cell references in it?

Not sure if this will satisfy all, but I found a simple workaround that fixed the problem for me. Move all your referenced cells/formulas to a different sheet so that you aren't referencing any cells in the sheet that has the table to be sorted. If you do this, you can sort away!

How do I use Comparator to define a custom sort order?

Define one Enum Type as

public enum Colors {
     BLUE, SILVER, MAGENTA, RED
}

Change data type of color from String to Colors Change return type and argument type of getter and setter method of color to Colors

Define comparator type as follows

static class ColorComparator implements Comparator<CarSort>
{
    public int compare(CarSort c1, CarSort c2)
    {
        return c1.getColor().compareTo(c2.getColor());
    }
}

after adding elements to List, call sort method of Collection by passing list and comparator objects as arguments

i.e, Collections.sort(carList, new ColorComparator()); then print using ListIterator.

full class implementation is as follows:

package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;    
import java.util.ListIterator;

public class CarSort implements Comparable<CarSort>{

    String name;
    Colors color;

    public CarSort(String name, Colors color){
        this.name = name;
        this.color = color;
    } 

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Colors getColor() {
        return color;
    }
    public void setColor(Colors color) {
        this.color = color;
    }

    //Implement the natural order for this class
    public int compareTo(CarSort c)
    {
        return getName().compareTo(c.getName());
    }

    static class ColorComparator implements Comparator<CarSort>
    {
        public int compare(CarSort c1, CarSort c2)
        {
            return c1.getColor().compareTo(c2.getColor());
        }
    }

    public enum Colors {
         BLUE, SILVER, MAGENTA, RED
    }

     public static void main(String[] args)
     {
         List<CarSort> carList = new ArrayList<CarSort>();
         List<String> sortOrder = new ArrayList<String>();

         carList.add(new CarSort("Ford Figo",Colors.SILVER));
         carList.add(new CarSort("Santro",Colors.BLUE));
         carList.add(new CarSort("Honda Jazz",Colors.MAGENTA));
         carList.add(new CarSort("Indigo V2",Colors.RED));
         Collections.sort(carList, new ColorComparator());

         ListIterator<CarSort> itr=carList.listIterator();
         while (itr.hasNext()) {
            CarSort carSort = (CarSort) itr.next();
            System.out.println("Car colors: "+carSort.getColor());
        }
     }
}

How can I get the session object if I have the entity-manager?

This will explain better.

EntityManager em = new JPAUtil().getEntityManager();
Session session = em.unwrap(Session.class);
Criteria c = session.createCriteria(Name.class);

Linking to an external URL in Javadoc?

This creates a "See Also" heading containing the link, i.e.:

/**
 * @see <a href="http://google.com">http://google.com</a>
 */

will render as:

See Also:
           http://google.com

whereas this:

/**
 * See <a href="http://google.com">http://google.com</a>
 */

will create an in-line link:

See http://google.com

How to select the Date Picker In Selenium WebDriver

I think this could be done in a much simpler way:

  1. Find the locator for the Month (use Firebug/Firepath)
  2. This is probably a Select element, use Selenium to select Month
  3. Do the same for Year
  4. Click by linkText "31" or whatever date you want to click

So code would look something like this:

WebElement month = driver.findElement(month combo locator);
Select monthCombo = new Select(month);
monthCombo.selectByVisibleText("March");

WebElement year = driver.findElement(year combo locator);
Select yearCombo = new Select(year);
yearCombo.selectByVisibleText("2015");

driver.click(By.linkText("31"));

This won't work if the date picker dropdowns are not Select, but most of the ones I've seen are individual elements (select, links, etc.)

Declaring a variable and setting its value from a SELECT query in Oracle

Not entirely sure what you are after but in PL/SQL you would simply

DECLARE
  v_variable INTEGER;
BEGIN
  SELECT mycolumn
    INTO v_variable
    FROM myTable;
END;

Ollie.

How do I fix the error 'Named Pipes Provider, error 40 - Could not open a connection to' SQL Server'?

Did have the same problem. Spent like 6 hours when had to migrate some servers. Tried all suggestions available on this topic and others.

Solution was as simple as server restart!

Reading a file character by character in C

Expanding upon the above code from @dreamlax

char *readFile(char *fileName) {
    FILE *file = fopen(fileName, "r");
    char *code;
    size_t n = 0;
    int c;

    if (file == NULL) return NULL; //could not open file
    fseek(file, 0, SEEK_END);
    long f_size = ftell(file);
    fseek(file, 0, SEEK_SET);
    code = malloc(f_size);

    while ((c = fgetc(file)) != EOF) {
        code[n++] = (char)c;
    }

    code[n] = '\0';        

    return code;
}

This gives you the length of the file, then proceeds to read it character by character.

convert pfx format to p12

If you are looking for a quick and manual process with UI. I always use Mozilla Firefox to convert from PFX to P12. First import the certificate into the Firefox browser (Options > Privacy & Security > View Certificates... > Import...). Once installed, perform the export to create the P12 file by choosing the certificate name from the Certificate Manager and then click Backup... and enter the file name and then enter the password.

How do I print colored output to the terminal in Python?

Would the Python termcolor module do? This would be a rough equivalent for some uses.

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

The example is right from this post, which has a lot more. Here is a part of the example from docs

import sys
from termcolor import colored, cprint

text = colored('Hello, World!', 'red', attrs=['reverse', 'blink'])
print(text)
cprint('Hello, World!', 'green', 'on_red')

A specific requirement was to set the color, and presumably other terminal attributes, so that all following prints are that way. While I stated in the original post that this is possible with this module I now don't think so. See the last section for a way to do that.

However, most of the time we print short segments of text in color, a line or two. So the interface in these examples may be a better fit than to 'turn on' a color, print, and then turn it off. (Like in the Perl example shown.) Perhaphs you can add optional argument(s) to your print function for coloring the output as well, and in the function use module's functions to color the text. This also makes it easier to resolve occasional conflicts between formatting and coloring. Just a thought.


Here is a basic approach to set the terminal so that all following prints are rendered with a given color, attributes, or mode.

Once an appropriate ANSI sequence is sent to the terminal, all following text is rendered that way. Thus if we want all text printed to this terminal in the future to be bright/bold red, print ESC[ followed by the codes for "bright" attribute (1) and red color (31), followed by m

# print "\033[1;31m"   # this would emit a new line as well
import sys
sys.stdout.write("\033[1;31m")
print "All following prints will be red ..."

To turn off any previously set attributes use 0 for attribute, \033[0;35m (magenta).

To suppress a new line in python 3 use print('...', end=""). The rest of the job is about packaging this for modular use (and for easier digestion).

File colors.py

RED   = "\033[1;31m"  
BLUE  = "\033[1;34m"
CYAN  = "\033[1;36m"
GREEN = "\033[0;32m"
RESET = "\033[0;0m"
BOLD    = "\033[;1m"
REVERSE = "\033[;7m"

I recommend a quick read through some references on codes. Colors and attributes can be combined and one can put together a nice list in this package. A script

import sys
from colors import *

sys.stdout.write(RED)
print "All following prints rendered in red, until changed"

sys.stdout.write(REVERSE + CYAN)
print "From now on change to cyan, in reverse mode"
print "NOTE: 'CYAN + REVERSE' wouldn't work"

sys.stdout.write(RESET)
print "'REVERSE' and similar modes need be reset explicitly"
print "For color alone this is not needed; just change to new color"
print "All normal prints after 'RESET' above."

If the constant use of sys.stdout.write() is a bother it can be be wrapped in a tiny function, or the package turned into a class with methods that set terminal behavior (print ANSI codes).

Some of the above is more of a suggestion to look it up, like combining reverse mode and color. (This is available in the Perl module used in the question, and is also sensitive to order and similar.)


A convenient list of escape codes is surprisingly hard to find, while there are many references on terminal behavior and how to control it. The Wiki page on ANSI escape codes has all information but requires a little work to bring it together. Pages on Bash prompt have a lot of specific useful information. Here is another page with straight tables of codes. There is much more out there.

This can be used alongside a module like termocolor.

Sum rows in data.frame or matrix

you can use rowSums

rowSums(data) should give you what you want.

Check existence of directory and create if doesn't exist

As of April 16, 2015, with the release of R 3.2.0 there's a new function called dir.exists(). To use this function and create the directory if it doesn't exist, you can use:

ifelse(!dir.exists(file.path(mainDir, subDir)), dir.create(file.path(mainDir, subDir)), FALSE)

This will return FALSE if the directory already exists or is uncreatable, and TRUE if it didn't exist but was succesfully created.

Note that to simply check if the directory exists you can use

dir.exists(file.path(mainDir, subDir))

What is the difference between single and double quotes in SQL?

I use this mnemonic:

  • Single quotes are for strings (one thing)
  • Double quotes are for tables names and column names (two things)

This is not 100% correct according to the specs, but this mnemonic helps me (human being).

Calculate correlation with cor(), only for numerical columns

if you have a dataframe where some columns are numeric and some are other (character or factor) and you only want to do the correlations for the numeric columns, you could do the following:

set.seed(10)

x = as.data.frame(matrix(rnorm(100), ncol = 10))
x$L1 = letters[1:10]
x$L2 = letters[11:20]

cor(x)

Error in cor(x) : 'x' must be numeric

but

cor(x[sapply(x, is.numeric)])

             V1         V2          V3          V4          V5          V6          V7
V1   1.00000000  0.3025766 -0.22473884 -0.72468776  0.18890578  0.14466161  0.05325308
V2   0.30257657  1.0000000 -0.27871430 -0.29075170  0.16095258  0.10538468 -0.15008158
V3  -0.22473884 -0.2787143  1.00000000 -0.22644156  0.07276013 -0.35725182 -0.05859479
V4  -0.72468776 -0.2907517 -0.22644156  1.00000000 -0.19305921  0.16948333 -0.01025698
V5   0.18890578  0.1609526  0.07276013 -0.19305921  1.00000000  0.07339531 -0.31837954
V6   0.14466161  0.1053847 -0.35725182  0.16948333  0.07339531  1.00000000  0.02514081
V7   0.05325308 -0.1500816 -0.05859479 -0.01025698 -0.31837954  0.02514081  1.00000000
V8   0.44705527  0.1698571  0.39970105 -0.42461411  0.63951574  0.23065830 -0.28967977
V9   0.21006372 -0.4418132 -0.18623823 -0.25272860  0.15921890  0.36182579 -0.18437981
V10  0.02326108  0.4618036 -0.25205899 -0.05117037  0.02408278  0.47630138 -0.38592733
              V8           V9         V10
V1   0.447055266  0.210063724  0.02326108
V2   0.169857120 -0.441813231  0.46180357
V3   0.399701054 -0.186238233 -0.25205899
V4  -0.424614107 -0.252728595 -0.05117037
V5   0.639515737  0.159218895  0.02408278
V6   0.230658298  0.361825786  0.47630138
V7  -0.289679766 -0.184379813 -0.38592733
V8   1.000000000  0.001023392  0.11436143
V9   0.001023392  1.000000000  0.15301699
V10  0.114361431  0.153016985  1.00000000

Using jquery to delete all elements with a given id

The cleanest way to do it is by using html5 selectors api, specifically querySelectorAll().

var contentToRemove = document.querySelectorAll("#myid");
$(contentToRemove).remove(); 

The querySelectorAll() function returns an array of dom elements matching a specific id. Once you have assigned the returned array to a var, then you can pass it as an argument to jquery remove().

from jquery $.ajax to angular $http

You may use this :

Download "angular-post-fix": "^0.1.0"

Then add 'httpPostFix' to your dependencies while declaring the angular module.

Ref : https://github.com/PabloDeGrote/angular-httppostfix

How to scroll to top of long ScrollView layout?

Had the same issue, probably some kind of bug.

Even the fullScroll(ScrollView.FOCUS_UP) from the other answer didn't work.
Only thing that worked for me was calling scroll_view.smoothScrollTo(0,0) right after the dialog is shown.

pandas: merge (join) two data frames on multiple columns

Try this

new_df = pd.merge(A_df, B_df,  how='left', left_on=['A_c1','c2'], right_on = ['B_c1','c2'])

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.merge.html

left_on : label or list, or array-like Field names to join on in left DataFrame. Can be a vector or list of vectors of the length of the DataFrame to use a particular vector as the join key instead of columns

right_on : label or list, or array-like Field names to join on in right DataFrame or vector/list of vectors per left_on docs

Dynamic variable names in Bash

An extra method that doesn't rely on which shell/bash version you have is by using envsubst. For example:

newvar=$(echo '$magic_variable_'"${dynamic_part}" | envsubst)

Is Python strongly typed?

Python is strongly, dynamically typed.

  • Strong typing means that the type of a value doesn't change in unexpected ways. A string containing only digits doesn't magically become a number, as may happen in Perl. Every change of type requires an explicit conversion.
  • Dynamic typing means that runtime objects (values) have a type, as opposed to static typing where variables have a type.

As for your example

bob = 1
bob = "bob"

This works because the variable does not have a type; it can name any object. After bob=1, you'll find that type(bob) returns int, but after bob="bob", it returns str. (Note that type is a regular function, so it evaluates its argument, then returns the type of the value.)

Contrast this with older dialects of C, which were weakly, statically typed, so that pointers and integers were pretty much interchangeable. (Modern ISO C requires conversions in many cases, but my compiler is still lenient about this by default.)

I must add that the strong vs. weak typing is more of a continuum than a boolean choice. C++ has stronger typing than C (more conversions required), but the type system can be subverted by using pointer casts.

The strength of the type system in a dynamic language such as Python is really determined by how its primitives and library functions respond to different types. E.g., + is overloaded so that it works on two numbers or two strings, but not a string and an number. This is a design choice made when + was implemented, but not really a necessity following from the language's semantics. In fact, when you overload + on a custom type, you can make it implicitly convert anything to a number:

def to_number(x):
    """Try to convert function argument to float-type object."""
    try: 
        return float(x) 
    except (TypeError, ValueError): 
        return 0 

class Foo:
    def __init__(self, number): 
        self.number = number

    def __add__(self, other):
        return self.number + to_number(other)

Instance of class Foo can be added to other objects:

>>> a = Foo(42)
>>> a + "1"
43.0
>>> a + Foo
42
>>> a + 1
43.0
>>> a + None
42

Observe that even though strongly typed Python is completely fine with adding objects of type int and float and returns an object of type float (e.g., int(42) + float(1) returns 43.0). On the other hand, due to the mismatch between types Haskell would complain if one tries the following (42 :: Integer) + (1 :: Float). This makes Haskell a strictly typed language, where types are entirely disjoint and only a controlled form of overloading is possible via type classes.

How to programmatically move, copy and delete files and directories on SD?

To move a file this api can be used but you need atleat 26 as api level -

move file

But if you want to move directory no support is there so this native code can be used

    import org.apache.commons.io.FileUtils;

    import java.io.IOException;
    import java.io.File;

    public class FileModule {

    public void moveDirectory(String src, String des) {
    File srcDir = new File(src);
    File destDir = new File(des);
     try {
        FileUtils.moveDirectory(srcDir,destDir);
    } catch (Exception e) {
      Log.e("Exception" , e.toString());
      }
    }

    public void deleteDirectory(String dir) {
      File delDir = new File(dir);
      try {
        FileUtils.deleteDirectory(delDir);
       } catch (IOException e) {
      Log.e("Exception" , e.toString());
      }
     }
    }

Server.MapPath - Physical path given, virtual path expected

var files = Directory.GetFiles(@"E:\ftproot\sales");

Configure Nginx with proxy_pass

Give this a try...

server {
    listen   80;
    server_name  dev.int.com;
    access_log off;
    location / {
        proxy_pass http://IP:8080;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:8080/jira  /;
        proxy_connect_timeout 300;
    }

    location ~ ^/stash {
        proxy_pass http://IP:7990;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:7990/  /stash;
        proxy_connect_timeout 300;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/nginx/html;
    }
}

How do you modify the web.config appSettings at runtime?

2012 This is a better solution for this scenario (tested With Visual Studio 2008):

Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
config.AppSettings.Settings.Remove("MyVariable");
config.AppSettings.Settings.Add("MyVariable", "MyValue");
config.Save();

Update 2018 =>
Tested in vs 2015 - Asp.net MVC5

var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
config.AppSettings.Settings["MyVariable"].Value = "MyValue";
config.Save();

if u need to checking element exist, use this code:

var config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
if (config.AppSettings.Settings["MyVariable"] != null)
{
config.AppSettings.Settings["MyVariable"].Value = "MyValue";
}
else { config.AppSettings.Settings.Add("MyVariable", "MyValue"); }
config.Save();

Cannot find vcvarsall.bat when running a Python script

Install Visual Studio Express 2008 (9.0) from here: http://go.microsoft.com/?linkid=7729279

That's what fixed it for me.

JAXB :Need Namespace Prefix to all the elements

To specify more than one namespace to provide prefixes, use something like:

@javax.xml.bind.annotation.XmlSchema(
    namespace = "urn:oecd:ties:cbc:v1", 
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED,
    xmlns ={@XmlNs(prefix="cbc", namespaceURI="urn:oecd:ties:cbc:v1"), 
            @XmlNs(prefix="iso", namespaceURI="urn:oecd:ties:isocbctypes:v1"),
            @XmlNs(prefix="stf", namespaceURI="urn:oecd:ties:stf:v4")})

... in package-info.java

How do I get the current location of an iframe?

I use this.

var iframe = parent.document.getElementById("theiframe");
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;

var currentFrame = innerDoc.location.href;

How do you determine the size of a file in C?

POSIX

The POSIX standard has its own method to get file size.
Include the sys/stat.h header to use the function.

Synopsis

  • Get file statistics using stat(3).
  • Obtain the st_size property.

Examples

Note: It limits the size to 4GB. If not Fat32 filesystem then use the 64bit version!

#include <stdio.h>
#include <sys/stat.h>

int main(int argc, char** argv)
{
    struct stat info;
    stat(argv[1], &info);

    // 'st' is an acronym of 'stat'
    printf("%s: size=%ld\n", argv[1], info.st_size);
}
#include <stdio.h>
#include <sys/stat.h>

int main(int argc, char** argv)
{
    struct stat64 info;
    stat64(argv[1], &info);

    // 'st' is an acronym of 'stat'
    printf("%s: size=%ld\n", argv[1], info.st_size);
}

ANSI C (standard)

The ANSI C doesn't directly provides the way to determine the length of the file.
We'll have to use our mind. For now, we'll use the seek approach!

Synopsis

  • Seek the file to the end using fseek(3).
  • Get the current position using ftell(3).

Example

#include <stdio.h>

int main(int argc, char** argv)
{
    FILE* fp = fopen(argv[1]);
    int f_size;

    fseek(fp, 0, SEEK_END);
    f_size = ftell(fp);
    rewind(fp); // to back to start again

    printf("%s: size=%ld", (unsigned long)f_size);
}

If the file is stdin or a pipe. POSIX, ANSI C won't work.
It will going return 0 if the file is a pipe or stdin.

Opinion: You should use POSIX standard instead. Because, it has 64bit support.

JS map return object

You're very close already, you just need to return the new object that you want. In this case, the same one except with the launches value incremented by 10:

_x000D_
_x000D_
var rockets = [_x000D_
    { country:'Russia', launches:32 },_x000D_
    { country:'US', launches:23 },_x000D_
    { country:'China', launches:16 },_x000D_
    { country:'Europe(ESA)', launches:7 },_x000D_
    { country:'India', launches:4 },_x000D_
    { country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
var launchOptimistic = rockets.map(function(elem) {_x000D_
  return {_x000D_
    country: elem.country,_x000D_
    launches: elem.launches+10,_x000D_
  } _x000D_
});_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
_x000D_
_x000D_

grep a file, but show several surrounding lines?

Search for "17655" in "/some/file.txt" showing 10 lines context before and after (using Awk), output preceded with line number followed by a colon. Use this on Solaris when 'grep' does not support the "-[ACB]" options.

awk '

/17655/ {
        for (i = (b + 1) % 10; i != b; i = (i + 1) % 10) {
                print before[i]
        }
        print (NR ":" ($0))
        a = 10
}

a-- > 0 {
        print (NR ":" ($0))
}

{
        before[b] = (NR ":" ($0))
        b = (b + 1) % 10
}' /some/file.txt;

Python json.loads shows ValueError: Extra data

I came across this because I was trying to load a JSON file dumped from MongoDB. It was giving me an error

JSONDecodeError: Extra data: line 2 column 1

The MongoDB JSON dump has one object per line, so what worked for me is:

import json
data = [json.loads(line) for line in open('data.json', 'r')]

SQL grammar for SELECT MIN(DATE)

To get the titles for dates greater than a week ago today, use this:

SELECT title, MIN(date_key_no) AS intro_date FROM table HAVING MIN(date_key_no)>= TO_NUMBER(TO_CHAR(SysDate, 'YYYYMMDD')) - 7

How to printf "unsigned long" in C?

Out of all the combinations you tried, %ld and %lu are the only ones which are valid printf format specifiers at all. %lu (long unsigned decimal), %lx or %lX (long hex with lowercase or uppercase letters), and %lo (long octal) are the only valid format specifiers for a variable of type unsigned long (of course you can add field width, precision, etc modifiers between the % and the l).

Select Rows with id having even number

SELECT * FROM Orders where OrderID % 2 = 0;///this is for even numbers

SELECT * FROM Orders where OrderID % 2 != 0;///this is for odd numbers

Is it safe to delete a NULL pointer?

Yes it is safe.

There's no harm in deleting a null pointer; it often reduces the number of tests at the tail of a function if the unallocated pointers are initialized to zero and then simply deleted.


Since the previous sentence has caused confusion, an example — which isn't exception safe — of what is being described:

void somefunc(void)
{
    SomeType *pst = 0;
    AnotherType *pat = 0;

    …
    pst = new SomeType;
    …
    if (…)
    {
        pat = new AnotherType[10];
        …
    }
    if (…)
    {
        …code using pat sometimes…
    }

    delete[] pat;
    delete pst;
}

There are all sorts of nits that can be picked with the sample code, but the concept is (I hope) clear. The pointer variables are initialized to zero so that the delete operations at the end of the function do not need to test whether they're non-null in the source code; the library code performs that check anyway.

Changing default encoding of Python?

This is a quick hack for anyone who is (1) On a Windows platform (2) running Python 2.7 and (3) annoyed because a nice piece of software (i.e., not written by you so not immediately a candidate for encode/decode printing maneuvers) won't display the "pretty unicode characters" in the IDLE environment (Pythonwin prints unicode fine), For example, the neat First Order Logic symbols that Stephan Boyer uses in the output from his pedagogic prover at First Order Logic Prover.

I didn't like the idea of forcing a sys reload and I couldn't get the system to cooperate with setting environment variables like PYTHONIOENCODING (tried direct Windows environment variable and also dropping that in a sitecustomize.py in site-packages as a one liner ='utf-8').

So, if you are willing to hack your way to success, go to your IDLE directory, typically: "C:\Python27\Lib\idlelib" Locate the file IOBinding.py. Make a copy of that file and store it somewhere else so you can revert to original behavior when you choose. Open the file in the idlelib with an editor (e.g., IDLE). Go to this code area:

# Encoding for file names
filesystemencoding = sys.getfilesystemencoding()

encoding = "ascii"
if sys.platform == 'win32':
    # On Windows, we could use "mbcs". However, to give the user
    # a portable encoding name, we need to find the code page 
    try:
        # --> 6/5/17 hack to force IDLE to display utf-8 rather than cp1252
        # --> encoding = locale.getdefaultlocale()[1]
        encoding = 'utf-8'
        codecs.lookup(encoding)
    except LookupError:
        pass

In other words, comment out the original code line following the 'try' that was making the encoding variable equal to locale.getdefaultlocale (because that will give you cp1252 which you don't want) and instead brute force it to 'utf-8' (by adding the line 'encoding = 'utf-8' as shown).

I believe this only affects IDLE display to stdout and not the encoding used for file names etc. (that is obtained in the filesystemencoding prior). If you have a problem with any other code you run in IDLE later, just replace the IOBinding.py file with the original unmodified file.

Fastest way to determine if record exists

I've used this in the past and it doesn't require a full table scan to see if something exists. It's super fast...

UPDATE TableName SET column=value WHERE column=value
IF @@ROWCOUNT=0
BEGIN
     --Do work
END             

How to combine GROUP BY, ORDER BY and HAVING

Steps for Using Group by,Having By and Order by...

Select Attitude ,count(*) from Person
group by person
HAving PersonAttitude='cool and friendly'
Order by PersonName.

React : difference between <Route exact path="/" /> and <Route path="/" />

Take a look here: https://reacttraining.com/react-router/core/api/Route/exact-bool

exact: bool

When true, will only match if the path matches the location.pathname exactly.

**path**    **location.pathname**   **exact**   **matches?**

/one        /one/two                true        no
/one        /one/two                false       yes

Find unique rows in numpy.array

The most straightforward solution is to make the rows a single item by making them strings. Each row then can be compared as a whole for its uniqueness using numpy. This solution is generalize-able you just need to reshape and transpose your array for other combinations. Here is the solution for the problem provided.

import numpy as np

original = np.array([[1, 1, 1, 0, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [0, 1, 1, 1, 0, 0],
       [1, 1, 1, 0, 0, 0],
       [1, 1, 1, 1, 1, 0]])

uniques, index = np.unique([str(i) for i in original], return_index=True)
cleaned = original[index]
print(cleaned)    

Will Give:

 array([[0, 1, 1, 1, 0, 0],
        [1, 1, 1, 0, 0, 0],
        [1, 1, 1, 1, 1, 0]])

Send my nobel prize in the mail

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available

The issue is due to OpenSSL package is missing on your PC.

If pip install openpyxl also gives error.

you can fix this by installing OpenSSL(Win64 OpenSSL v1.1.1g) from below site :

slproweb.com/products/Win32OpenSSL.html

Restart the IDE you are using, for changes to be in effect.

Spring MVC Multipart Request with JSON

We've seen in our projects that a post request with JSON and files is creating a lot of confusion between the frontend and backend developers, leading to unnecessary wastage of time.

Here's a better approach: convert file bytes array to Base64 string and send it in the JSON.

public Class UserDTO {
    private String firstName;
    private String lastName;
    private FileDTO profilePic; 
}

public class FileDTO {
    private String base64;
    // just base64 string is enough. If you want, send additional details
    private String name;
    private String type;
    private String lastModified;
}

@PostMapping("/user")
public String saveUser(@RequestBody UserDTO user) {
    byte[] fileBytes = Base64Utils.decodeFromString(user.getProfilePic().getBase64());
    ....
}

JS code to convert file to base64 string:

var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {

  const userDTO = {
    firstName: "John",
    lastName: "Wick",
    profilePic: {
      base64: reader.result,
      name: file.name,
      lastModified: file.lastModified,
      type: file.type
    }
  }
  
  // post userDTO
};
reader.onerror = function (error) {
  console.log('Error: ', error);
};

All com.android.support libraries must use the exact same version specification

The best way to solve the problem is implement all 'com.android.support:...' suggested by Android Studio

(Doesn't matter which support versions you are using – 27.1.1, 28.0.0 etc.)

Place the cursor to the error line e.g.

implementation 'com.android.support:appcompat-v7:28.0.0'

Android Studio will suggest you which 'com.android.support:...' is different version than 'com.android.support:appcompat-v7:28.0.0'

Example

All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 28.0.0, 27.1.0, 27.0.2. Examples include com.android.support:animated-vector-drawable:28.0.0 and com.android.support:exifinterface:27.1.0

So add com.android.support:animated-vector-drawable:28.0.0 & com.android.support:exifinterface:28.0.0. Now sync gradle file.

One by one try to implement all the suggested 'com.android.support:...' until there is no error in this line implementation 'com.android.support:appcompat-v7:28.0.0'

In my case, I added

implementation 'com.android.support:appcompat-v7:28.0.0'

implementation 'com.android.support:animated-vector-drawable:28.0.0'
implementation 'com.android.support:exifinterface:28.0.0'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:customtabs:28.0.0'
implementation 'com.android.support:support-media-compat:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'

All these dependencies, it could be different for you.

`&mdash;` or `&#8212;` is there any difference in HTML output?

From W3 web site Common HTML entities used for typography

For the sake of portability, Unicode entity references should be reserved for use in documents certain to be written in the UTF-8 or UTF-16 character sets. In all other cases, the alphanumeric references should be used.

Translation: If you are looking for widest support, go with &mdash;

PHP passing $_GET in linux command prompt

At the command line paste the following

export QUERY_STRING="param1=abc&param2=xyz" ;  
POST_STRING="name=John&lastname=Doe" ; php -e -r 
'parse_str($_SERVER["QUERY_STRING"], $_GET); parse_str($_SERVER["POST_STRING"], 
$_POST);  include "index.php";'

Disable submit button ONLY after submit

This solution has the advantages of working on mobile and being quite simple:

<form ... onsubmit="myButtonValue.disabled = true; return true;">

SQL Query To Obtain Value that Occurs more than once

For postgresql:

SELECT * AS rec 
FROM (
    SELECT lastname, COUNT(*) AS counter 
    FROM students 
    GROUP BY lastname) AS tbl 
WHERE counter > 1;

Deserialize a JSON array in C#

This should work...

JavaScriptSerializer ser = new JavaScriptSerializer();
var records = new ser.Deserialize<List<Record>>(jsonData);

public class Person
{
    public string Name;
    public int Age;
    public string Location;
}
public class Record
{
    public Person record;
}

How to split a file into equal parts, without breaking individual lines?

I made a bash script, that given a number of parts as input, split a file

#!/bin/sh

parts_total="$2";
input="$1";

parts=$((parts_total))
for i in $(seq 0 $((parts_total-2))); do
  lines=$(wc -l "$input" | cut -f 1 -d" ")
  #n is rounded, 1.3 to 2, 1.6 to 2, 1 to 1
  n=$(awk  -v lines=$lines -v parts=$parts 'BEGIN { 
    n = lines/parts;
    rounded = sprintf("%.0f", n);
    if(n>rounded){
      print rounded + 1;
    }else{
      print rounded;
    }
  }');
  head -$n "$input" > split${i}
  tail -$((lines-n)) "$input" > .tmp${i}
  input=".tmp${i}"
  parts=$((parts-1));
done
mv .tmp$((parts_total-2)) split$((parts_total-1))
rm .tmp*

I used head and tail commands, and store in tmp files, for split the files

#10 means 10 parts
sh mysplitXparts.sh input_file 10

or with awk, where 0.1 is 10% => 10 parts, or 0.334 is 3 parts

awk -v size=$(wc -l < input) -v perc=0.1 '{
  nfile = int(NR/(size*perc)); 
  if(nfile >= 1/perc){
    nfile--;
  } 
  print > "split_"nfile
}' input

Unable to start debugging on the web server. Could not start ASP.NET debugging VS 2010, II7, Win 7 x64

If App Pool has trouble restarting or simply doesn't want to restart, verify if windows made recent update on ASP.NET v4.0 or other App Pool. That is what happend in my case. I simply restarted my computer, then restarted ASP.NET v4.0 App Pool and everything was working again!

The name 'InitializeComponent' does not exist in the current context

For those who find this on the internet. Check the Windows.csproj file if the compilation is there. There should be 2 entries

<Page Include="YourFile.xaml">
  <SubType>Designer</SubType>
  <Generator>MSBuild:Compile</Generator>
</Page>

<Compile Include="YourFile.xaml.cs">
  <DependentUpon>YourFile.xaml</DependentUpon>
</Compile>

Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman

If you are using AngularJS you need to pass the body params as string:

    factory.getToken = function(person_username) {
    console.log('Getting DI Token');
    var url = diUrl + "/token";

    return $http({
        method: 'POST',
        url: url,
        data: 'grant_type=password&[email protected]&password=mypass',
        responseType:'json',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    });
};

Get all dates between two dates in SQL Server

Easily create a Table Value Function that will return a table with all dates. Input dates as string You can customize the date in the the format you like '01/01/2017' or '01-01-2017' in string formats (103,126 ...)

Try this

CREATE FUNCTION [dbo].[DateRange_To_Table] ( @minDate_Str NVARCHAR(30), @maxDate_Str NVARCHAR(30))

RETURNS  @Result TABLE(DateString NVARCHAR(30) NOT NULL, DateNameString NVARCHAR(30) NOT NULL)

AS

begin

    DECLARE @minDate DATETIME, @maxDate DATETIME
    SET @minDate = CONVERT(Datetime, @minDate_Str,103)
    SET @maxDate = CONVERT(Datetime, @maxDate_Str,103)


    INSERT INTO @Result(DateString, DateNameString )
    SELECT CONVERT(NVARCHAR(10),@minDate,103), CONVERT(NVARCHAR(30),DATENAME(dw,@minDate))



    WHILE @maxDate > @minDate
    BEGIN
        SET @minDate = (SELECT DATEADD(dd,1,@minDate))
        INSERT INTO @Result(DateString, DateNameString )
        SELECT CONVERT(NVARCHAR(10),@minDate,103), CONVERT(NVARCHAR(30),DATENAME(dw,@minDate))
    END




    return

end   

To execute the function do this:

SELECT * FROM dbo.DateRange_To_Table ('01/01/2017','31/01/2017')

The output will be

01/01/2017  Sunday
02/01/2017  Monday
03/01/2017  Tuesday
04/01/2017  Wednesday
05/01/2017  Thursday
06/01/2017  Friday
07/01/2017  Saturday
08/01/2017  Sunday
09/01/2017  Monday
10/01/2017  Tuesday
11/01/2017  Wednesday
12/01/2017  Thursday
13/01/2017  Friday
14/01/2017  Saturday
15/01/2017  Sunday
16/01/2017  Monday
17/01/2017  Tuesday
18/01/2017  Wednesday
19/01/2017  Thursday
20/01/2017  Friday
21/01/2017  Saturday
22/01/2017  Sunday
23/01/2017  Monday
24/01/2017  Tuesday
25/01/2017  Wednesday
26/01/2017  Thursday
27/01/2017  Friday
28/01/2017  Saturday
29/01/2017  Sunday
30/01/2017  Monday
31/01/2017  Tuesday

How to change a string into uppercase

s = 'sdsd'
print (s.upper())
upper = raw_input('type in something lowercase.')
lower = raw_input('type in the same thing caps lock.')
print upper.upper()
print lower.lower()

How to convert milliseconds into human readable form?

This is a method I wrote. It takes an integer milliseconds value and returns a human-readable String:

public String convertMS(int ms) {
    int seconds = (int) ((ms / 1000) % 60);
    int minutes = (int) (((ms / 1000) / 60) % 60);
    int hours = (int) ((((ms / 1000) / 60) / 60) % 24);

    String sec, min, hrs;
    if(seconds<10)  sec="0"+seconds;
    else            sec= ""+seconds;
    if(minutes<10)  min="0"+minutes;
    else            min= ""+minutes;
    if(hours<10)    hrs="0"+hours;
    else            hrs= ""+hours;

    if(hours == 0)  return min+":"+sec;
    else    return hrs+":"+min+":"+sec;

}

Programmatically obtain the phone number of the Android phone

This is a more simplified answer:

public String getMyPhoneNumber()
{
    return ((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
            .getLine1Number();
}

What is the most robust way to force a UIView to redraw?

Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.

The way you do this is in the UITableView didSelectRowAtIndexPath you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue. Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD

How can I change a file's encoding with vim?

It could be useful to change the encoding just on the command line before the file is read:

rem On MicroSoft Windows
vim --cmd "set encoding=utf-8" file.ext
# In *nix shell
vim --cmd 'set encoding=utf-8' file.ext

See starting, --cmd.

What are the differences between LDAP and Active Directory?

Active Directory is a super-set of the LDAP protocol. Depending on how the organization uses Active Directory, your LDAP search/set queries may or may not work.

curl error 18 - transfer closed with outstanding read data remaining

Seeing this error during the use of Guzzle as well. The following header fixed it for me:

'headers' => [
    'accept-encoding' => 'gzip, deflate',
],

I issued the request with Postman which gave me a complete response and no error. Then I started adding the headers that Postman sends to the Guzzle request and this was the one that fixed it.

Is it possible to change the speed of HTML's <marquee> tag?

There isn't specifically an attribute to control that. Marquee isn't a highly reliable tag anyways. You may want to consider using jQuery and the .animate() function. If you are interested in pursuing that avenue and need code for it, just let me know.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

This is a problem for users who live in a country that is banned by Google (like Iran). for this reason we need to remove these restrictions by a proxy. follow me :

file->settings->Appearance&Behavior->System Setting-> Http Proxy-> Manual proxy configuration ->HTTP -> Host name : fodev.org ->Port : 8118 .

and click Ok Button. then go to file-> Invalidate Caches/Restart . . . Use and enjoy the correct execution without error ;)

Getting multiple selected checkbox values in a string in javascript and PHP

I you are using jQuery you can put the checkboxes in a form and then use something like this:

var formData = jQuery("#" + formId).serialize();

$.ajax({
      type: "POST",
      url: url,
      data: formData,
      success: success
}); 

Where is virtualenvwrapper.sh after pip install?

You can use the find command to search for a file:

find / -name virtualenvwrapper.sh

This will search all directories from the root for the file.


on ubuntu 12.04 LTS, installing through pip, it is installed to

/usr/local/bin/virtualenvwrapper.sh


on ubuntu 17.04, installing through pip as a normal user, it is installed to

~/.local/bin/virtualenvwrapper.sh

How do I print a list of "Build Settings" in Xcode project?

This has been answered above, but I wanted to suggest an alternative.

When in the Build Settings for you project or target, you can go to the Editor menu and select Show Setting Names from the menu. This will change all of the options in the Build Settings pane to the build variable names. The option in the menu changes to Show Setting Titles, select this to change back to the original view.

This can be handy when you know what build setting you want to use in a script, toggle the setting names in the menu and you can see the variable name.

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

How do I tell if .NET 3.5 SP1 is installed?

Take a look at this article which shows the registry keys you need to look for and provides a .NET library that will do this for you.

First, you should to determine if .NET 3.5 is installed by looking at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install, which is a DWORD value. If that value is present and set to 1, then that version of the Framework is installed.

Look at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP, which is a DWORD value which indicates the Service Pack level (where 0 is no service pack).

To be correct about things, you really need to ensure that .NET Fx 2.0 and .NET Fx 3.0 are installed first and then check to see if .NET 3.5 is installed. If all three are true, then you can check for the service pack level.

Matrix Transpose in Python

def matrixTranspose(anArray):
  transposed = [None]*len(anArray[0])

  for i in range(len(transposed)):
    transposed[i] = [None]*len(transposed)

  for t in range(len(anArray)):
    for tt in range(len(anArray[t])):            
        transposed[t][tt] = anArray[tt][t]
  return transposed

theArray = [['a','b','c'],['d','e','f'],['g','h','i']]

print matrixTranspose(theArray)

Make a URL-encoded POST request using `http.NewRequest(...)`

URL-encoded payload must be provided on the body parameter of the http.NewRequest(method, urlStr string, body io.Reader) method, as a type that implements io.Reader interface.

Based on the sample code:

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Set("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String() // "https://api.com/user/"

    client := &http.Client{}
    r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
}

resp.Status is 200 OK this way.

How to remove listview all items

Call setListAdapter() again. This time with an empty ArrayList.

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

How can I show a hidden div when a select option is selected?

take look at my solution

i want to make visaCard-note div to be visible only if selected cardType is visa

and here is the html

<select name="cardType">
    <option value="1">visa</option>
    <option value="2">mastercard</option>
</select>

here is the js

var visa="1";//visa is selected by default 
$("select[name=cardType]").change(function () {
    document.getElementById('visaCard-note').style.visibility = this.value==visa ? 'visible' : 'hidden';
})

Submit form after calling e.preventDefault()

Sorry for delay, but I will try to make perfect form :)

I will added Count validation steps and check every time not .val(). Check .length, because I think is better pattern in your case. Of course remove unbind function.

My jsFiddle

Of course source code:

// Prevent form submit if any entrees are missing
$('form').submit(function(e){

    e.preventDefault();

    var formIsValid = true;

    // Count validation steps
    var validationLoop = 0;

    // Cycle through each Attendee Name
    $('[name="atendeename[]"]', this).each(function(index, el){

        // If there is a value
        if ($(el).val().length > 0) {
            validationLoop++;

            // Find adjacent entree input
            var entree = $(el).next('input');

            var entreeValue = entree.val();

            // If entree is empty, don't submit form
            if (entreeValue.length === 0) {
                alert('Please select an entree');
                entree.focus();
                formIsValid = false;
                return false;
            }

        }

    });

    if (formIsValid && validationLoop > 0) {
        alert("Correct Form");
        return true;
    } else {
        return false;
    }

});

PHP Fatal Error Failed opening required File

You could fix it with the PHP constant __DIR__

require_once __DIR__ . '/common/configs/config_templates.inc.php';

It is the directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname __FILE__ . This directory name does not have a trailing slash unless it is the root directory. 1

Facebook Graph API error code list

While there does not appear to be a public, Facebook-curated list of error codes available, a number of folks have taken it upon themselves to publish lists of known codes.

Take a look at StackOverflow #4348018 - List of Facebook error codes for a number of useful resources.

How to display gpg key details without importing it?

There are several detail levels you can get when looking at OpenPGP key data: a basic summary, a machine-readable output of this summary or a detailed (and very technical) list of the individual OpenPGP packets.

Basic Key Information

For a brief peak at an OpenPGP key file, you can simply pass the filename as parameter or pipe in the key data through STDIN. If no command is passed, GnuPG tries to guess what you want to do -- and for key data, this is printing a summary on the key:

$ gpg a4ff2279.asc
gpg: WARNING: no command supplied.  Trying to guess what you mean ...
pub   rsa8192 2012-12-25 [SC]
      0D69E11F12BDBA077B3726AB4E1F799AA4FF2279
uid           Jens Erat (born 1988-01-19 in Stuttgart, Germany)
uid           Jens Erat <[email protected]>
uid           Jens Erat <[email protected]>
uid           Jens Erat <[email protected]>
uid           Jens Erat <[email protected]>
uid           [jpeg image of size 12899]
sub   rsa4096 2012-12-26 [E] [revoked: 2014-03-26]
sub   rsa4096 2012-12-26 [S] [revoked: 2014-03-26]
sub   rsa2048 2013-01-23 [S] [expires: 2023-01-21]
sub   rsa2048 2013-01-23 [E] [expires: 2023-01-21]
sub   rsa4096 2014-03-26 [S] [expires: 2020-09-03]
sub   rsa4096 2014-03-26 [E] [expires: 2020-09-03]
sub   rsa4096 2014-11-22 [A] [revoked: 2016-03-01]
sub   rsa4096 2016-02-24 [A] [expires: 2020-02-23]

By setting --keyid-format 0xlong, long key IDs are printed instead of the insecure short key IDs:

$ gpg a4ff2279.asc                                                                 
gpg: WARNING: no command supplied.  Trying to guess what you mean ...
pub   rsa8192/0x4E1F799AA4FF2279 2012-12-25 [SC]
      0D69E11F12BDBA077B3726AB4E1F799AA4FF2279
uid                             Jens Erat (born 1988-01-19 in Stuttgart, Germany)
uid                             Jens Erat <[email protected]>
uid                             Jens Erat <[email protected]>
uid                             Jens Erat <[email protected]>
uid                             Jens Erat <[email protected]>
uid                             [jpeg image of size 12899]
sub   rsa4096/0x0F3ED8E6759A536E 2012-12-26 [E] [revoked: 2014-03-26]
sub   rsa4096/0x2D6761A7CC85941A 2012-12-26 [S] [revoked: 2014-03-26]
sub   rsa2048/0x9FF7E53ACB4BD3EE 2013-01-23 [S] [expires: 2023-01-21]
sub   rsa2048/0x5C88F5D83E2554DF 2013-01-23 [E] [expires: 2023-01-21]
sub   rsa4096/0x8E78E44DFB1B55E9 2014-03-26 [S] [expires: 2020-09-03]
sub   rsa4096/0xCC73B287A4388025 2014-03-26 [E] [expires: 2020-09-03]
sub   rsa4096/0x382D23D4C9773A5C 2014-11-22 [A] [revoked: 2016-03-01]
sub   rsa4096/0xFF37A70EDCBB4926 2016-02-24 [A] [expires: 2020-02-23]
pub   rsa1024/0x7F60B22EA4FF2279 2014-06-16 [SCEA] [revoked: 2016-08-16]

Providing -v or -vv will even add some more information. I prefer printing the package details in this case, though (see below).

Machine-Readable Output

GnuPG also has a colon-separated output format, which is easily parsable and has a stable format. The format is documented in GnuPG doc/DETAILS file. The option to receive this format is --with-colons.

$ gpg --with-colons a4ff2279.asc
gpg: WARNING: no command supplied.  Trying to guess what you mean ...
pub:-:8192:1:4E1F799AA4FF2279:1356475387:::-:
uid:::::::::Jens Erat (born 1988-01-19 in Stuttgart, Germany):
uid:::::::::Jens Erat <[email protected]>:
uid:::::::::Jens Erat <[email protected]>:
uid:::::::::Jens Erat <[email protected]>:
uid:::::::::Jens Erat <[email protected]>:
uat:::::::::1 12921:
sub:-:4096:1:0F3ED8E6759A536E:1356517233:1482747633:::
sub:-:4096:1:2D6761A7CC85941A:1356517456:1482747856:::
sub:-:2048:1:9FF7E53ACB4BD3EE:1358985314:1674345314:::
sub:-:2048:1:5C88F5D83E2554DF:1358985467:1674345467:::
sub:-:4096:1:8E78E44DFB1B55E9:1395870592:1599164118:::
sub:-:4096:1:CC73B287A4388025:1395870720:1599164118:::
sub:-:4096:1:382D23D4C9773A5C:1416680427:1479752427:::
sub:-:4096:1:FF37A70EDCBB4926:1456322829:1582466829:::

Since GnuPG 2.1.23, the gpg: WARNING: no command supplied. Trying to guess what you mean ... warning can be omitted by using the --import-options show-only option together with the --import command (this also works without --with-colons, of course):

$ gpg --with-colons --import-options show-only --import a4ff2279
[snip]

For older versions: the warning message is printed on STDERR, so you could just read STDIN to split apart the key information from the warning.

Technical Details: Listing OpenPGP Packets

Without installing any further packages, you can use gpg --list-packets [file] to view information on the OpenPGP packets contained in the file.

$ gpg --list-packets a4ff2279.asc
:public key packet:
    version 4, algo 1, created 1356475387, expires 0
    pkey[0]: [8192 bits]
    pkey[1]: [17 bits]
    keyid: 4E1F799AA4FF2279
:user ID packet: "Jens Erat (born 1988-01-19 in Stuttgart, Germany)"
:signature packet: algo 1, keyid 4E1F799AA4FF2279
    version 4, created 1356516623, md5len 0, sigclass 0x13
    digest algo 2, begin of digest 18 46
    hashed subpkt 27 len 1 (key flags: 03)
[snip]

The pgpdump [file] tool works similar to gpg --list-packets and provides a similar output, but resolves all those algorithm identifiers to readable representations. It is available for probably all relevant distributions (on Debian derivatives, the package is called pgpdump like the tool itself).

$ pgpdump a4ff2279.asc
Old: Public Key Packet(tag 6)(1037 bytes)
    Ver 4 - new
    Public key creation time - Tue Dec 25 23:43:07 CET 2012
    Pub alg - RSA Encrypt or Sign(pub 1)
    RSA n(8192 bits) - ...
    RSA e(17 bits) - ...
Old: User ID Packet(tag 13)(49 bytes)
    User ID - Jens Erat (born 1988-01-19 in Stuttgart, Germany)
Old: Signature Packet(tag 2)(1083 bytes)
    Ver 4 - new
    Sig type - Positive certification of a User ID and Public Key packet(0x13).
    Pub alg - RSA Encrypt or Sign(pub 1)
    Hash alg - SHA1(hash 2)
    Hashed Sub: key flags(sub 27)(1 bytes)
[snip]

How to list only files and not directories of a directory Bash?

"find '-maxdepth' " does not work with my old version of bash, therefore I use:

for f in $(ls) ; do if [ -f $f ] ; then echo $f ; fi ; done

Find (and kill) process locking port 3000 on Mac

Using sindresorhus's fkill tool, you can do this:

$ fkill :3000

Django MEDIA_URL and MEDIA_ROOT

If you'r using python 3.0+ then configure your project as below

Setting

STATIC_DIR = BASE_DIR / 'static'
MEDIA_DIR = BASE_DIR / 'media'
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'

Main Urls

from django.conf import settings
from django.conf.urls.static import static

urlspatterns=[
........
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Printing prime numbers from 1 through 100

A simple program to print "N" prime numbers. You can use N value as 100.

    #include  <iostream >
    using  namespace  std;

    int  main()
    {
        int  N;
        cin  >>  N;
        for (int  i =  2;  N > 0;  ++i)
        {
            bool  isPrime  =  true ;
            for (int  j =  2;  j < i;  ++j)
            {
                if (i  % j ==  0)
                {
                    isPrime  =  false ;
                    break ;
                }
            }
            if (isPrime)
            {
                --N;
                cout  <<  i  <<  "\n";
            }
        }
        return  0;
    }

Getting an option text/value with JavaScript

var option_user_selection = document.getElementById("maincourse").options[document.getElementById("maincourse").selectedIndex ].text

PHP: Convert any string to UTF-8 without knowing the original character set, or at least try

There is no way to identify the charset of a string that is completely accurate. There are ways to try to guess the charset. One of these ways, and probably/currently the best in PHP, is mb_detect_encoding(). This will scan your string and look for occurrences of stuff unique to certain charsets. Depending on your string, there may not be such distinguishable occurrences.

Take the ISO-8859-1 charset vs ISO-8859-15 ( http://en.wikipedia.org/wiki/ISO/IEC_8859-15#Changes_from_ISO-8859-1 )

There's only a handful of different characters, and to make it worse, they're represented by the same bytes. There is no way to detect, being given a string without knowing it's encoding, whether byte 0xA4 is supposed to signify ¤ or € in your string, so there is no way to know it's exact charset.

(Note: you could add a human factor, or an even more advanced scanning technique (e.g. what Oroboros102 suggests), to try to figure out based upon the surrounding context, if the character should be ¤ or €, though this seems like a bridge too far)

There are more distinguishable differences between e.g. UTF-8 and ISO-8859-1, so it's still worth trying to figure it out when you're unsure, though you can and should never rely on it being correct.

Interesting read: http://kore-nordmann.de/blog/php_charset_encoding_FAQ.html#how-do-i-determine-the-charset-encoding-of-a-string

There are other ways of ensuring the correct charset though. Concerning forms, try to enforce UTF-8 as much as possible (check out snowman to make sure yout submission will be UTF-8 in every browser: http://intertwingly.net/blog/2010/07/29/Rails-and-Snowmen ) That being done, at least you're can be sure that every text submitted through your forms is utf_8. Concerning uploaded files, try running the unix 'file -i' command on it through e.g. exec() (if possible on your server) to aid the detection (using the document's BOM.) Concerning scraping data, you could read the HTTP headers, that usually specify the charset. When parsing XML files, see if the XML meta-data contain a charset definition.

Rather than trying to automagically guess the charset, you should first try to ensure a certain charset yourself where possible, or trying to grab a definition from the source you're getting it from (if applicable) before resorting to detection.

Best way to update data with a RecyclerView adapter

RecyclerView's Adapter doesn't come with many methods otherwise available in ListView's adapter. But your swap can be implemented quite simply as:

class MyRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
   List<Data> data;
   ...

    public void swap(ArrayList<Data> datas)
    {
        data.clear();
        data.addAll(datas);
        notifyDataSetChanged();     
    }
}

Also there is a difference between

list.clear();
list.add(data);

and

list = newList;

The first is reusing the same list object. The other is dereferencing and referencing the list. The old list object which can no longer be reached will be garbage collected but not without first piling up heap memory. This would be the same as initializing new adapter everytime you want to swap data.

MS SQL 2008 - get all table names and their row counts in a DB

to get all tables in a database:

select * from INFORMATION_SCHEMA.TABLES

to get all columns in a database:

select * from INFORMATION_SCHEMA.columns

to get all views in a db:

select * from INFORMATION_SCHEMA.TABLES where table_type = 'view'

Regex to match 2 digits, optional decimal, two digits

To build on Lee's answer, you need to anchor the expression to satisfy the requirement of not having more than 2 numbers before the decimal.

If each number is a separate string, you can use the string anchors:

^\d{0,2}(\.\d{1,2})?$

If each number is within a string, you can use the word anchors:

\b\d{0,2}(\.\d{1,2})?\b

Run local python script on remote server

Although this question isn't quite new and an answer was already chosen, I would like to share another nice approach.

Using the paramiko library - a pure python implementation of SSH2 - your python script can connect to a remote host via SSH, copy itself (!) to that host and then execute that copy on the remote host. Stdin, stdout and stderr of the remote process will be available on your local running script. So this solution is pretty much independent of an IDE.

On my local machine, I run the script with a cmd-line parameter 'deploy', which triggers the remote execution. Without such a parameter, the actual code intended for the remote host is run.

import sys
import os

def main():
    print os.name

if __name__ == '__main__':
    try:
        if sys.argv[1] == 'deploy':
            import paramiko

            # Connect to remote host
            client = paramiko.SSHClient()
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect('remote_hostname_or_IP', username='john', password='secret')

            # Setup sftp connection and transmit this script
            sftp = client.open_sftp()
            sftp.put(__file__, '/tmp/myscript.py')
            sftp.close()

            # Run the transmitted script remotely without args and show its output.
            # SSHClient.exec_command() returns the tuple (stdin,stdout,stderr)
            stdout = client.exec_command('python /tmp/myscript.py')[1]
            for line in stdout:
                # Process each line in the remote output
                print line

            client.close()
            sys.exit(0)
    except IndexError:
        pass

    # No cmd-line args provided, run script normally
    main()

Exception handling is left out to simplify this example. In projects with multiple script files you will probably have to put all those files (and other dependencies) on the remote host.

AngularJS ng-click stopPropagation

ngClick directive (as well as all other event directives) creates $event variable which is available on same scope. This variable is a reference to JS event object and can be used to call stopPropagation():

<table>
  <tr ng-repeat="user in users" ng-click="showUser(user)">
    <td>{{user.firstname}}</td>
    <td>{{user.lastname}}</td>
    <td>
      <button class="btn" ng-click="deleteUser(user.id, $index); $event.stopPropagation();">
        Delete
      </button>
    </td>              
  </tr>
</table>

PLUNKER

Index of duplicates items in a python list

Wow, everyone's answer is so long. I simply used a pandas dataframe, masking, and the duplicated function (keep=False markes all duplicates as True, not just first or last):

import pandas as pd
import numpy as np
np.random.seed(42)  # make results reproducible

int_df = pd.DataFrame({'int_list': np.random.randint(1, 20, size=10)})
dupes = int_df['int_list'].duplicated(keep=False)
print(int_df['int_list'][dupes].index)

This should return Int64Index([0, 2, 3, 4, 6, 7, 9], dtype='int64').

Add Favicon to Website

Simply put a file named favicon.ico in the webroot.

If you want to know more, please start reading:

ReactJS Two components communicating

Oddly nobody mentioned mobx. The idea is similar to redux. If I have a piece of data that multiple components are subscribed to it, then I can use this data to drive multiple components.