Programs & Examples On #Castor

Castor is an open source data binding framework.

How to force browser to download file?

Set content-type and other headers before you write the file out. For small files the content is buffered, and the browser gets the headers first. For big ones the data come first.

How to execute 16-bit installer on 64-bit Win7?

I posted some information on the Infragistics forums for designer widgets that may help you for this. You can view the post with the following link:
http://forums.infragistics.com/forums/p/52530/320151.aspx#320151

Note that the registry keys would be different for the different product and you may need to install on a 32 bit machine to see what keys you need.

What is the difference between a static and a non-static initialization code block

The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.

Class initializers are executed in the order they are defined (top down, just like simple variable initializers) when the class is loaded (actually, when it's resolved, but that's a technicality).

Instance initializers are executed in the order defined when the class is instantiated, immediately before the constructor code is executed, immediately after the invocation of the super constructor.

If you remove static from int a, it becomes an instance variable, which you are not able to access from the static initializer block. This will fail to compile with the error "non-static variable a cannot be referenced from a static context".

If you also remove static from the initializer block, it then becomes an instance initializer and so int a is initialized at construction.

Oracle find a constraint

maybe this can help..

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

Portable way to get file size (in bytes) in shell?

Finally I decided to use ls, and bash array expansion:

TEMP=( $( ls -ln FILE ) )
SIZE=${TEMP[4]}

it's not really nice, but at least it does only 1 fork+execve, and it doesn't rely on secondary programming language (perl/ruby/python/whatever)

How to multiply all integers inside list

Another functional approach which is maybe a little easier to look at than an anonymous function if you go that route is using functools.partial to utilize the two-parameter operator.mul with a fixed multiple

>>> from functools import partial
>>> from operator import mul
>>> double = partial(mul, 2)
>>> list(map(double, [1, 2, 3]))
[2, 4, 6]

serialize/deserialize java 8 java.time with Jackson JSON mapper

If you are using Jersey then you need to add the Maven dependency (jackson-datatype-jsr310) as the others suggested and register your object mapper instance like so:

@Provider
public class JacksonObjectMapper implements ContextResolver<ObjectMapper> {

  final ObjectMapper defaultObjectMapper;

  public JacksonObjectMapper() {
    defaultObjectMapper = createDefaultMapper();
  }

  @Override
  public ObjectMapper getContext(Class<?> type) {
    return defaultObjectMapper;
  }

  private static ObjectMapper createDefaultMapper() {
    final ObjectMapper mapper = new ObjectMapper();    
    mapper.registerModule(new JavaTimeModule());
    return mapper;
  }
}

When registering Jackson in your resources, you need to add this mapper like so:

final ResourceConfig rc = new ResourceConfig().packages("<your package>");
rc
  .register(JacksonObjectMapper.class)
  .register(JacksonJaxbJsonProvider.class);

Java: get greatest common divisor

Or the Euclidean algorithm for calculating the GCD...

public int egcd(int a, int b) {
    if (a == 0)
        return b;

    while (b != 0) {
        if (a > b)
            a = a - b;
        else
            b = b - a;
    }

    return a;
}

What's the difference between interface and @interface in java?

interface in the Java programming language is an abstract type that is used to specify a behavior that classes must implement. They are similar to protocols. Interfaces are declared using the interface keyword

@interface is used to create your own (custom) Java annotations. Annotations are defined in their own file, just like a Java class or interface. Here is custom Java annotation example:

@interface MyAnnotation {

    String   value();

    String   name();
    int      age();
    String[] newNames();

}

This example defines an annotation called MyAnnotation which has four elements. Notice the @interface keyword. This signals to the Java compiler that this is a Java annotation definition.

Notice that each element is defined similarly to a method definition in an interface. It has a data type and a name. You can use all primitive data types as element data types. You can also use arrays as data type. You cannot use complex objects as data type.

To use the above annotation, you could use code like this:

@MyAnnotation(
    value="123",
    name="Jakob",
    age=37,
    newNames={"Jenkov", "Peterson"}
)
public class MyClass {


}

Reference - http://tutorials.jenkov.com/java/annotations.html

How to check if a MySQL query using the legacy API was successful?

This is the first example in the manual page for mysql_query:

$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

If you wish to use something other than die, then I'd suggest trigger_error.

In Angular, What is 'pathmatch: full' and what effect does it have?

While technically correct, the other answers would benefit from an explanation of Angular's URL-to-route matching. I don't think you can fully (pardon the pun) understand what pathMatch: full does if you don't know how the router works in the first place.


Let's first define a few basic things. We'll use this URL as an example: /users/james/articles?from=134#section.

  1. It may be obvious but let's first point out that query parameters (?from=134) and fragments (#section) do not play any role in path matching. Only the base url (/users/james/articles) matters.

  2. Angular splits URLs into segments. The segments of /users/james/articles are, of course, users, james and articles.

  3. The router configuration is a tree structure with a single root node. Each Route object is a node, which may have children nodes, which may in turn have other children or be leaf nodes.

The goal of the router is to find a router configuration branch, starting at the root node, which would match exactly all (!!!) segments of the URL. This is crucial! If Angular does not find a route configuration branch which could match the whole URL - no more and no less - it will not render anything.

E.g. if your target URL is /a/b/c but the router is only able to match either /a/b or /a/b/c/d, then there is no match and the application will not render anything.

Finally, routes with redirectTo behave slightly differently than regular routes, and it seems to me that they would be the only place where anyone would really ever want to use pathMatch: full. But we will get to this later.

Default (prefix) path matching

The reasoning behind the name prefix is that such a route configuration will check if the configured path is a prefix of the remaining URL segments. However, the router is only able to match full segments, which makes this naming slightly confusing.

Anyway, let's say this is our root-level router configuration:

const routes: Routes = [
  {
    path: 'products',
    children: [
      {
        path: ':productID',
        component: ProductComponent,
      },
    ],
  },
  {
    path: ':other',
    children: [
      {
        path: 'tricks',
        component: TricksComponent,
      },
    ],
  },
  {
    path: 'user',
    component: UsersonComponent,
  },
  {
    path: 'users',
    children: [
      {
        path: 'permissions',
        component: UsersPermissionsComponent,
      },
      {
        path: ':userID',
        children: [
          {
            path: 'comments',
            component: UserCommentsComponent,
          },
          {
            path: 'articles',
            component: UserArticlesComponent,
          },
        ],
      },
    ],
  },
];

Note that every single Route object here uses the default matching strategy, which is prefix. This strategy means that the router iterates over the whole configuration tree and tries to match it against the target URL segment by segment until the URL is fully matched. Here's how it would be done for this example:

  1. Iterate over the root array looking for a an exact match for the first URL segment - users.
  2. 'products' !== 'users', so skip that branch. Note that we are using an equality check rather than a .startsWith() or .includes() - only full segment matches count!
  3. :other matches any value, so it's a match. However, the target URL is not yet fully matched (we still need to match james and articles), thus the router looks for children.
  • The only child of :other is tricks, which is !== 'james', hence not a match.
  1. Angular then retraces back to the root array and continues from there.
  2. 'user' !== 'users, skip branch.
  3. 'users' === 'users - the segment matches. However, this is not a full match yet, thus we need to look for children (same as in step 3).
  • 'permissions' !== 'james', skip it.
  • :userID matches anything, thus we have a match for the james segment. However this is still not a full match, thus we need to look for a child which would match articles.
    1. We can see that :userID has a child route articles, which gives us a full match! Thus the application renders UserArticlesComponent.

Full URL (full) matching

Example 1

Imagine now that the users route configuration object looked like this:

{
  path: 'users',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

Note the usage of pathMatch: full. If this were the case, steps 1-5 would be the same, however step 6 would be different:

  1. 'users' !== 'users/james/articles - the segment does not match because the path configuration users with pathMatch: full does not match the full URL, which is users/james/articles.
  2. Since there is no match, we are skipping this branch.
  3. At this point we reached the end of the router configuration without having found a match. The application renders nothing.

Example 2

What if we had this instead:

{
  path: 'users/:userID',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'comments',
      component: UserCommentsComponent,
    },
    {
      path: 'articles',
      component: UserArticlesComponent,
    },
  ],
}

users/:userID with pathMatch: full matches only users/james thus it's a no-match once again, and the application renders nothing.

Example 3

Let's consider this:

{
  path: 'users',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      pathMatch: 'full',
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

In this case:

  1. 'users' === 'users - the segment matches, but james/articles still remains unmatched. Let's look for children.
  • 'permissions' !== 'james' - skip.
  • :userID' can only match a single segment, which would be james. However, it's a pathMatch: full route, and it must match james/articles (the whole remaining URL). It's not able to do that and thus it's not a match (so we skip this branch)!
  1. Again, we failed to find any match for the URL and the application renders nothing.

As you may have noticed, a pathMatch: full configuration is basically saying this:

Ignore my children and only match me. If I am not able to match all of the remaining URL segments myself, then move on.

Redirects

Any Route which has defined a redirectTo will be matched against the target URL according to the same principles. The only difference here is that the redirect is applied as soon as a segment matches. This means that if a redirecting route is using the default prefix strategy, a partial match is enough to cause a redirect. Here's a good example:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];

For our initial URL (/users/james/articles), here's what would happen:

  1. 'not-found' !== 'users' - skip it.
  2. 'users' === 'users' - we have a match.
  3. This match has a redirectTo: 'not-found', which is applied immediately.
  4. The target URL changes to not-found.
  5. The router begins matching again and finds a match for not-found right away. The application renders NotFoundComponent.

Now consider what would happen if the users route also had pathMatch: full:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    pathMatch: 'full',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];
  1. 'not-found' !== 'users' - skip it.
  2. users would match the first segment of the URL, but the route configuration requires a full match, thus skip it.
  3. 'users/:userID' matches users/james. articles is still not matched but this route has children.
  • We find a match for articles in the children. The whole URL is now matched and the application renders UserArticlesComponent.

Empty path (path: '')

The empty path is a bit of a special case because it can match any segment without "consuming" it (so it's children would have to match that segment again). Consider this example:

const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'users',
        component: BadUsersComponent,
      }
    ]
  },
  {
    path: 'users',
    component: GoodUsersComponent,
  },
];

Let's say we are trying to access /users:

  • path: '' will always match, thus the route matches. However, the whole URL has not been matched - we still need to match users!
  • We can see that there is a child users, which matches the remaining (and only!) segment and we have a full match. The application renders BadUsersComponent.

Now back to the original question

The OP used this router configuration:

const routes: Routes = [
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
  {
    path: '',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
  {
    path: '**',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
];

If we are navigating to the root URL (/), here's how the router would resolve that:

  1. welcome does not match an empty segment, so skip it.
  2. path: '' matches the empty segment. It has a pathMatch: 'full', which is also satisfied as we have matched the whole URL (it had a single empty segment).
  3. A redirect to welcome happens and the application renders WelcomeComponent.

What if there was no pathMatch: 'full'?

Actually, one would expect the whole thing to behave exactly the same. However, Angular explicitly prevents such a configuration ({ path: '', redirectTo: 'welcome' }) because if you put this Route above welcome, it would theoretically create an endless loop of redirects. So Angular just throws an error, which is why the application would not work at all! (https://angular.io/api/router/Route#pathMatch)

Actually, this does not make too much sense to me because Angular also has implemented a protection against such endless redirects - it only runs a single redirect per routing level! This would stop all further redirects (as you'll see in the example below).

What about path: '**'?

path: '**' will match absolutely anything (af/frewf/321532152/fsa is a match) with or without a pathMatch: 'full'.

Also, since it matches everything, the root path is also included, which makes { path: '', redirectTo: 'welcome' } completely redundant in this setup.

Funnily enough, it is perfectly fine to have this configuration:

const routes: Routes = [
  {
    path: '**',
    redirectTo: 'welcome'
  },
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
];

If we navigate to /welcome, path: '**' will be a match and a redirect to welcome will happen. Theoretically this should kick off an endless loop of redirects but Angular stops that immediately (because of the protection I mentioned earlier) and the whole thing works just fine.

Undefined symbols for architecture arm64

detail Hope can help you. I add framework and the problem has been resolved

How to verify element present or visible in selenium 2 (Selenium WebDriver)

webDriver.findElement(By.xpath("//*[@id='element']")).isDisplayed();

Using getline() in C++

int main(){
.... example with file
     //input is a file
    if(input.is_open()){
        cin.ignore(1,'\n'); //it ignores everything after new line
        cin.getline(buffer,255); // save it in buffer
        input<<buffer; //save it in input(it's a file)
        input.close();
    }
}

What's your most controversial programming opinion?

Regurgitating well known sayings by programming greats out of context with the zeal of a fanatic and the misplaced assumption that they are ironclad rules really gets my goat. For example 'premature optimization is the root of all evil' as covered by this thread.

IMO, many technical problems and solutions are very context sensitive and the notion of global best practices is a fallacy.

Script for rebuilding and reindexing the fragmented index?

To rebuild use:

ALTER INDEX __NAME_OF_INDEX__ ON __NAME_OF_TABLE__ REBUILD

or to reorganize use:

ALTER INDEX __NAME_OF_INDEX__ ON __NAME_OF_TABLE__ REORGANIZE

Reorganizing should be used at lower (<30%) fragmentations but only rebuilding (which is heavier to the database) cuts the fragmentation down to 0%.
For further information see https://msdn.microsoft.com/en-us/library/ms189858.aspx

Using helpers in model: how do I include helper dependencies?

This works better for me:

Simple:

ApplicationController.helpers.my_helper_method

Advance:

class HelperProxy < ActionView::Base
  include ApplicationController.master_helper_module

  def current_user
    #let helpers act like we're a guest
    nil
  end       

  def self.instance
    @instance ||= new
  end
end

Source: http://makandracards.com/makandra/1307-how-to-use-helper-methods-inside-a-model

How to get the host name of the current machine as defined in the Ansible hosts file?

The necessary variable is inventory_hostname.

- name: Install this only for local dev machine
  pip: name=pyramid
  when: inventory_hostname == "local"

It is somewhat hidden in the documentation at the bottom of this section.

Does Spring @Transactional attribute work on a private method?

Spring Docs explain that

In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.

Consider the use of AspectJ mode (see mode attribute in table below) if you expect self-invocations to be wrapped with transactions as well. In this case, there will not be a proxy in the first place; instead, the target class will be weaved (that is, its byte code will be modified) in order to turn @Transactional into runtime behavior on any kind of method.

Another way is user BeanSelfAware

How to allow Cross domain request in apache2

First enable mod_headers on your server, then you can use header directive in both Apache conf and .htaccess.

  1. enable mod_headers
  • a2enmod headers
  1. configure header in .htaccess file
  • Header add Access-Control-Allow-Origin "*"
  • Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
  • Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

PHP function to build query string from array

Just as addition to @thatjuan's answer.
More compatible PHP4 version of this:

if (!function_exists('http_build_query')) {
    if (!defined('PHP_QUERY_RFC1738')) {
        define('PHP_QUERY_RFC1738', 1);
    }
    if (!defined('PHP_QUERY_RFC3986')) {
        define('PHP_QUERY_RFC3986', 2);
    }
    function http_build_query($query_data, $numeric_prefix = '', $arg_separator = '&', $enc_type = PHP_QUERY_RFC1738)
    {
        $data = array();
        foreach ($query_data as $key => $value) {
            if (is_numeric($key)) {
                $key = $numeric_prefix . $key;
            }
            if (is_scalar($value)) {
                $k = $enc_type == PHP_QUERY_RFC3986 ? urlencode($key) : rawurlencode($key);
                $v = $enc_type == PHP_QUERY_RFC3986 ? urlencode($value) : rawurlencode($value);
                $data[] = "$k=$v";
            } else {
                foreach ($value as $sub_k => $val) {
                    $k = "$key[$sub_k]";
                    $k = $enc_type == PHP_QUERY_RFC3986 ? urlencode($k) : rawurlencode($k);
                    $v = $enc_type == PHP_QUERY_RFC3986 ? urlencode($val) : rawurlencode($val);
                    $data[] = "$k=$v";
                }
            }
        }
        return implode($arg_separator, $data);
    }
}

Find the smallest positive integer that does not occur in a given sequence

Swift version using functions rather than an iterative approach

'The solution obtained perfect score' - Codility enter image description here

This solution uses functions rather than an iterative approach. So the solution relies heavily on the language's optimizations. A similar approach could be done in Java such as using Java's set operations and other functions.

public func solution(_ A : inout [Int]) -> Int {
    let positives = A.filter{ $0 > 0}
    let max = positives.count <= 100_000 ? positives.count + 1 : 100_001
    return Set(1...max).subtracting(A).min() ?? -1
}
  1. Obtained all positive numbers from the source array.
  2. Obtained all possible results based on the positive count. Limited the set to 100k as stated in the problem. Added 1 in case the source array was a complete sequence.
  3. Returned the minimum positive number after excluding the source array's elements from the set of all possible results.

Note: The function declaration was from Codility and inout was unneeded. Returning an integer did not allow for nil so -1 was used.

Open multiple Eclipse workspaces on the Mac

Based on a previous answer that helped me, but different directory:

cd /Applications/Eclipse.app/Contents/MacOS
./eclipse &

Thanks

Using VBA code, how to export Excel worksheets as image in Excel 2003?

Winand, Quality was also an issue for me so I did this:

For Each ws In ActiveWorkbook.Worksheets
    If ws.PageSetup.PrintArea <> "" Then
        'Reverse the effects of page zoom on the exported image
        zoom_coef = 100 / ws.Parent.Windows(1).Zoom
        areas = Split(ws.PageSetup.PrintArea, ",")
        areaNo = 0
        For Each a In areas
            Set area = ws.Range(a)
            ' Change xlPrinter to xlScreen to see zooming white space
            area.CopyPicture Appearance:=xlPrinter, Format:=xlPicture
            Set chartobj = ws.ChartObjects.Add(0, 0, area.Width * zoom_coef, area.Height * zoom_coef)
            chartobj.Chart.Paste
            'scale the image before export
            ws.Shapes(chartobj.Index).ScaleHeight 3, msoFalse, msoScaleFromTopLeft
            ws.Shapes(chartobj.Index).ScaleWidth 3, msoFalse, msoScaleFromTopLeft
            chartobj.Chart.Export ws.Name & "-" & areaNo & ".png", "png"
            chartobj.delete
            areaNo = areaNo + 1
        Next
    End If
Next

See here:https://robp30.wordpress.com/2012/01/11/improving-the-quality-of-excel-image-export/

Fastest way to remove first char in a String

I would just use

string data= "/temp string";
data = data.substring(1)

Output: temp string

That always works for me.

What event handler to use for ComboBox Item Selected (Selected Item not necessarily changed)

You can use "ComboBoxItem.PreviewMouseDown" event. So each time when mouse is down on some item this event will be fired.

To add this event in XAML use "ComboBox.ItemContainerStyle" like in next example:

   <ComboBox x:Name="MyBox"
        ItemsSource="{Binding MyList}"
        SelectedValue="{Binding MyItem, Mode=OneWayToSource}" >
        <ComboBox.ItemContainerStyle>
            <Style>
                <EventSetter Event="ComboBoxItem.PreviewMouseDown"
                    Handler="cmbItem_PreviewMouseDown"/>
            </Style>
        </ComboBox.ItemContainerStyle>
   </ComboBox>

and handle it as usual

void cmbItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    //...do your item selection code here...
}

Thanks to MSDN

How should I pass an int into stringWithFormat?

Do this:

label.text = [NSString stringWithFormat:@"%d", count];

How to perform OR condition in django queryset?

Both options are already mentioned in the existing answers:

from django.db.models import Q
q1 = User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))

and

q2 = User.objects.filter(income__gte=5000) | User.objects.filter(income__isnull=True)

However, there seems to be some confusion regarding which one is to prefer.

The point is that they are identical on the SQL level, so feel free to pick whichever you like!

The Django ORM Cookbook talks in some detail about this, here is the relevant part:


queryset = User.objects.filter(
        first_name__startswith='R'
    ) | User.objects.filter(
    last_name__startswith='D'
)

leads to

In [5]: str(queryset.query)
Out[5]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
"auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
"auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
"auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'

and

qs = User.objects.filter(Q(first_name__startswith='R') | Q(last_name__startswith='D'))

leads to

In [9]: str(qs.query)
Out[9]: 'SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login",
 "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name",
  "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff",
  "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user"
  WHERE ("auth_user"."first_name"::text LIKE R% OR "auth_user"."last_name"::text LIKE D%)'

source: django-orm-cookbook


Append text with .bat

I am not proficient at batch scripting but I can tell you that REM stands for Remark. The append won't occur as it is essentially commented out.

http://technet.microsoft.com/en-us/library/bb490986.aspx

Also, the append operator redirects the output of a command to a file. In the snippet you posted it is not clear what output should be redirected.

Reset select2 value and show placeholder

I tried the above solutions but it didn't work for me.

This is kind of hack, where you do not have to trigger change.

$("select").select2('destroy').val("").select2();

or

$("select").each(function () { //added a each loop here
        $(this).select2('destroy').val("").select2();
});

Possible reasons for timeout when trying to access EC2 instance

If SSH access doesn't work for your EC2 instance, you need to check:

  • Security Group for your instance is allowing Inbound SSH access (check: view rules).

If you're using VPC instance (you've VPC ID and Subnet ID attached to your instance), check:

  1. In VPC Dashboard, find used Subnet ID which is attached to your VPC.
  2. Check its attached Route table which should have 0.0.0.0/0 as Destination and your Internet Gateway as Target.

On Linux, you may also check route info in System Log in Networking of the instance, e.g.:

++++++++++++++++++++++++++++++++++++++Net device info+++++++++++++++++++++++++++++++++++++++
+--------+------+------------------------------+---------------+-------+-------------------+
| Device |  Up  |           Address            |      Mask     | Scope |     Hw-Address    |
+--------+------+------------------------------+---------------+-------+-------------------+
|   lo   | True |          127.0.0.1           |   255.0.0.0   |   .   |         .         |
|  eth0  | True |         172.30.2.226         | 255.255.255.0 |   .   | 0a:70:f3:2f:82:23 |
+--------+------+------------------------------+---------------+-------+-------------------+
++++++++++++++++++++++++++++Route IPv4 info+++++++++++++++++++++++++++++
+-------+-------------+------------+---------------+-----------+-------+
| Route | Destination |  Gateway   |    Genmask    | Interface | Flags |
+-------+-------------+------------+---------------+-----------+-------+
|   0   |   0.0.0.0   | 172.30.2.1 |    0.0.0.0    |    eth0   |   UG  |
|   1   |   10.0.3.0  |  0.0.0.0   | 255.255.255.0 |   lxcbr0  |   U   |
|   2   |  172.30.2.0 |  0.0.0.0   | 255.255.255.0 |    eth0   |   U   |
+-------+-------------+------------+---------------+-----------+-------+

where UG flags showing you your internet gateway.

For more details, check: Troubleshooting Connecting to Your Instance at Amazon docs.

How to change package name in android studio?

First click once on your package and then click setting icon on Android Studio.

Close/Unselect Compact Empty Middle Packages

Then, right click your package and rename it.

Thats all.

enter image description here

Roblox Admin Command Script

for i=1,#target do
    game.Players.target[i].Character:BreakJoints()
end

Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:

game.Players.target.1.Character:BreakJoints()

Which is completely incorrect.


c = game.Players:GetChildren()

Never use "Players:GetChildren()", it is not guaranteed to return only players.

Instead use:

c = Game.Players:GetPlayers()

if msg:lower()=="me" then
    table.insert(people, source)
    return people

Here you add the player's name in the list "people", where you in the other places adds the player object.


Fixed code:

local Admins = {"FakeNameHereSoNoStalkers"}

function Kill(Players)
    for i,Player in ipairs(Players) do
        if Player.Character then
            Player.Character:BreakJoints()
        end
    end
end

function IsAdmin(Player)
    for i,AdminName in ipairs(Admins) do
        if Player.Name:lower() == AdminName:lower() then return true end
    end
    return false
end

function GetPlayers(Player,Msg)
    local Targets = {}
    local Players = Game.Players:GetPlayers()

    if Msg:lower() == "me" then
        Targets = { Player }
    elseif Msg:lower() == "all" then
        Targets = Players
    elseif Msg:lower() == "others" then
        for i,Plr in ipairs(Players) do
            if Plr ~= Player then
                table.insert(Targets,Plr)
            end
        end
    else
        for i,Plr in ipairs(Players) do
            if Plr.Name:lower():sub(1,Msg:len()) == Msg then
                table.insert(Targets,Plr)
            end
        end
    end
    return Targets
end

Game.Players.PlayerAdded:connect(function(Player)
    if IsAdmin(Player) then
        Player.Chatted:connect(function(Msg)
            if Msg:lower():sub(1,6) == ":kill " then
                Kill(GetPlayers(Player,Msg:sub(7)))
            end
        end)
    end
end)

To show only file name without the entire directory path

When you want to list names in a path but they have different file extensions.

me@server:/var/backups$ ls -1 *.zip && ls -1 *.gz

Python 3.2 Unable to import urllib2 (ImportError: No module named urllib2)

    import urllib2

Traceback (most recent call last):

File "", line 1, in

    import urllib2

ImportError: No module named 'urllib2' So urllib2 has been been replaced by the package : urllib.request.

Here is the PEP link (Python Enhancement Proposals )

http://www.python.org/dev/peps/pep-3108/#urllib-package

so instead of urllib2 you can now import urllib.request and then use it like this:

    >>>import urllib.request

    >>>urllib.request.urlopen('http://www.placementyogi.com')

Original Link : http://placementyogi.com/articles/python/importerror-no-module-named-urllib2-in-python-3-x

How to round the minute of a datetime object

def get_rounded_datetime(self, dt, freq, nearest_type='inf'):

    if freq.lower() == '1h':
        round_to = 3600
    elif freq.lower() == '3h':
        round_to = 3 * 3600
    elif freq.lower() == '6h':
        round_to = 6 * 3600
    else:
        raise NotImplementedError("Freq %s is not handled yet" % freq)

    # // is a floor division, not a comment on following line:
    seconds_from_midnight = dt.hour * 3600 + dt.minute * 60 + dt.second
    if nearest_type == 'inf':
        rounded_sec = int(seconds_from_midnight / round_to) * round_to
    elif nearest_type == 'sup':
        rounded_sec = (int(seconds_from_midnight / round_to) + 1) * round_to
    else:
        raise IllegalArgumentException("nearest_type should be  'inf' or 'sup'")

    dt_midnight = datetime.datetime(dt.year, dt.month, dt.day)

    return dt_midnight + datetime.timedelta(0, rounded_sec)

Reliable way for a Bash script to get the full path to itself

If we use Bash I believe this is the most convenient way as it doesn't require calls to any external commands:

THIS_PATH="${BASH_SOURCE[0]}";
THIS_DIR=$(dirname $THIS_PATH)

how to open Jupyter notebook in chrome on windows

For windows set the default browser to open html files to Chrome. Configuration > Default Apps > Default Apps by File Type. Worked for me.

List all of the possible goals in Maven 2?

Strange nobody listed an actual command to do it:

mvn help:describe -e -Dplugin=site

If you want to list all goals of the site plugin. Output:

Name: Apache Maven Site Plugin Description: The Maven Site Plugin is a plugin that generates a site for the current project. Group Id: org.apache.maven.plugins Artifact Id: maven-site-plugin Version: 3.7.1 Goal Prefix: site

This plugin has 9 goals:

site:attach-descriptor Description: Adds the site descriptor (site.xml) to the list of files to be installed/deployed. For Maven-2.x this is enabled by default only when the project has pom packaging since it will be used by modules inheriting, but this can be enabled for other projects packaging if needed. This default execution has been removed from the built-in lifecycle of Maven 3.x for pom-projects. Users that actually use those projects to provide a common site descriptor for sub modules will need to explicitly define this goal execution to restore the intended behavior.

site:deploy Description: Deploys the generated site using wagon supported protocols to the site URL specified in the section of the POM. For scp protocol, the website files are packaged by wagon into zip archive, then the archive is transfered to the remote host, next it is un-archived which is much faster than making a file by file copy.

site:effective-site Description: Displays the effective site descriptor as an XML for this build, after inheritance and interpolation of site.xml, for the first locale.

site:help Description: Display help information on maven-site-plugin. Call mvn site:help -Ddetail=true -Dgoal= to display parameter details.

site:jar Description: Bundles the site output into a JAR so that it can be deployed to a repository.

site:run Description: Starts the site up, rendering documents as requested for faster editing. It uses Jetty as the web server.

site:site Description: Generates the site for a single project. Note that links between module sites in a multi module build will not work, since local build directory structure doesn't match deployed site.

site:stage Description: Deploys the generated site to a local staging or mock directory based on the site URL specified in the section of the POM. It can be used to test that links between module sites in a multi-module build work.

This goal requires the site to already have been generated using the site goal, such as by calling mvn site.

site:stage-deploy Description: Deploys the generated site to a staging or mock URL to the site URL specified in the section of the POM, using wagon supported protocols

For more information, run 'mvn help:describe [...] -Ddetail'

More details on https://mkyong.com/maven/how-to-display-maven-plugin-goals-and-parameters/

How can I toggle word wrap in Visual Studio?

In Visual Studio 2008, CTRL+E+W.

Stateless vs Stateful

I had the same doubt about stateful v/s stateless class design and did some research. Just completed and my findings has been posted in my blog

  • Entity classes needs to be stateful
  • The helper / worker classes should not be stateful.

How line ending conversions work with git core.autocrlf between different operating systems

core.autocrlf value does not depend on OS type but on Windows default value is true and for Linux - input. I explored 3 possible values for commit and checkout cases and this is the resulting table:

+------------------------------------------------------------+
¦ core.autocrlf ¦     false    ¦     input    ¦     true     ¦
¦---------------+--------------+--------------+--------------¦
¦               ¦ LF   => LF   ¦ LF   => LF   ¦ LF   => LF   ¦
¦ git commit    ¦ CR   => CR   ¦ CR   => CR   ¦ CR   => CR   ¦
¦               ¦ CRLF => CRLF ¦ CRLF => LF   ¦ CRLF => LF   ¦
¦---------------+--------------+--------------+--------------¦
¦               ¦ LF   => LF   ¦ LF   => LF   ¦ LF   => CRLF ¦
¦ git checkout  ¦ CR   => CR   ¦ CR   => CR   ¦ CR   => CR   ¦
¦               ¦ CRLF => CRLF ¦ CRLF => CRLF ¦ CRLF => CRLF ¦
+------------------------------------------------------------+

Maven: How to change path to target directory from command line?

You should use profiles.

<profiles>
    <profile>
        <id>otherOutputDir</id>
        <build>
            <directory>yourDirectory</directory>
        </build>
    </profile>
</profiles>

And start maven with your profile

mvn compile -PotherOutputDir

If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :

<properties>
    <buildDirectory>${project.basedir}/target</buildDirectory>
</properties>

<build>
    <directory>${buildDirectory}</directory>
</build>

And compile like this :

mvn compile -DbuildDirectory=test

That's because you can't change the target directory by using -Dproject.build.directory

HTML5 Audio stop function

I was having same issue. A stop should stop the stream and onplay go to live if it is a radio. All solutions I saw had a disadvantage:

  • player.currentTime = 0 keeps downloading the stream.
  • player.src = '' raise error event

My solution:

var player = document.getElementById('radio');
player.pause();
player.src = player.src;

And the HTML

<audio src="http://radio-stream" id="radio" class="hidden" preload="none"></audio>

Download JSON object as a file from browser

I recently had to create a button that would download a json file of all values of a large form. I needed this to work with IE/Edge/Chrome. This is what I did:

function download(text, name, type)
    {
        var file = new Blob([text], {type: type});
        var isIE = /*@cc_on!@*/false || !!document.documentMode;
        if (isIE)
        {
            window.navigator.msSaveOrOpenBlob(file, name);
        }
        else
        {
            var a = document.createElement('a');
            a.href = URL.createObjectURL(file);
            a.download = name;
            a.click();
        }
     }

download(jsonData, 'Form_Data_.json','application/json');

There was one issue with filename and extension in edge but at the time of writing this seemed to be a bug with Edge that is due to be fixed.

Hope this helps someone

java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused

Since you have not specified you are connected to a server from the device or emulator so I guess you are using your application in the emulator.

If you are referring your localhost on your system from the Android emulator then you have to use http://10.0.2.2:8080/ Because Android emulator runs in a Virtual Machine therefore here 127.0.0.1 or localhost will be emulator's own loopback address.

Refer: Emulator Networking

android - save image into gallery

Actually, you can save you picture at any place. If you want to save in a public space, so any other application can access, use this code:

storageDir = new File(
    Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES
    ), 
    getAlbumName()
);

The picture doesn't go to the album. To do this, you need to call a scan:

private void galleryAddPic() {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(mCurrentPhotoPath);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    this.sendBroadcast(mediaScanIntent);
}

You can found more info at https://developer.android.com/training/camera/photobasics.html#TaskGallery

Change the background color in a twitter bootstrap modal?

If you want to change the background color of the backdrop for a specific modal, you can access the backdrop element in this way:

$('#myModal').data('bs.modal').$backdrop

Then you can change any css property via .css jquery function. In particular, with background:

$('#myModal').data('bs.modal').$backdrop.css('background-color','orange')

Note that $('#myModal') has to be initialized, otherwise $backdrop is going to be null. Same applies to bs.modal data element.

Insert Multiple Rows Into Temp Table With SQL Server 2012

When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:

SQL Fiddle

MS SQL Server 2012 Schema Setup:

Query 1:

CREATE TABLE #Names
  ( 
    Name1 VARCHAR(100),
    Name2 VARCHAR(100)
  ) 

INSERT INTO #Names
  (Name1, Name2)
VALUES
  ('Matt', 'Matthew'),
  ('Matt', 'Marshal'),
  ('Matt', 'Mattison')

SELECT * FROM #NAMES

Results:

| NAME1 |    NAME2 |
--------------------
|  Matt |  Matthew |
|  Matt |  Marshal |
|  Matt | Mattison |

Here a SSMS 2012 screenshot: enter image description here

Scrollview vertical and horizontal in android

I found a better solution.

XML: (design.xml)

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent">
  <FrameLayout android:layout_width="90px" android:layout_height="90px">
    <RelativeLayout android:id="@+id/container" android:layout_width="fill_parent" android:layout_height="fill_parent">        
    </RelativeLayout>
</FrameLayout>
</FrameLayout>

Java Code:

public class Example extends Activity {
  private RelativeLayout container;
  private int currentX;
  private int currentY;

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.design);

    container = (RelativeLayout)findViewById(R.id.container);

    int top = 0;
    int left = 0;

    ImageView image1 = ...
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(left, top, 0, 0);               
    container.addView(image1, layoutParams);

    ImageView image2 = ...
    left+= 100;
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(left, top, 0, 0);               
    container.addView(image2, layoutParams);

    ImageView image3 = ...
    left= 0;
    top+= 100;
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(left, top, 0, 0);               
    container.addView(image3, layoutParams);

    ImageView image4 = ...
    left+= 100;     
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    layoutParams.setMargins(left, top, 0, 0);               
    container.addView(image4, layoutParams);
  }     

  @Override 
  public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN: {
            currentX = (int) event.getRawX();
            currentY = (int) event.getRawY();
            break;
        }

        case MotionEvent.ACTION_MOVE: {
            int x2 = (int) event.getRawX();
            int y2 = (int) event.getRawY();
            container.scrollBy(currentX - x2 , currentY - y2);
            currentX = x2;
            currentY = y2;
            break;
        }   
        case MotionEvent.ACTION_UP: {
            break;
        }
    }
      return true; 
  }
}

That's works!!!

If you want to load other layout or control, the structure is the same.

Run git pull over all subdirectories

Run the following from the parent directory, plugins in this case:

find . -type d -depth 1 -exec git --git-dir={}/.git --work-tree=$PWD/{} pull origin master \;

To clarify:

  • find . searches the current directory
  • -type d to find directories, not files
  • -depth 1 for a maximum depth of one sub-directory
  • -exec {} \; runs a custom command for every find
  • git --git-dir={}/.git --work-tree=$PWD/{} pull git pulls the individual directories

To play around with find, I recommend using echo after -exec to preview, e.g.:

find . -type d -depth 1 -exec echo git --git-dir={}/.git --work-tree=$PWD/{} status \;

Note: if the -depth 1 option is not available, try -mindepth 1 -maxdepth 1.

How to pass password to scp?

curl can be used as a alternative to scp to copy a file and it supports a password on the commandline.

curl --insecure --user username:password -T /path/to/sourcefile sftp://desthost/path/

How to make bootstrap column height to 100% row height?

You can solve that using display table.

Here is the updated JSFiddle that solves your problem.

CSS

.body {
    display: table;
    background-color: green;
}

.left-side {
    background-color: blue;
    float: none;
    display: table-cell;
    border: 1px solid;
}

.right-side {
    background-color: red;
    float: none;
    display: table-cell;
    border: 1px solid;
}

HTML

<div class="row body">
        <div class="col-xs-9 left-side">
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
        </div>
        <div class="col-xs-3 right-side">
            asdfdf
        </div>
    </div>

Deserialize a json string to an object in python

While Alex's answer points us to a good technique, the implementation that he gave runs into a problem when we have nested objects.

class more_info
    string status

class payload
    string action
    string method
    string data
    class more_info

with the below code:

def as_more_info(dct):
    return MoreInfo(dct['status'])

def as_payload(dct):
    return Payload(dct['action'], dct['method'], dct['data'], as_more_info(dct['more_info']))

payload = json.loads(message, object_hook = as_payload)

payload.more_info will also be treated as an instance of payload which will lead to parsing errors.

From the official docs:

object_hook is an optional function that will be called with the result of any object literal decoded (a dict). The return value of object_hook will be used instead of the dict.

Hence, I would prefer to propose the following solution instead:

class MoreInfo(object):
    def __init__(self, status):
        self.status = status

    @staticmethod
    def fromJson(mapping):
        if mapping is None:
            return None

        return MoreInfo(
            mapping.get('status')
        )

class Payload(object):
    def __init__(self, action, method, data, more_info):
        self.action = action
        self.method = method
        self.data = data
        self.more_info = more_info

    @staticmethod
    def fromJson(mapping):
        if mapping is None:
            return None

        return Payload(
            mapping.get('action'),
            mapping.get('method'),
            mapping.get('data'),
            MoreInfo.fromJson(mapping.get('more_info'))
        )

import json
def toJson(obj, **kwargs):
    return json.dumps(obj, default=lambda j: j.__dict__, **kwargs)

def fromJson(msg, cls, **kwargs):
    return cls.fromJson(json.loads(msg, **kwargs))

info = MoreInfo('ok')
payload = Payload('print', 'onData', 'better_solution', info)
pl_json = toJson(payload)
l1 = fromJson(pl_json, Payload)

PostgreSQL delete all content

For small tables DELETE is often faster and needs less aggressive locking (for heavy concurrent load):

DELETE FROM tbl;

With no WHERE condition.

For medium or bigger tables, go with TRUNCATE tbl, like @Greg posted.

Locking a file in Python

Locking a file is usually a platform-specific operation, so you may need to allow for the possibility of running on different operating systems. For example:

import os

def my_lock(f):
    if os.name == "posix":
        # Unix or OS X specific locking here
    elif os.name == "nt":
        # Windows specific locking here
    else:
        print "Unknown operating system, lock unavailable"

Loop code for each file in a directory

Use the glob function in a foreach loop to do whatever is an option. I also used the file_exists function in the example below to check if the directory exists before going any further.

$directory = 'my_directory/';
$extension = '.txt';

if ( file_exists($directory) ) {
   foreach ( glob($directory . '*' . $extension) as $file ) {
      echo $file;
   }
}
else {
   echo 'directory ' . $directory . ' doesn\'t exist!';
}

What's the most efficient way to check if a record exists in Oracle?

What is the underlying logic you want to implement? If, for instance, you want to test for the existence of a record to determine to insert or update then a better choice would be to use MERGE instead.

If you expect the record to exist most of the time, this is probably the most efficient way of doing things (although the CASE WHEN EXISTS solution is likely to be just as efficient):

begin
    select null into dummy
    from sales
    where sales_type = 'Accessories'
    and rownum = 1;

    --  do things here when record exists
    ....        

exception
    when no_data_found then
        -- do things here when record doesn't exists
        .....
end;

You only need the ROWNUM line if SALES_TYPE is not unique. There's no point in doing a count when all you want to know is whether at least one record exists.

html - table row like a link

When i want simulate a <tr> with a link but respecting the html standards, I do this.

HTML:

<table>
    <tr class="trLink">
        <td>
            <a href="#">Something</a>
        </td>
    </tr>
</table>

CSS:

tr.trLink {
    cursor: pointer;
}
tr.trLink:hover {
   /*TR-HOVER-STYLES*/
}

tr.trLink a{
    display: block;
    height: 100%;
    width: 100%;
}
tr.trLink:hover a{
   /*LINK-HOVER-STYLES*/
}

In this way, when someone go with his mouse on a TR, all the row (and this links) gets the hover style and he can't see that there are multiple links.

Hope can help someone.

Fiddle HERE

Example using Hyperlink in WPF

One of the most beautiful ways in my opinion (since it is now commonly available) is using behaviours.

It requires:

  • nuget dependency: Microsoft.Xaml.Behaviors.Wpf
  • if you already have behaviours built in you might have to follow this guide on Microsofts blog.

xaml code:

xmlns:Interactions="http://schemas.microsoft.com/xaml/behaviors"

AND

<Hyperlink NavigateUri="{Binding Path=Link}">
    <Interactions:Interaction.Behaviors>
        <behaviours:HyperlinkOpenBehaviour ConfirmNavigation="True"/>
    </Interactions:Interaction.Behaviors>
    <Hyperlink.Inlines>
        <Run Text="{Binding Path=Link}"/>
    </Hyperlink.Inlines>
</Hyperlink>

behaviour code:

using System.Windows;
using System.Windows.Documents;
using System.Windows.Navigation;
using Microsoft.Xaml.Behaviors;

namespace YourNameSpace
{
    public class HyperlinkOpenBehaviour : Behavior<Hyperlink>
    {
        public static readonly DependencyProperty ConfirmNavigationProperty = DependencyProperty.Register(
            nameof(ConfirmNavigation), typeof(bool), typeof(HyperlinkOpenBehaviour), new PropertyMetadata(default(bool)));

        public bool ConfirmNavigation
        {
            get { return (bool) GetValue(ConfirmNavigationProperty); }
            set { SetValue(ConfirmNavigationProperty, value); }
        }

        /// <inheritdoc />
        protected override void OnAttached()
        {
            this.AssociatedObject.RequestNavigate += NavigationRequested;
            this.AssociatedObject.Unloaded += AssociatedObjectOnUnloaded;
            base.OnAttached();
        }

        private void AssociatedObjectOnUnloaded(object sender, RoutedEventArgs e)
        {
            this.AssociatedObject.Unloaded -= AssociatedObjectOnUnloaded;
            this.AssociatedObject.RequestNavigate -= NavigationRequested;
        }

        private void NavigationRequested(object sender, RequestNavigateEventArgs e)
        {
            if (!ConfirmNavigation || MessageBox.Show("Are you sure?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                OpenUrl();
            }

            e.Handled = true;
        }

        private void OpenUrl()
        {
//          Process.Start(new ProcessStartInfo(AssociatedObject.NavigateUri.AbsoluteUri));
            MessageBox.Show($"Opening {AssociatedObject.NavigateUri}");
        }

        /// <inheritdoc />
        protected override void OnDetaching()
        {
            this.AssociatedObject.RequestNavigate -= NavigationRequested;
            base.OnDetaching();
        }
    }
}

Align inline-block DIVs to top of container element

<style type="text/css">
        div {
  text-align: center;
         }

         .img1{
            width: 150px;
            height: 150px;
            border-radius: 50%;
         }

         span{
            display: block;
         }
    </style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type='password' class='secondInput mt-4 mr-1' placeholder="Password">
  <span class='dif'></span>
  <br>
  <button>ADD</button>
</div>

<script type="text/javascript">

$('button').click(function() {
  $('.dif').html("<img/>");

})

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

This is probably one of the fastest way to remove permanently the duplicates from an array 10x times faster than the most functions here.& 78x faster in safari

function toUnique(a,b,c){//array,placeholder,placeholder
 b=a.length;
 while(c=--b)while(c--)a[b]!==a[c]||a.splice(c,1)
}
var array=[1,2,3,4,5,6,7,8,9,0,1,2,1];
toUnique(array);
console.log(array);
  1. Test: http://jsperf.com/wgu
  2. Demo: http://jsfiddle.net/46S7g/
  3. More: https://stackoverflow.com/a/25082874/2450730

if you can't read the code above ask, read a javascript book or here are some explainations about shorter code. https://stackoverflow.com/a/21353032/2450730

EDIT As stated in the comments this function does return an array with uniques, the question however asks to find the duplicates. in that case a simple modification to this function allows to push the duplicates into an array, then using the previous function toUnique removes the duplicates of the duplicates.

function theDuplicates(a,b,c,d){//array,placeholder,placeholder
 b=a.length,d=[];
 while(c=--b)while(c--)a[b]!==a[c]||d.push(a.splice(c,1))
}
var array=[1,2,3,4,5,6,7,8,9,0,1,2,1];

toUnique(theDuplicates(array));

Concat scripts in order with Gulp

I just use gulp-angular-filesort

function concatOrder() {

    return gulp.src('./build/src/app/**/*.js')
        .pipe(sort())
        .pipe(plug.concat('concat.js'))
        .pipe(gulp.dest('./output/'));
}

Extract / Identify Tables from PDF python

I'd just like to add to the very helpful answer from Kurt Pfeifle - there is now a Python wrapper for Tabula, and this seems to work very well so far: https://github.com/chezou/tabula-py

This will convert your PDF table to a Pandas data frame. You can also set the area in x,y co-ordinates which is obviously very handy for irregular data.

Jenkins - how to build a specific branch

I can see many good answers to the question, but I still would like to share this method, by using Git parameter as follows:

Add Git parameter

When building the pipeline you will be asked to choose the branch: Choose branch to build

After that through the groovy code you could specify the branch you want to clone:

git branch:BRANCH[7..-1], url: 'https://github.com/YourName/YourRepo.git' , credentialsId: 'github' 

Note that I'm using a slice from 7 to the last character to shrink "origin/" and get the branch name.

Also in case you configured a webhooks trigger it still work and it will take the default branch you specified(master in our case).

How to go to a specific element on page?

document.getElementById("elementID").scrollIntoView();

Same thing, but wrapping it in a function:

function scrollIntoView(eleID) {
   var e = document.getElementById(eleID);
   if (!!e && e.scrollIntoView) {
       e.scrollIntoView();
   }
}

This even works in an IFrame on an iPhone.

Example of using getElementById: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_document_getelementbyid

How to find whether or not a variable is empty in Bash?

Presuming Bash:

var=""

if [ -n "$var" ]; then
    echo "not empty"
else
    echo "empty"
fi

.attr('checked','checked') does not work

Why not try IS?

$('selector').is(':checked') /* result true or false */

Look a FAQ: jQuery .is() enjoin us ;-)

How to unload a package without restarting R

Note also that you can only use unload() once. If you use it a second time without rerunning library(), y'll get the not very informative error message invalid 'name' argument:

library(vegan)
#> Loading required package: permute
#> Loading required package: lattice
#> This is vegan 2.5-6
detach("package:vegan",  unload=TRUE)
detach("package:vegan",  unload=TRUE)
#> Error in detach("package:vegan", unload = TRUE): invalid 'name' argument

Created on 2020-05-09 by the reprex package (v0.3.0)

check if file exists in php

for me also the file_exists() function is not working properly. So I got this alternative solution. Hope this one help someone

$path = 'http://localhost/admin/public/upload/video_thumbnail/thumbnail_1564385519_0.png';

    if (@GetImageSize($path)) {
        echo 'File exits';
    } else {
        echo "File doesn't exits";
    }

How to get the number of columns in a matrix?

When want to get row size with size() function, below code can be used:

size(A,1)

Another usage for it:

[height, width] = size(A)

So, you can get 2 dimension of your matrix.

ImageView in android XML layout with layout_height="wrap_content" has padding top & bottom

I had a simular issue and resolved it using android:adjustViewBounds="true" on the ImageView.

<ImageView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@string/banner_alt"
    android:src="@drawable/banner_portrait" />

How can I add a volume to an existing Docker container?

Unfortunately the switch option to mount a volume is only found in the run command.

docker run --help

-v, --volume list Bind mount a volume (default [])

There is a way you can work around this though so you won't have to reinstall the applications you've already set up on your container.

  1. Export your container docker container export -o ./myimage.docker mycontainer
  2. Import as an image docker import ./myimage.docker myimage
  3. Then docker run -i -t -v /somedir --name mycontainer myimage /bin/bash

How to include clean target in Makefile?

By the way it is written, clean rule is invoked only if it is explicitly called:

make clean

I think it is better, than make clean every time. If you want to do this by your way, try this:

CXX = g++ -O2 -Wall

all: clean code1 code2

code1: code1.cc utilities.cc
   $(CXX) $^ -o $@

code2: code2.cc utilities.cc
   $(CXX) $^ -o $@

clean: 
    rm ...
    echo Clean done

How to unstage large number of files without deleting the content

If you have a pristine repo (or HEAD isn't set)[1] you could simply

rm .git/index

Of course, this will require you to re-add the files that you did want to be added.


[1] Note (as explained in the comments) this would usually only happen when the repo is brand-new ("pristine") or if no commits have been made. More technically, whenever there is no checkout or work-tree.

Just making it more clear :)

How to concatenate variables into SQL strings

You could make use of Prepared Stements like this.

set @query = concat( "select name from " );
set @query = concat( "table_name"," [where condition] " );

prepare stmt from @like_q;
execute stmt;

How to iterate through table in Lua?

For those wondering why ipairs doesn't print all the values of the table all the time, here's why (I would comment this, but I don't have enough good boy points).

The function ipairs only works on tables which have an element with the key 1. If there is an element with the key 1, ipairs will try to go as far as it can in a sequential order, 1 -> 2 -> 3 -> 4 etc until it cant find an element with a key that is the next in the sequence. The order of the elements does not matter.

Tables that do not meet those requirements will not work with ipairs, use pairs instead.

Examples:

ipairsCompatable = {"AAA", "BBB", "CCC"}
ipairsCompatable2 = {[1] = "DDD", [2] = "EEE", [3] = "FFF"}
ipairsCompatable3 = {[3] = "work", [2] = "does", [1] = "this"}

notIpairsCompatable = {[2] = "this", [3] = "does", [4] = "not"}
notIpairsCompatable2 = {[2] = "this", [5] = "doesn't", [24] = "either"}

ipairs will go as far as it can with it's iterations but won't iterate over any other element in the table.

kindofIpairsCompatable = {[2] = 2, ["cool"] = "bro", [1] = 1, [3] = 3, [5] = 5 }

When printing these tables, these are the outputs. I've also included pairs outputs for comparison.

ipairs + ipairsCompatable
1       AAA
2       BBB
3       CCC

ipairs + ipairsCompatable2
1       DDD
2       EEE
3       FFF

ipairs + ipairsCompatable3
1       this
2       does
3       work

ipairs + notIpairsCompatable

pairs + notIpairsCompatable
2       this
3       does
4       not

ipairs + notIpairsCompatable2

pairs + notIpairsCompatable2
2       this
5       doesnt
24      either

ipairs + kindofIpairsCompatable
1       1
2       2
3       3

pairs + kindofIpairsCompatable
1       1
2       2
3       3
5       5
cool    bro

"You may need an appropriate loader to handle this file type" with Webpack and Babel

Make sure you have the es2015 babel preset installed.

An example package.json devDependencies is:

"devDependencies": {
  "babel-core": "^6.0.20",
  "babel-loader": "^6.0.1",
  "babel-preset-es2015": "^6.0.15",
  "babel-preset-react": "^6.0.15",
  "babel-preset-stage-0": "^6.0.15",
  "webpack": "^1.9.6",
  "webpack-dev-middleware": "^1.2.0",
  "webpack-hot-middleware": "^2.0.0"
},

Now configure babel-loader in your webpack config:

{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }

add a .babelrc file to the root of your project where the node modules are:

{
  "presets": ["es2015", "stage-0", "react"]
}

More info:

The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files

Workaround:

Window -> Preferences -> Java -> Installed JREs, select a different JRE

maybe this JDK edition is not suitable:

enter image description here


So try this one instead:

enter image description here

Problem solved!

How to get all keys with their values in redis

I refined the bash solution a bit, so that the more efficient scan is used instead of keys, and printing out array and hash values is supported. My solution also prints out the key name.

redis_print.sh:

#!/bin/bash

# Default to '*' key pattern, meaning all redis keys in the namespace
REDIS_KEY_PATTERN="${REDIS_KEY_PATTERN:-*}"
for key in $(redis-cli --scan --pattern "$REDIS_KEY_PATTERN")
do
    type=$(redis-cli type $key)
    if [ $type = "list" ]
    then
        printf "$key => \n$(redis-cli lrange $key 0 -1 | sed 's/^/  /')\n"
    elif [ $type = "hash" ]
    then
        printf "$key => \n$(redis-cli hgetall $key | sed 's/^/  /')\n"
    else
        printf "$key => $(redis-cli get $key)\n"
    fi
done

Note: you can formulate a one-liner of this script by removing the first line of redis_print.sh and commanding: cat redis_print.sh | tr '\n' ';' | awk '$1=$1'

Delete empty lines using sed

sed '/^$/d' should be fine, are you expecting to modify the file in place? If so you should use the -i flag.

Maybe those lines are not empty, so if that's the case, look at this question Remove empty lines from txtfiles, remove spaces from start and end of line I believe that's what you're trying to achieve.

How can I show figures separately in matplotlib?

None of the above solutions seems to work in my case, with matplotlib 3.1.0 and Python 3.7.3. Either both the figures show up on calling show() or none show up in different answers posted above.

Building upon @Ivan's answer, and taking hint from here, the following seemed to work well for me:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(1) # Creates figure fig and add an axes, ax.
fig2, ax2 = plt.subplots(1) # Another figure

ax.plot(range(20)) #Add a straight line to the axes of the first figure.
ax2.plot(range(100)) #Add a straight line to the axes of the first figure.

# plt.close(fig) # For not showing fig
plt.close(fig2) # For not showing fig2
plt.show()

How can I remove all text after a character in bash?

Let's say you have a path with a file in this format:

/dirA/dirB/dirC/filename.file

Now you only want the path which includes four "/". Type

$ echo "/dirA/dirB/dirC/filename.file" | cut -f1-4 -d"/"

and your output will be

/dirA/dirB/dirC

The advantage of using cut is that you can also cut out the uppest directory as well as the file (in this example), so if you type

$ echo "/dirA/dirB/dirC/filename.file" | cut -f1-3 -d"/"

your output would be

/dirA/dirB

Though you can do the same from the other side of the string, it would not make that much sense in this case as typing

$ echo "/dirA/dirB/dirC/filename.file" | cut -f2-4 -d"/"

results in

dirA/dirB/dirC

In some other cases the last case might also be helpful. Mind that there is no "/" at the beginning of the last output.

Can I check if Bootstrap Modal Shown / Hidden?

its an old question but anyway heres something i used incase someone was looking for the same thing

if (!$('#myModal').is(':visible')) {
    // if modal is not shown/visible then do something
}

PHP, MySQL error: Column count doesn't match value count at row 1

The number of column parameters in your insert query is 9, but you've only provided 8 values.

INSERT INTO dbname (id, Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')

The query should omit the "id" parameter, because it is auto-generated (or should be anyway):

INSERT INTO dbname (Name, Description, shortDescription, Ingredients, Method, Length, dateAdded, Username) VALUES ('', '%s', '%s', '%s', '%s', '%s', '%s', '%s')

How to change the blue highlight color of a UITableViewCell?

I have to set the selection style to UITableViewCellSelectionStyleDefault for custom background color to work. If any other style, the custom background color will be ignored. Tested on iOS 8.

The full code for the cell as follows:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"MyCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // This is how you change the background color
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    UIView *bgColorView = [[UIView alloc] init];
    bgColorView.backgroundColor = [UIColor redColor];
    [cell setSelectedBackgroundView:bgColorView];

    return cell;
}

jQuery.getJSON - Access-Control-Allow-Origin Issue

It's simple, use $.getJSON() function and in your URL just include

callback=?

as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

Also worth noting, for people who find this in their searches, is this...

<div ng-repeat="button in buttons" class="bb-button" ng-click="goTo(button.path)">
  <div class="bb-button-label">{{ button.label }}</div>
  <div class="bb-button-description">{{ button.description }}</div>
</div>

Note the value of ng-click. The parameter passed to goTo() is a string from a property of the binding object (the button), but it is not wrapped in quotes. Looks like AngularJS handles that for us. I got hung up on that for a few minutes.

How to hide a status bar in iOS?

I had the same problem, but its an easy fix! Just set

status bar is initially hidden = YES

then add an row by clicking on the plus right after the text status bar is initially hidden, then set the text to

view controller-based status bar appearance

by clicking the arrows, and set it to NO

Hope this helps!

Copy files from one directory into an existing directory

If you want to copy something from one directory into the current directory, do this:

cp dir1/* .

This assumes you're not trying to copy hidden files.

How to get the public IP address of a user in C#

In MVC IP can be obtained by the following Code

string ipAddress = Request.ServerVariables["REMOTE_ADDR"];

Get paragraph text inside an element

Use jQuery:

$("li").find("p").html()

should work.

How to validate date with format "mm/dd/yyyy" in JavaScript?

function fdate_validate(vi)
{
  var parts =vi.split('/');
  var result;
  var mydate = new Date(parts[2],parts[1]-1,parts[0]);
  if (parts[2] == mydate.getYear() && parts[1]-1 == mydate.getMonth() && parts[0] == mydate.getDate() )
  {result=0;}
  else
  {result=1;}
  return(result);
}

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

Get source JARs from Maven repository

you can find info in this related question: Get source jar files attached to Eclipse for Maven-managed dependencies
if you use the eclipse maven plugin then use 'mvn eclipse:eclipse -DdownloadSources=true'

Can I escape a double quote in a verbatim string literal?

There is a proposal open in GitHub for the C# language about having better support for raw string literals. One valid answer, is to encourage the C# team to add a new feature to the language (such as triple quote - like Python).

see https://github.com/dotnet/csharplang/discussions/89#discussioncomment-257343

Bootstrap modal link

Please remove . from your target it should be a id

<a href="#bannerformmodal" data-toggle="modal" data-target="#bannerformmodal">Load me</a>

Also you have to give your modal id like below

<div class="modal fade bannerformmodal" tabindex="-1" role="dialog" aria-labelledby="bannerformmodal" aria-hidden="true" id="bannerformmodal">

Here is the solution in a fiddle.

Android Studio 3.0 Execution failed for task: unable to merge dex

The easiest way to avoid suck kind of error is:

-Change library combilesdkversion as same as your app compilesdkversion

-Change library's supportLibrary version as same as your build.gradle(app)

How To change the column order of An Existing Table in SQL Server 2008

This can be an issue when using Source Control and automated deployments to a shared development environment. Where I work we have a very large sample DB on our development tier to work with (a subset of our production data).

Recently I did some work to remove one column from a table and then add some extra ones on the end. I then had to undo my column removal so I re-added it on the end which means the table and all references are correct in the environment but the Source Control automated deployment will no longer work because it complains about the table definition changing.

The real problem here is that the table + indexes are ~120GB and the environment only has ~60GB free so I'll need to either:

a) Rename the existing columns which are in the wrong order, add new columns in the right order, update the data then drop the old columns

OR

b) Rename the table, create a new table with the correct order, insert to the new table from the old and delete from the old as I go along

The SSMS/TFS Schema compare option of using a temp table won't work because there isn't enough room on disc to do it.

I'm not trying to say this is the best way to go about things or that column order really matters, just that I have a scenario where it is an issue and I'm sharing the options I've thought of to fix the issue

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

ArrayIndexOutOfBoundsException in simple words is -> you have 10 students in your class (int array size 10) and you want to view the value of the 11th student (a student who does not exist)

if you make this int i[3] then i takes values i[0] i[1] i[2]

for your problem try this code structure

double[] array = new double[50];

    for (int i = 0; i < 24; i++) {

    }

    for (int j = 25; j < 50; j++) {

    }

Remove duplicate rows in MySQL

I have a table which forget to add a primary key in the id row. Though is has auto_increment on the id. But one day, one stuff replay the mysql bin log on the database which insert some duplicate rows.

I remove the duplicate row by

  1. select the unique duplicate rows and export them

select T1.* from table_name T1 inner join (select count(*) as c,id from table_name group by id) T2 on T1.id = T2.id where T2.c > 1 group by T1.id;

  1. delete the duplicate rows by id

  2. insert the row from the exported data.

  3. Then add the primary key on id

How to trim a string after a specific character in java

How about

Scanner scanner = new Scanner(result);
String line = scanner.nextLine();//will contain 34.1 -118.33

Android java.exe finished with non-zero exit value 1

All you need to do is to kill some of the running process and free the space on your Memory(RAM). You can try closing some of the high memory consuming program. You can also try restarting the Android Studio. It worked for me.

Pass by Reference / Value in C++

When passing by value:

void func(Object o);

and then calling

func(a);

you will construct an Object on the stack, and within the implementation of func it will be referenced by o. This might still be a shallow copy (the internals of a and o might point to the same data), so a might be changed. However if o is a deep copy of a, then a will not change.

When passing by reference:

void func2(Object& o);

and then calling

func2(a);

you will only be giving a new way to reference a. "a" and "o" are two names for the same object. Changing o inside func2 will make those changes visible to the caller, who knows the object by the name "a".

Can I scroll a ScrollView programmatically in Android?

I had to create Interface

public interface ScrollViewListener {
    void onScrollChanged(ScrollViewExt scrollView, 
                         int x, int y, int oldx, int oldy);
}    

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;

public class CustomScrollView extends ScrollView {
    private ScrollViewListener scrollViewListener = null;
    public ScrollViewExt(Context context) {
        super(context);
    }

    public CustomScrollView (Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public CustomScrollView (Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setScrollViewListener(ScrollViewListener scrollViewListener) {
        this.scrollViewListener = scrollViewListener;
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if (scrollViewListener != null) {
            scrollViewListener.onScrollChanged(this, l, t, oldl, oldt);
        }
    }
}




<"Your Package name ".CustomScrollView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusableInTouchMode="true"
    android:scrollbars="vertical">

    private CustomScrollView scrollView;

scrollView = (CustomScrollView)mView.findViewById(R.id.scrollView);
        scrollView.setScrollViewListener(this);


    @Override
    public void onScrollChanged(ScrollViewExt scrollView, int x, int y, int oldx, int oldy) {
        // We take the last son in the scrollview
        View view = (View) scrollView.getChildAt(scrollView.getChildCount() - 1);
        int diff = (view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY()));

        // if diff is zero, then the bottom has been reached
        if (diff == 0) {
                // do stuff
            //TODO keshav gers
            pausePlayer();
            videoFullScreenPlayer.setVisibility(View.GONE);

        }
    }

How to show/hide if variable is null

To clarify, the above example does work, my code in the example did not work for unrelated reasons.

If myvar is false, null or has never been used before (i.e. $scope.myvar or $rootScope.myvar never called), the div will not show. Once any value has been assigned to it, the div will show, except if the value is specifically false.

The following will cause the div to show:

$scope.myvar = "Hello World";

or

$scope.myvar = true;

The following will hide the div:

$scope.myvar = null;

or

$scope.myvar = false;

How to have a a razor action link open in a new tab?

If your goal is to use the ActionLink helper and open a new tab:

@Html.ActionLink("New tab please", "Home", null , new { target = "_blank" })

@Html.ActionLink("New tab please", "Home", Nothing, New With {Key .target = "_blank"})

How to create strings containing double quotes in Excel formulas?

Three double quotes: " " " x " " " = "x" Excel will auto change to one double quote. e.g.:

=CONCATENATE("""x"""," hi")  

= "x" hi

Finding current executable's path without /proc/self/exe

The whereami library by Gregory Pakosz implements this for a variety of platforms, using the APIs mentioned in mark4o's post. This is most interesting if you "just" need a solution that works for a portable project and are not interested in the peculiarities of the various platforms.

At the time of writing, supported platforms are:

  • Windows
  • Linux
  • Mac
  • iOS
  • Android
  • QNX Neutrino
  • FreeBSD
  • NetBSD
  • DragonFly BSD
  • SunOS

The library consists of whereami.c and whereami.h and is licensed under MIT and WTFPL2. Drop the files into your project, include the header and use it:

#include "whereami.h"

int main() {
  int length = wai_getExecutablePath(NULL, 0, NULL);
  char* path = (char*)malloc(length + 1);
  wai_getExecutablePath(path, length, &dirname_length);
  path[length] = '\0';

  printf("My path: %s", path);

  free(path);
  return 0;
}

Getting the IP Address of a Remote Socket Endpoint

http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.remoteendpoint.aspx

You can then call the IPEndPoint..::.Address method to retrieve the remote IPAddress, and the IPEndPoint..::.Port method to retrieve the remote port number.

More from the link (fixed up alot heh):

Socket s;

IPEndPoint remoteIpEndPoint = s.RemoteEndPoint as IPEndPoint;
IPEndPoint localIpEndPoint = s.LocalEndPoint as IPEndPoint;

if (remoteIpEndPoint != null)
{
    // Using the RemoteEndPoint property.
    Console.WriteLine("I am connected to " + remoteIpEndPoint.Address + "on port number " + remoteIpEndPoint.Port);
}

if (localIpEndPoint != null)
{
    // Using the LocalEndPoint property.
    Console.WriteLine("My local IpAddress is :" + localIpEndPoint.Address + "I am connected on port number " + localIpEndPoint.Port);
}

Where does gcc look for C and C++ header files?

You can create a file that attempts to include a bogus system header. If you run gcc in verbose mode on such a source, it will list all the system include locations as it looks for the bogus header.

$ echo "#include <bogus.h>" > t.c; gcc -v t.c; rm t.c

[..]

#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.

[..]

t.c:1:32: error: bogus.h: No such file or directory

Referencing a string in a string array resource with xml

Unfortunately:

  • It seems you can not reference a single item from an array in values/arrays.xml with XML. Of course you can in Java, but not XML. There's no information on doing so in the Android developer reference, and I could not find any anywhere else.

  • It seems you can't use an array as a key in the preferences layout. Each key has to be a single value with it's own key name.

What I want to accomplish: I want to be able to loop through the 17 preferences, check if the item is checked, and if it is, load the string from the string array for that preference name.

Here's the code I was hoping would complete this task:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());  
ArrayAdapter<String> itemsArrayList = new ArrayAdapter<String>(getBaseContext(),   android.R.layout.simple_list_item_1);  
String[] itemNames = getResources().getStringArray(R.array.itemNames_array);  


for (int i = 0; i < 16; i++) {  
    if (prefs.getBoolean("itemKey[i]", true)) {  
        itemsArrayList.add(itemNames[i]);  
    }  
} 

What I did:

  • I set a single string for each of the items, and referenced the single strings in the . I use the single string reference for the preferences layout checkbox titles, and the array for my loop.

  • To loop through the preferences, I just named the keys like key1, key2, key3, etc. Since you reference a key with a string, you have the option to "build" the key name at runtime.

Here's the new code:

for (int i = 0; i < 16; i++) {  
        if (prefs.getBoolean("itemKey" + String.valueOf(i), true)) {  
        itemsArrayList.add(itemNames[i]);  
    }  
}

How to make a new List in Java

Since Java 7 you have type inference for generic instance creation, so there is no need to duplicate generic parameters on the right hand side of the assignment:

List<String> list = new ArrayList<>();

A fixed-size list can be defined as:

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

For immutable lists you can use the Guava library:

List<String> list = ImmutableList.of("foo", "bar");

how to save and read array of array in NSUserdefaults in swift?

Here is an example of reading and writing a list of objects of type SNStock that implements NSCoding - we have an accessor for the entire list, watchlist, and two methods to add and remove objects, that is addStock(stock: SNStock) and removeStock(stock: SNStock).

import Foundation

class DWWatchlistController {

  private let kNSUserDefaultsWatchlistKey: String = "dw_watchlist_key"

  private let userDefaults: NSUserDefaults

  private(set) var watchlist:[SNStock] {

    get {
      if let watchlistData : AnyObject = userDefaults.objectForKey(kNSUserDefaultsWatchlistKey) {
        if let watchlist : AnyObject = NSKeyedUnarchiver.unarchiveObjectWithData(watchlistData as! NSData) {
          return watchlist as! [SNStock]
        }
      }
      return []
    }

    set(watchlist) {
      let watchlistData = NSKeyedArchiver.archivedDataWithRootObject(watchlist)
      userDefaults.setObject(watchlistData, forKey: kNSUserDefaultsWatchlistKey)
      userDefaults.synchronize()
    }
  }

  init() {
    userDefaults = NSUserDefaults.standardUserDefaults()
  }

  func addStock(stock: SNStock) {
    var watchlist = self.watchlist
    watchlist.append(stock)
    self.watchlist = watchlist
  }

  func removeStock(stock: SNStock) {
    var watchlist = self.watchlist
    if let index = find(watchlist, stock) {
      watchlist.removeAtIndex(index)
      self.watchlist = watchlist
    }
  }

}

Remember that your object needs to implement NSCoding or else the encoding won't work. Here is what SNStock looks like:

import Foundation

class SNStock: NSObject, NSCoding
{
  let ticker: NSString
  let name: NSString

  init(ticker: NSString, name: NSString)
  {
    self.ticker = ticker
    self.name = name
  }

  //MARK: NSCoding

  required init(coder aDecoder: NSCoder) {
    self.ticker = aDecoder.decodeObjectForKey("ticker") as! NSString
    self.name = aDecoder.decodeObjectForKey("name") as! NSString
  }

  func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(ticker, forKey: "ticker")
    aCoder.encodeObject(name, forKey: "name")
  }

  //MARK: NSObjectProtocol

  override func isEqual(object: AnyObject?) -> Bool {
    if let object = object as? SNStock {
      return self.ticker == object.ticker &&
        self.name == object.name
    } else {
      return false
    }
  }

  override var hash: Int {
    return ticker.hashValue
  }
}

Hope this helps!

How to get a file directory path from file path?

If you care target files to be symbolic link, firstly you can check it and get the original file. The if clause below may help you.

if [ -h $file ]
then
 base=$(dirname $(readlink $file))
else
 base=$(dirname $file)
fi

How to fix 'Notice: Undefined index:' in PHP form action

use isset for this purpose

<?php

 $index = 1;
 if(isset($_POST['filename'])) {
     $filename = $_POST['filename'];
     echo $filename;
 }

?>

memcpy() vs memmove()

I have tried to run same program using eclipse and it shows clear difference between memcpy and memmove. memcpy() doesn't care about overlapping of memory location which results in corruption of data, while memmove() will copy data to temporary variable first and then copy into actual memory location.

While trying to copy data from location str1 to str1+2, output of memcpy is "aaaaaa". The question would be how? memcpy() will copy one byte at a time from left to right. As shown in your program "aabbcc" then all copying will take place as below,

  1. aabbcc -> aaabcc

  2. aaabcc -> aaaacc

  3. aaaacc -> aaaaac

  4. aaaaac -> aaaaaa

memmove() will copy data to temporary variable first and then copy to actual memory location.

  1. aabbcc(actual) -> aabbcc(temp)

  2. aabbcc(temp) -> aaabcc(act)

  3. aabbcc(temp) -> aaaacc(act)

  4. aabbcc(temp) -> aaaabc(act)

  5. aabbcc(temp) -> aaaabb(act)

Output is

memcpy : aaaaaa

memmove : aaaabb

how to set select element as readonly ('disabled' doesnt pass select value on server)

You can simulate a readonly select box using the CSS pointer-events property:

select[readonly]
{
    pointer-events: none;
}

The HTML tabindex property will also prevent it from being selected by keyboard tabbing:

<select tabindex="-1">

_x000D_
_x000D_
select[readonly]_x000D_
{_x000D_
    pointer-events: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* irrelevent styling */_x000D_
_x000D_
*_x000D_
{_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
*[readonly]_x000D_
{_x000D_
  background: #fafafa;_x000D_
  border: 1px solid #ccc;_x000D_
  color: #555;_x000D_
}_x000D_
_x000D_
input, select_x000D_
{_x000D_
  display:block;_x000D_
  width: 20rem;_x000D_
  padding: 0.5rem;_x000D_
  margin-bottom: 1rem;_x000D_
}
_x000D_
<form>_x000D_
  <input type="text" value="this is a normal text box">_x000D_
  <input type="text" readonly value="this is a readonly text box">_x000D_
  <select readonly tabindex="-1">_x000D_
    <option>This is a readonly select box</option>_x000D_
    <option>Option 2</option>_x000D_
  </select>_x000D_
  <select>_x000D_
    <option>This is a normal select box</option>_x000D_
    <option>Option 2</option>_x000D_
  </select>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Keep values selected after form submission

Since WordPress already uses jQuery you can try something like this:

var POST=<?php echo json_encode($_POST); ?>;
for(k in POST){
  $("#"+k).val(POST[k]);
}

Batch file: Find if substring is in string (not in a file)

To find a text in the Var, Example:

var_text="demo string test"
Echo.%var_text% | findstr /C:"test">nul && (
    echo "found test" 
    ) || Echo.%var_text% | findstr /C:"String">nul && (
             echo "found String with S uppercase letter" 
    ) || (
             echo "Not Found " 
    )

LEGEND:

  1. & Execute_that AND execute_this
  2. || Ex: Execute_that IF_FAIL execute this
  3. && Ex: Execute_that IF_SUCCESSFUL execute this
  4. >nul no echo result of command
  5. findstr
  6. /C: Use string as a literal search string

Failed to load the JNI shared Library (JDK)

Make sure you are starting Eclipse with Administrator rights.

Transaction isolation levels relation with locks on table

As brb tea says, depends on the database implementation and the algorithm they use: MVCC or Two Phase Locking.

CUBRID (open source RDBMS) explains the idea of this two algorithms:

  • Two-phase locking (2PL)

The first one is when the T2 transaction tries to change the A record, it knows that the T1 transaction has already changed the A record and waits until the T1 transaction is completed because the T2 transaction cannot know whether the T1 transaction will be committed or rolled back. This method is called Two-phase locking (2PL).

  • Multi-version concurrency control (MVCC)

The other one is to allow each of them, T1 and T2 transactions, to have their own changed versions. Even when the T1 transaction has changed the A record from 1 to 2, the T1 transaction leaves the original value 1 as it is and writes that the T1 transaction version of the A record is 2. Then, the following T2 transaction changes the A record from 1 to 3, not from 2 to 4, and writes that the T2 transaction version of the A record is 3.

When the T1 transaction is rolled back, it does not matter if the 2, the T1 transaction version, is not applied to the A record. After that, if the T2 transaction is committed, the 3, the T2 transaction version, will be applied to the A record. If the T1 transaction is committed prior to the T2 transaction, the A record is changed to 2, and then to 3 at the time of committing the T2 transaction. The final database status is identical to the status of executing each transaction independently, without any impact on other transactions. Therefore, it satisfies the ACID property. This method is called Multi-version concurrency control (MVCC).

The MVCC allows concurrent modifications at the cost of increased overhead in memory (because it has to maintain different versions of the same data) and computation (in REPETEABLE_READ level you can't loose updates so it must check the versions of the data, like Hiberate does with Optimistick Locking).

In 2PL Transaction isolation levels control the following:

  • Whether locks are taken when data is read, and what type of locks are requested.

  • How long the read locks are held.

  • Whether a read operation referencing rows modified by another transaction:

    • Block until the exclusive lock on the row is freed.

    • Retrieve the committed version of the row that existed at the time the statement or transaction started.

    • Read the uncommitted data modification.

Choosing a transaction isolation level does not affect the locks that are acquired to protect data modifications. A transaction always gets an exclusive lock on any data it modifies and holds that lock until the transaction completes, regardless of the isolation level set for that transaction. For read operations, transaction isolation levels primarily define the level of protection from the effects of modifications made by other transactions.

A lower isolation level increases the ability of many users to access data at the same time, but increases the number of concurrency effects, such as dirty reads or lost updates, that users might encounter.

Concrete examples of the relation between locks and isolation levels in SQL Server (use 2PL except on READ_COMMITED with READ_COMMITTED_SNAPSHOT=ON)

  • READ_UNCOMMITED: do not issue shared locks to prevent other transactions from modifying data read by the current transaction. READ UNCOMMITTED transactions are also not blocked by exclusive locks that would prevent the current transaction from reading rows that have been modified but not committed by other transactions. [...]

  • READ_COMMITED:

    • If READ_COMMITTED_SNAPSHOT is set to OFF (the default): uses shared locks to prevent other transactions from modifying rows while the current transaction is running a read operation. The shared locks also block the statement from reading rows modified by other transactions until the other transaction is completed. [...] Row locks are released before the next row is processed. [...]
    • If READ_COMMITTED_SNAPSHOT is set to ON, the Database Engine uses row versioning to present each statement with a transactionally consistent snapshot of the data as it existed at the start of the statement. Locks are not used to protect the data from updates by other transactions.
  • REPETEABLE_READ: Shared locks are placed on all data read by each statement in the transaction and are held until the transaction completes.

  • SERIALIZABLE: Range locks are placed in the range of key values that match the search conditions of each statement executed in a transaction. [...] The range locks are held until the transaction completes.

pretty-print JSON using JavaScript

Better way.

Prettify JSON Array in Javascript

JSON.stringify(jsonobj,null,'\t')

How to apply CSS to iframe?

If the content of the iframe is not completely under your control or you want to access the content from different pages with different styles you could try manipulating it using JavaScript.

var frm = frames['frame'].document;
var otherhead = frm.getElementsByTagName("head")[0];
var link = frm.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", "style.css");
otherhead.appendChild(link);

Note that depending on what browser you use this might only work on pages served from the same domain.

How to count the number of occurrences of a character in an Oracle varchar value?

I justed faced very similar problem... BUT RegExp_Count couldn't resolved it. How many times string '16,124,3,3,1,0,' contains ',3,'? As we see 2 times, but RegExp_Count returns just 1. Same thing is with ''bbaaaacc' and when looking in it 'aa' - should be 3 times and RegExp_Count returns just 2.

select REGEXP_COUNT('336,14,3,3,11,0,' , ',3,') from dual;
select REGEXP_COUNT('bbaaaacc' , 'aa') from dual;

I lost some time to research solution on web. Couldn't' find... so i wrote my own function that returns TRUE number of occurance. Hope it will be usefull.

CREATE OR REPLACE FUNCTION EXPRESSION_COUNT( pEXPRESSION VARCHAR2, pPHRASE VARCHAR2 ) RETURN NUMBER AS
  vRET NUMBER := 0;
  vPHRASE_LENGTH NUMBER := 0;
  vCOUNTER NUMBER := 0;
  vEXPRESSION VARCHAR2(4000);
  vTEMP VARCHAR2(4000);
BEGIN
  vEXPRESSION := pEXPRESSION;
  vPHRASE_LENGTH := LENGTH( pPHRASE );
  LOOP
    vCOUNTER := vCOUNTER + 1;
    vTEMP := SUBSTR( vEXPRESSION, 1, vPHRASE_LENGTH);
    IF (vTEMP = pPHRASE) THEN        
        vRET := vRET + 1;
    END IF;
    vEXPRESSION := SUBSTR( vEXPRESSION, 2, LENGTH( vEXPRESSION ) - 1);
  EXIT WHEN ( LENGTH( vEXPRESSION ) = 0 ) OR (vEXPRESSION IS NULL);
  END LOOP;
  RETURN vRET;
END;

Convert all data frame character columns to factors

I used to do a simple for loop. As @A5C1D2H2I1M1N2O1R2T1 answer, lapply is a nice solution. But if you convert all the columns, you will need a data.frame before, otherwise you will end up with a list. Little execution time differences.

 mm2N=mm2New[,10:18]
 str(mm2N)
'data.frame':   35487 obs. of  9 variables:
 $ bb    : int  4 6 2 3 3 2 5 2 1 2 ...
 $ vabb  : int  -3 -3 -2 -2 -3 -1 0 0 3 3 ...
 $ bb55  : int  7 6 3 4 4 4 9 2 5 4 ...
 $ vabb55: int  -3 -1 0 -1 -2 -2 -3 0 -1 3 ...
 $ zr    : num  0 -2 -1 1 -1 -1 -1 1 1 0 ...
 $ z55r  : num  -2 -2 0 1 -2 -2 -2 1 -1 1 ...
 $ fechar: num  0 -1 1 0 1 1 0 0 1 0 ...
 $ varr  : num  3 3 1 1 1 1 4 1 1 3 ...
 $ minmax: int  3 0 4 6 6 6 0 6 6 1 ...

 # For solution
 t1=Sys.time()
 for(i in 1:ncol(mm2N)) mm2N[,i]=as.factor(mm2N[,i])
 Sys.time()-t1
Time difference of 0.2020121 secs
 str(mm2N)
'data.frame':   35487 obs. of  9 variables:
 $ bb    : Factor w/ 6 levels "1","2","3","4",..: 4 6 2 3 3 2 5 2 1 2 ...
 $ vabb  : Factor w/ 7 levels "-3","-2","-1",..: 1 1 2 2 1 3 4 4 7 7 ...
 $ bb55  : Factor w/ 8 levels "2","3","4","5",..: 6 5 2 3 3 3 8 1 4 3 ...
 $ vabb55: Factor w/ 7 levels "-3","-2","-1",..: 1 3 4 3 2 2 1 4 3 7 ...
 $ zr    : Factor w/ 5 levels "-2","-1","0",..: 3 1 2 4 2 2 2 4 4 3 ...
 $ z55r  : Factor w/ 5 levels "-2","-1","0",..: 1 1 3 4 1 1 1 4 2 4 ...
 $ fechar: Factor w/ 3 levels "-1","0","1": 2 1 3 2 3 3 2 2 3 2 ...
 $ varr  : Factor w/ 5 levels "1","2","3","4",..: 3 3 1 1 1 1 4 1 1 3 ...
 $ minmax: Factor w/ 7 levels "0","1","2","3",..: 4 1 5 7 7 7 1 7 7 2 ...

 #lapply solution
 mm2N=mm2New[,10:18]
 t1=Sys.time()
 mm2N <- lapply(mm2N, as.factor)
 Sys.time()-t1
Time difference of 0.209012 secs
 str(mm2N)
List of 9
 $ bb    : Factor w/ 6 levels "1","2","3","4",..: 4 6 2 3 3 2 5 2 1 2 ...
 $ vabb  : Factor w/ 7 levels "-3","-2","-1",..: 1 1 2 2 1 3 4 4 7 7 ...
 $ bb55  : Factor w/ 8 levels "2","3","4","5",..: 6 5 2 3 3 3 8 1 4 3 ...
 $ vabb55: Factor w/ 7 levels "-3","-2","-1",..: 1 3 4 3 2 2 1 4 3 7 ...
 $ zr    : Factor w/ 5 levels "-2","-1","0",..: 3 1 2 4 2 2 2 4 4 3 ...
 $ z55r  : Factor w/ 5 levels "-2","-1","0",..: 1 1 3 4 1 1 1 4 2 4 ...
 $ fechar: Factor w/ 3 levels "-1","0","1": 2 1 3 2 3 3 2 2 3 2 ...
 $ varr  : Factor w/ 5 levels "1","2","3","4",..: 3 3 1 1 1 1 4 1 1 3 ...
 $ minmax: Factor w/ 7 levels "0","1","2","3",..: 4 1 5 7 7 7 1 7 7 2 ...

 #data.frame lapply solution
 mm2N=mm2New[,10:18]
 t1=Sys.time()
 mm2N <- data.frame(lapply(mm2N, as.factor))
 Sys.time()-t1
Time difference of 0.2010119 secs
 str(mm2N)
'data.frame':   35487 obs. of  9 variables:
 $ bb    : Factor w/ 6 levels "1","2","3","4",..: 4 6 2 3 3 2 5 2 1 2 ...
 $ vabb  : Factor w/ 7 levels "-3","-2","-1",..: 1 1 2 2 1 3 4 4 7 7 ...
 $ bb55  : Factor w/ 8 levels "2","3","4","5",..: 6 5 2 3 3 3 8 1 4 3 ...
 $ vabb55: Factor w/ 7 levels "-3","-2","-1",..: 1 3 4 3 2 2 1 4 3 7 ...
 $ zr    : Factor w/ 5 levels "-2","-1","0",..: 3 1 2 4 2 2 2 4 4 3 ...
 $ z55r  : Factor w/ 5 levels "-2","-1","0",..: 1 1 3 4 1 1 1 4 2 4 ...
 $ fechar: Factor w/ 3 levels "-1","0","1": 2 1 3 2 3 3 2 2 3 2 ...
 $ varr  : Factor w/ 5 levels "1","2","3","4",..: 3 3 1 1 1 1 4 1 1 3 ...
 $ minmax: Factor w/ 7 levels "0","1","2","3",..: 4 1 5 7 7 7 1 7 7 2 ...

What is a "thread" (really)?

This was taken from a Yahoo Answer:

A thread is a coding construct unaffect by the architecture of an application. A single process frequently may contain multiple threads. Threads can also directly communicate with each other since they share the same variables.

Processes are independent execution units with their own state information. They also use their own address spaces and can only interact with other processes through interprocess communication mechanisms.

However, to put in simpler terms threads are like different "tasks". So think of when you are doing something, for instance you are writing down a formula on one paper. That can be considered one thread. Then another thread is you writing something else on another piece of paper. That is where multitasking comes in.

Intel processors are said to have "hyper-threading" (AMD has it too) and it is meant to be able to perform multiple "threads" or multitask much better.

I am not sure about the logistics of how a thread is handled. I do recall hearing about the processor going back and forth between them, but I am not 100% sure about this and hopefully somebody else can answer that.

PHP: How to send HTTP response code?

If you are here because of Wordpress giving 404's when loading the environment, this should fix the problem:

define('WP_USE_THEMES', false);
require('../wp-blog-header.php');
status_header( 200 );
//$wp_query->is_404=false; // if necessary

The problem is due to it sending a Status: 404 Not Found header. You have to override that. This will also work:

define('WP_USE_THEMES', false);
require('../wp-blog-header.php');
header("HTTP/1.1 200 OK");
header("Status: 200 All rosy");

How I could add dir to $PATH in Makefile?

By design make parser executes lines in a separate shell invocations, that's why changing variable (e.g. PATH) in one line, the change may not be applied for the next lines (see this post).

One way to workaround this problem, is to convert multiple commands into a single line (separated by ;), or use One Shell special target (.ONESHELL, as of GNU Make 3.82).

Alternatively you can provide PATH variable at the time when shell is invoked. For example:

PATH  := $(PATH):$(PWD)/bin:/my/other/path
SHELL := env PATH=$(PATH) /bin/bash

jquery change div text

Put the title in its own span.

<span id="dialog_title_span">'+dialog_title+'</span>
$('#dialog_title_span').text("new dialog title");

Opacity of background-color, but not the text

I use an alpha-transparent PNG for that:

div.semi-transparent {
  background: url('semi-transparent.png');
}

For IE6, you'd need to use a PNG fix (1, 2), though.

Good MapReduce examples

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

Usually I take two things:

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

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

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

One addendum to the excellent answers above, on a point that confused me even after I had read Stroustrup and thought I understood the rvalue/lvalue distinction. When you see

int&& a = 3,

it's very tempting to read the int&& as a type and conclude that a is an rvalue. It's not:

int&& a = 3;
int&& c = a; //error: cannot bind 'int' lvalue to 'int&&'
int& b = a; //compiles

a has a name and is ipso facto an lvalue. Don't think of the && as part of the type of a; it's just something telling you what a is allowed to bind to.

This matters particularly for T&& type arguments in constructors. If you write

Foo::Foo(T&& _t) : t{_t} {}

you will copy _t into t. You need

Foo::Foo(T&& _t) : t{std::move(_t)} {} if you want to move. Would that my compiler warned me when I left out the move!

mysql query: SELECT DISTINCT column1, GROUP BY column2

Try the following:

SELECT DISTINCT(ip), name, COUNT(name) nameCnt, 
time, price, SUM(price) priceSum
FROM tablename 
WHERE time >= $yesterday AND time <$today 
GROUP BY ip, name

How to delete stuff printed to console by System.out.println()?

I am using blueJ for java programming. There is a way to clear the screen of it's terminal window. Try this:-

System.out.print ('\f');

this will clear whatever is printed before this line. But this does not work in command prompt.

ipython notebook clear cell output in code

And in case you come here, like I did, looking to do the same thing for plots in a Julia notebook in Jupyter, using Plots, you can use:

    IJulia.clear_output(true)

so for a kind of animated plot of multiple runs

    if nrun==1  
      display(plot(x,y))         # first plot
    else 
      IJulia.clear_output(true)  # clear the window (as above)
      display(plot!(x,y))        # plot! overlays the plot
    end

Without the clear_output call, all plots appear separately.

How can I disable an <option> in a <select> based on its value in JavaScript?

var vals = new Array( 2, 3, 5, 8 );
select_disable_options('add_reklamaciq_reason',vals);
select_disable_options('add_reklamaciq_reason');

function select_disable_options(selectid,vals){
  var selected = false ;
  $('#'+selectid+' option').removeAttr('selected');
  $('#'+selectid+' option').each(function(i,elem){
       var elid = parseInt($(elem).attr('value'));
       if(vals){
           if(vals.indexOf(elid) != -1){
               $(elem).removeAttr('disabled');
               if(selected == false){
                   $(elem).attr('selected','selected');
                   selected = true ; 
               }
           }else{
               $(elem).attr('disabled','disabled'); 
           }
       }else{
            $(elem).removeAttr('disabled');
       }
  });   
}

Here with JQ .. if anybody search it

Delete all the records

Use the DELETE statement

Delete From <TableName>

Eg:

Delete from Student;

ngOnInit not being called when Injectable class is Instantiated

import {Injectable, OnInit} from 'angular2/core';
import { RestApiService, RestRequest } from './rest-api.service';
import {Service} from "path/to/service/";

@Injectable()
export class MovieDbService implements OnInit {

userId:number=null;

constructor(private _movieDbRest: RestApiService,
            private instanceMyService : Service ){

   // do evreything like OnInit just on services

   this._movieDbRest.callAnyMethod();

   this.userId = this.instanceMyService.getUserId()


}

How do I wait for a promise to finish before returning the variable of a function?

You don't want to make the function wait, because JavaScript is intended to be non-blocking. Rather return the promise at the end of the function, then the calling function can use the promise to get the server response.

var promise = query.find(); 
return promise; 

//Or return query.find(); 

Postfix is installed but how do I test it?

(I just got this working, with my main issue being that I don't have a real internet hostname, so answering this question in case it helps someone)

You need to specify a hostname with HELO. Even so, you should get an error, so Postfix is probably not running.

Also, the => is not a command. The '.' on a single line without any text around it is what tells Postfix that the entry is complete. Here are the entries I used:

telnet localhost 25
(says connected)
EHLO howdy.com
(returns a bunch of 250 codes)
MAIL FROM: [email protected]
RCPT TO: (use a real email address you want to send to)
DATA (type whatever you want on muliple lines)
. (this on a single line tells Postfix that the DATA is complete)

You should get a response like:

250 2.0.0 Ok: queued as 6E414C4643A

The email will probably end up in a junk folder. If it is not showing up, then you probably need to setup the 'Postfix on hosts without a real Internet hostname'. Here is the breakdown on how I completed that step on my Ubuntu box:

sudo vim /etc/postfix/main.cf
smtp_generic_maps = hash:/etc/postfix/generic (add this line somewhere)
(edit or create the file 'generic' if it doesn't exist)
sudo vim /etc/postfix/generic
(add these lines, I don't think it matters what names you use, at least to test)
[email protected]             [email protected]
[email protected]             [email protected]
@localdomain.local                [email protected]
then run:
postmap /etc/postfix/generic (this needs to be run whenever you change the 
generic file)

Happy Trails

No input file specified

Adding php5.ini doesn't work at all. But see the 'Disable FastCGI' section in this article on GoDaddy: http://support.godaddy.com/help/article/5121/changing-your-hosting-accounts-file-extensions

Add these lines to .htaccess files (webroot & website installation directory):

Options +ExecCGI
addhandler x-httpd-php5-cgi .php

It saves me a day! Cheers! Thanks DragonLord!

force line break in html table cell

You could put the text into a div (or other container) with a width of 50%.

http://jsfiddle.net/6gjsd/

How do I break out of a loop in Perl?

Simply last would work here:

for my $entry (@array){
    if ($string eq "text"){
         last;
    }
}

If you have nested loops, then last will exit from the innermost loop. Use labels in this case:

LBL_SCORE: {
    for my $entry1 (@array1) {
        for my $entry2 (@array2) {
            if ($entry1 eq $entry2) { # Or any condition
                last LBL_SCORE;
            }
        }
    }
 }

Given a last statement will make the compiler to come out from both the loops. The same can be done in any number of loops, and labels can be fixed anywhere.

Function Pointers in Java

I have implemented callback/delegate support in Java using reflection. Details and working source are available on my website.

How It Works

We have a principle class named Callback with a nested class named WithParms. The API which needs the callback will take a Callback object as a parameter and, if neccessary, create a Callback.WithParms as a method variable. Since a great many of the applications of this object will be recursive, this works very cleanly.

With performance still a high priority to me, I didn't want to be required to create a throwaway object array to hold the parameters for every invocation - after all in a large data structure there could be thousands of elements, and in a message processing scenario we could end up processing thousands of data structures a second.

In order to be threadsafe the parameter array needs to exist uniquely for each invocation of the API method, and for efficiency the same one should be used for every invocation of the callback; I needed a second object which would be cheap to create in order to bind the callback with a parameter array for invocation. But, in some scenarios, the invoker would already have a the parameter array for other reasons. For these two reasons, the parameter array did not belong in the Callback object. Also the choice of invocation (passing the parameters as an array or as individual objects) belongs in the hands of the API using the callback enabling it to use whichever invocation is best suited to it's inner workings.

The WithParms nested class, then, is optional and serves two purposes, it contains the parameter object array needed for the callback invocations, and it provides 10 overloaded invoke() methods (with from 1 to 10 parameters) which load the parameter array and then invoke the callback target.

Expression must be a modifiable L-value

lvalue means "left value" -- it should be assignable. You cannot change the value of text since it is an array, not a pointer.

Either declare it as char pointer (in this case it's better to declare it as const char*):

const char *text;
if(number == 2) 
    text = "awesome"; 
else 
    text = "you fail";

Or use strcpy:

char text[60];
if(number == 2) 
    strcpy(text, "awesome"); 
else 
    strcpy(text, "you fail");

How can I delete an item from an array in VB.NET?

This may be a lazy man's solution, but can't you just delete the contents of the index you want removed by reassigning their values to 0 or "" and then ignore/skip these empty array elements instead of recreating and copying arrays on and off?

When do items in HTML5 local storage expire?

I would suggest to store timestamp in the object you store in the localStorage

var object = {value: "value", timestamp: new Date().getTime()}
localStorage.setItem("key", JSON.stringify(object));

You can parse the object, get the timestamp and compare with the current Date, and if necessary, update the value of the object.

var object = JSON.parse(localStorage.getItem("key")),
    dateString = object.timestamp,
    now = new Date().getTime().toString();

compareTime(dateString, now); //to implement

How do I alter the position of a column in a PostgreSQL database table?

I use Django and it requires id column in each table if you don't want to have a headache. Unfortunately, I was careless and my table bp.geo_location_vague didn't contain this field. I initialed little trick. Step 1:

CREATE VIEW bp.geo_location_vague_vw AS
    SELECT 
        a.id, -- I change order of id column here. 
        a.in_date,
        etc
    FROM bp.geo_location_vague a

Step 2: (without create table - table will create automaticaly!)

SELECT * into bp.geo_location_vague_cp2 FROM bp.geo_location_vague_vw

Step 3:

CREATE SEQUENCE bp.tbl_tbl_id_seq;
ALTER TABLE bp.geo_location_vague_cp2 ALTER COLUMN id SET DEFAULT nextval('tbl_tbl_id_seq');
ALTER SEQUENCE bp.tbl_tbl_id_seq OWNED BY bp.geo_location_vague_cp2.id;
SELECT setval('tbl_tbl_id_seq', COALESCE(max(id), 0)) FROM bp.geo_location_vague_cp2;

Because I need have bigserial pseudotype in the table. After SELECT * into pg will create bigint type insetad bigserial.

step 4: Now we can drop the view, drop source table and rename the new table in the old name. The trick was ended successfully.

Get current date/time in seconds

Based on your comment, I think you're looking for something like this:

var timeout = new Date().getTime() + 15*60*1000; //add 15 minutes;

Then in your check, you're checking:

if(new Date().getTime() > timeout) {
  alert("Session has expired");
}

Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm­­.dll, please install or use the JRE or JDK that contains these missing components.

Follow these steps:

Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)

After that, go to C:/Program files/java/jre7/bin

Here, create an folder called Server

Now go into the C:/Program files/java/jre7/bin/client folder

Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server folder

How to set app icon for Electron / Atom Shell App

For windows use Resource Hacker

Download and Install: :D

http://www.angusj.com/resourcehacker/

  • Run It
  • Select open and select exe file
  • On your left open a folder called Icon Group
  • Right click 1: 1033
  • Click replace icon
  • Select the icon of your choice
  • Then select replace icon
  • Save then close

You should have build the app

How to declare a constant map in Golang?

You can create constants in many different ways:

const myString = "hello"
const pi = 3.14 // untyped constant
const life int = 42 // typed constant (can use only with ints)

You can also create a enum constant:

const ( 
   First = 1
   Second = 2
   Third = 4
)

You can not create constants of maps, arrays and it is written in effective go:

Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance, 1<<3 is a constant expression, while math.Sin(math.Pi/4) is not because the function call to math.Sin needs to happen at run time.

Display HTML snippets in HTML

In HTML? No.

In XML/XHTML? You could use a CDATA block.

Find files in created between a date range

You can use the below to find what you need.

Find files older than a specific date/time:

find ~/ -mtime $(echo $(date +%s) - $(date +%s -d"Dec 31, 2009 23:59:59") | bc -l | awk '{print $1 / 86400}' | bc -l)

Or you can find files between two dates. First date more recent, last date, older. You can go down to the second, and you don't have to use mtime. You can use whatever you need.

find . -mtime $(date +%s -d"Aug 10, 2013 23:59:59") -mtime $(date +%s -d"Aug 1, 2013 23:59:59")

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

The difference between encodeURI() and encodeURIComponent() are exactly 11 characters encoded by encodeURIComponent but not by encodeURI:

Table with the ten differences between encodeURI and encodeURIComponent

I generated this table easily with console.table in Google Chrome with this code:

_x000D_
_x000D_
var arr = [];_x000D_
for(var i=0;i<256;i++) {_x000D_
  var char=String.fromCharCode(i);_x000D_
  if(encodeURI(char)!==encodeURIComponent(char)) {_x000D_
    arr.push({_x000D_
      character:char,_x000D_
      encodeURI:encodeURI(char),_x000D_
      encodeURIComponent:encodeURIComponent(char)_x000D_
    });_x000D_
  }_x000D_
}_x000D_
console.table(arr);
_x000D_
_x000D_
_x000D_

How do I redirect to another webpage?

First write properly. You want to navigate within an application for another link from your application for another link. Here is the code:

window.location.href = "http://www.google.com";

And if you want to navigate pages within your application then I also have code, if you want.

pip or pip3 to install packages for Python 3?

I think pip, pip2 and pip3 are not soft links to the same executable file path. Note these commands and results in my Linux terminal:

mrz@mrz-pc ~ $ ls -l `which pip`
-rwxr-xr-x 1 root root 292 Nov 10  2016 /usr/bin/pip
mrz@mrz-pc ~ $ ls -l `which pip2`
-rwxr-xr-x 1 root root 283 Nov 10  2016 /usr/bin/pip2
mrz@mrz-pc ~ $ ls -l `which pip3`
-rwxr-xr-x 1 root root 293 Nov 10  2016 /usr/bin/pip3
mrz@mrz-pc ~ $ pip -V
pip 9.0.1 from /home/mrz/.local/lib/python2.7/site-packages (python 2.7)
mrz@mrz-pc ~ $ pip2 -V
pip 8.1.1 from /usr/lib/python2.7/dist-packages (python 2.7)
mrz@mrz-pc ~ $ pip3 -V
pip 9.0.1 from /home/mrz/.local/lib/python3.5/site-packages (python 3.5)

As you see they exist in different paths.

pip3 always operates on the Python3 environment only, as pip2 does with Python2. pip operates in whichever environment is appropriate to the context. For example, if you are in a Python3 venv, pip will operate on the Python3 environment.

Performing Inserts and Updates with Dapper

You can try this:

 string sql = "UPDATE Customer SET City = @City WHERE CustomerId = @CustomerId";             
 conn.Execute(sql, customerEntity);

How to check if an alert exists using WebDriver?

This code will check whether the alert is present or not.

public static void isAlertPresent(){
    try{
    Alert alert = driver.switchTo().alert();
    System.out.println(alert.getText()+" Alert is Displayed"); 
    }
    catch(NoAlertPresentException ex){
    System.out.println("Alert is NOT Displayed");
    }
    }

Creating custom function in React component

You can create functions in react components. It is actually regular ES6 class which inherits from React.Component. Just be careful and bind it to the correct context in onClick event:

export default class Archive extends React.Component { 

    saySomething(something) {
        console.log(something);
    }

    handleClick(e) {
        this.saySomething("element clicked");
    }

    componentDidMount() {
        this.saySomething("component did mount");
    }

    render() {
        return <button onClick={this.handleClick.bind(this)} value="Click me" />;
    }
}

CSS animation delay in repeating

You can create a "fake" delay between infinite animations purely with CSS. The way to do it is smartly define your keyframe animation points and your animation duration speed.

For example, if we wanted to animate a bouncing ball, and we wanted a good .5s to 1s delay between each bounce, we can do something like:

@keyframes bounce{
    0%{
        transform: translateY(0);
    }
    50%{
        transform: translateY(25%);
    }
    75%{
        transform: translateY(15%);
    }
    90%{
        transform: translateY(0%);
    }
    100%{
        transform: translateY(0);
    }
}

What we do is make sure that the ball goes back to its original position much earlier than 100%. In my example, I'm doing it in 90% which provided me with around .1s delay which was good enough for me. But obviously for your case, you can either add more key frame points and change the transform values.

Furthermore, you can add additional animation duration to balance your key frame animations.

For example:

 animation: bounce .5s ease-in-out infinite;

Lets say that we wanted the full animation to end in .5s, but we wanted an additional .2s in delay between the animations.

 animation: bounce .7s ease-in-out infinite;

So we'll add an additional .2s delay, and in our key frame animations, we can add more percentage points to fill in the gaps of the .2s delay.

Java: Finding the highest value in an array

import java.util.*;
class main9 //Find the smallest and 2lagest and  ascending and descending order of  elements in array//
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the array range");
        int no=sc.nextInt();
        System.out.println("Enter the array element");
        int a[]=new int[no];
        int i;
        for(i=0;i<no;i++)
        {
            a[i]=sc.nextInt();
        }
        Arrays.sort(a);
        int s=a[0];
        int l=a[a.length-1];
        int m=a[a.length-2];
        System.out.println("Smallest no is="+s);
        System.out.println("lagest 2 numbers are=");
        System.out.println(l);
        System.out.println(m);
        System.out.println("Array in ascending:");
        for(i=0;i<no;i++)
        {
            System.out.println(a[i]);
        }
        System.out.println("Array in descending:");
        for(i=a.length-1;i>=0;i--)
        {
            System.out.println(a[i]);
        }
    }
}

Is there shorthand for returning a default value if None in Python?

return "default" if x is None else x

try the above.

Vibrate and Sound defaults on notification

I m using the followung code and its working fine for me .

private void sendNotification(String msg) {
    Log.d(TAG, "Preparing to send notification...: " + msg);
    mNotificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), 0);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            this).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("GCM Notification")
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    Log.d(TAG, "Notification sent successfully.");
}

Android: How can I validate EditText input?

You can get desired behavior by listening when user hit "Done" button on keyboard, also checkout other tips about working with EditText in my post "Android form validation - the right way"

Sample code:

mTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {                    
            validateAndSubmit();
            return true;
        }
        return false;
    }});  

Leave only two decimal places after the dot

Simple solution:

double totalCost = 123.45678;
totalCost = Convert.ToDouble(String.Format("{0:0.00}", totalCost));

//output: 123.45

submit form on click event using jquery

If you have a form action and an input type="submit" inside form tags, it's going to submit the old fashioned way and basically refresh the page. When doing AJAX type transactions this isn't the desired effect you are after.

Remove the action. Or remove the form altogether, though in cases it does come in handy to serialize to cut your workload. If the form tags remain, move the button outside the form tags, or alternatively make it a link with an onclick or click handler as opposed to an input button. Jquery UI Buttons works great in this case because you can mimic an input button with an a tag element.

What is the difference between the HashMap and Map objects in Java?

Map is an interface that HashMap implements. The difference is that in the second implementation your reference to the HashMap will only allow the use of functions defined in the Map interface, while the first will allow the use of any public functions in HashMap (which includes the Map interface).

It will probably make more sense if you read Sun's interface tutorial

How to convert .crt to .pem

You can do this conversion with the OpenSSL library

http://www.openssl.org/

Windows binaries can be found here:

http://www.slproweb.com/products/Win32OpenSSL.html

Once you have the library installed, the command you need to issue is:

openssl x509 -in mycert.crt -out mycert.pem -outform PEM

How to prepare a Unity project for git?

Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository
  2. Switch to Hidden Meta Files in Editor ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Editor ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save scene and project from File menu

Note that the only folders you need to keep under source control are Assets and ProjectSettigns.

More information about keeping Unity Project under source control you can find in this post.

What is a regex to match ONLY an empty string?

Wow, ya'll are overthinking it. It's as simple as the following. Besides, many of those answers aren't understood by the RE2 dialect used by C and golang.

^$

Importing two classes with same name. How to handle?

This scenario is not so common in real-world programming, but not so strange too. It happens sometimes that two classes in different packages have same name and we need both of them.

It is not mandatory that if two classes have same name, then both will contain same functionalities and we should pick only one of them.

If we need both, then there is no harm in using that. And it's not a bad programming idea too.

But we should use fully qualified names of the classes (that have same name) in order to make it clear which class we are referring too.

:)

How to align text below an image in CSS?

Since the default for block elements is to order one on top of the other you should also be able to do this:

<div>
    <img src="path/to/img">
    <div>Text Under Image</div>
</div

img {
    display: block;
}

android layout with visibility GONE

Done by having it like that:

view = inflater.inflate(R.layout.entry_detail, container, false);
TextView tp1= (TextView) view.findViewById(R.id.tp1);
LinearLayout layone= (LinearLayout) view.findViewById(R.id.layone);
tp1.setVisibility(View.VISIBLE);
layone.setVisibility(View.VISIBLE);

How to return a specific element of an array?

Make sure return type of you method is same what you want to return. Eg: `

  public int get(int[] r)
  {
     return r[0];
  }

`

Note : return type is int, not int[], so it is able to return int.

In general, prototype can be

public Type get(Type[] array, int index)
{
    return array[index];
}

How to change the default encoding to UTF-8 for Apache?

For completeness, on Apache2 on Ubuntu, you will find the default charset in charset.conf in conf-available.

Uncomment the line

AddDefaultCharset UTF-8

How to create a Jar file in Netbeans

Now (2020) NetBeans 11 does it automatically with the "Build" command (right click on the project's name and choose "Build")

Running Python code in Vim

You can extends for any language with 1 keybinding with augroup command, for example:

augroup rungroup
    autocmd!
    autocmd BufRead,BufNewFile *.go nnoremap <F5> :exec '!go run' shellescape(@%, 1)<cr>
    autocmd BufRead,BufNewFile *.py nnoremap <F5> :exec '!python' shellescape(@%, 1)<cr>
augroup END

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

If you knew the Class of ImplementationType you could create an instance of it. So what you are trying to do is not possible.

SQL Server: how to create a stored procedure

I think it can help you:

CREATE PROCEDURE DEPT_COUNT
(
    @DEPT_NAME VARCHAR(20), -- Input parameter
    @D_COUNT INT OUTPUT     -- Output parameter
    -- Remember parameters begin with "@"
)
AS -- You miss this word in your example
BEGIN
    SELECT COUNT(*) 
    INTO #D_COUNT -- Into a Temp Table (prefix "#")
    FROM INSTRUCTOR
    WHERE INSTRUCTOR.DEPT_NAME = DEPT_COUNT.DEPT_NAME
END

Then, you can call the SP like this way, for example:

DECLARE @COUNTER INT
EXEC DEPT_COUNT 'DeptName', @COUNTER OUTPUT
SELECT @COUNTER

How to get $HOME directory of different user in bash script?

I was also looking for this, but didn't want to impersonate a user to simply acquire a path!

user_path=$(grep $username /etc/passwd|cut -f6 -d":");

Now in your script, you can refer to $user_path in most cases would be /home/username

Assumes: You have previously set $username with the value of the intended users username. Source: http://www.unix.com/shell-programming-and-scripting/171782-cut-fields-etc-passwd-file-into-variables.html

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

String str = "  this is string   ";
str = str.replaceAll("\\s+", " ").trim();

.htaccess redirect all pages to new domain

Just to clarify, after removing the hosting redirect which was in the way, my original solution also works:

RewriteEngine On
RewriteRule ^(.*)$ http://newdomain.com/ [R=301]

How to access the GET parameters after "?" in Express?

In my case with the given code, I was able to parse the value of the passed parameter in this way.

_x000D_
_x000D_
const express = require('express');
const bodyParser = require('body-parser');

const app = express(); 
app.use(bodyParser.urlencoded({ extended: false }));
//url/par1=val1&par2=val2 
let val1= req.body.par1;
let val2 = req.body.par2;
_x000D_
_x000D_
_x000D_

CSS transition when class removed

Basically set up your css like:

element {
  border: 1px solid #fff;      
  transition: border .5s linear;
}

element.saved {
  border: 1px solid transparent;
}

Is it possible to program Android to act as physical USB keyboard?

Don't give up. Linux can do it with the right hardware, via "USB Gadgets." And giving the following facts:

  1. My old Nokia N95 could use it's USB to be a "Mass Storage Device", a "Media Player", "a GSM modem", or to print photos.
  2. I can plug an iPhone into an iPad via a the Apple USB-Camera passive adapter, and they transfer pictures.
  3. iPhone can obvious present as a number of things, e.g. when they go into DFU.

Why is all this relevant?

Because if I was writing a linux phone I know what it would do, and how it would do it. And the answer would involve USB Gadgets.

Reading one of the links that was posted here,

It's the Linux kernel, the code is in drivers/usb/gadget/ in the kernel.org tree if you are interested. Android does have a few specific gadget patches that are not in mainline, but it's not all that much. You can see all of this by just checking out their kernel git tree, no need to bother their developers.

I would guess that you would have a shot at it - but it would involve recompiling the android kernel/operating system - or at least having a build environment in which you /could/ rebuild the kernel if you wanted.

BTW, I have an Atmel NGW100mkII, which support USB gadgets, but doesn't ship with the HID module. And I'll be having to do the above and more.

Passing arguments forward to another javascript function

If you want to only pass certain arguments, you can do so like this:

Foo.bar(TheClass, 'theMethod', 'arg1', 'arg2')

Foo.js

bar (obj, method, ...args) {
  obj[method](...args)
}

obj and method are used by the bar() method, while the rest of args are passed to the actual call.

How to use awk sort by column 3

awk -F "," '{print $0}' user.csv | sort -nk3 -t ','

This should work

Set padding for UITextField with UITextBorderStyleNone

Why not Attributed String !?!, this is one of the blessing feature of IOS 6.0 :)

NSMutableParagraphStyle *mps = [[NSMutableParagraphStyle alloc] init];
            mps.firstLineHeadIndent = 5.0f;
UIColor *placeColor = self.item.bgColor;

textFieldInstance.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"My Place Holder" attributes:@{NSForegroundColorAttributeName: placeColor, NSFontAttributeName : [UIFont systemFontOfSize:7.0f], NSParagraphStyleAttributeName : mps}];

Installing Python 2.7 on Windows 8

I think that the essence of this question is how to install Python and be able to use it from the command line. The steps below show how to get all that working. Check that you didn't miss anything:

  1. From https://www.python.org/download/releases/2.7.6 download appropriate Python 2.7.6 Windows Installer. (If that link doesn't work, check https://www.python.org/downloads/)
  2. Run the file
  3. Select install for all users or install just for me, click Next
  4. You'll see it installs under the C:\Python27 folder, click Next
  5. Click Next again for the 'Customize Python' step
  6. Click Finish
  7. Open Control Panel, then System
  8. Click 'Advanced system settings' on the left
  9. Click the 'Environment Variables' button
  10. Under 'System variables' click the variable called 'Path' then the 'Edit...' button. (This will set it for all users, you could instead choose to edit the User variables to just set python as a command prompt command for the current user)
  11. Without deleting any other text, add C:\Python27; (include the semi-colon) to the beginning of the 'Variable value' and click OK.
  12. Click OK on the 'Environment Variables' window.

Open a new command prompt window type python, you will have python running in the command prompt. Note: command prompt windows open prior to setting the Environment Variable will not have the python command available.

How to comment out a block of code in Python

In Visual Studio using the Python Tools for Visual Studio, blocks can be commented out by Ctrl+K, Ctrl+C and uncommented by Ctrl+K, Ctrl+U.

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

Added a new answer to display the code formatted:

The thing is that you were checking for document.referer, because you were in ff it was returning always true, then it was navigating to http://mysite.com. Try the following:

function backAway(){
    if (document.referrer) {
        //firefox, chrome, etc..
        i = 0;
    } else {
        // under ie
        i = 1;
    }
    if (history.length>i)
    {
        // there are items in history property
        history.back();
    } else {
        window.location = 'http://www.mysite.com/';
    }
    return false;
}

How different is Scrum practice from Agile Practice?

As is mentioned, Agile is a methodology, and there are various ways to define what agile is. To a large extent, if it involves constant unit testing and the ability to quickly adapt when the business needs change then it is probably agile. The opposite is the waterfall method.

There are various implementations that are codified by consultants, such as Xtremem Programming, Scrum and RUP (Rational Unified Process).

So, if you are using Scrum then you can switch between agile and scrum depending on if you are talking about the methodology or your implementation. You will want to see if the terms are being used correctly, by the context.

For example, if I am talking about the 15 min standup as part of my agile process, that is not necessarily needed to be agile, but scrum almost requires it, so when you interchange the terms, it is important to differentiate between the two concepts.

What is sys.maxint in Python 3?

If you are looking for a number that is bigger than all others:

Method 1:

float('inf')

Method 2:

import sys
max = sys.maxsize

If you are looking for a number that is smaller than all others:

Method 1:

float('-inf')

Method 2:

import sys
min = -sys.maxsize - 1

Method 1 works in both Python2 and Python3. Method 2 works in Python3. I have not tried Method 2 in Python2.