Programs & Examples On #Corporate policy

Querying data by joining two tables in two database on different servers

You could try the following:

select customer1.Id,customer1.Name,customer1.city,CustAdd.phone,CustAdd.Country
from customer1
inner join [EBST08].[Test].[dbo].[customerAddress] CustAdd
on customer1.Id=CustAdd.CustId

Selecting between two dates within a DateTime field - SQL Server

select * 
from blah 
where DatetimeField between '22/02/2009 09:00:00.000' and '23/05/2009 10:30:00.000'

Depending on the country setting for the login, the month/day may need to be swapped around.

How to use doxygen to create UML class diagrams from C++ source

Quote from this post (it's written by the author of doxygen himself) :

run doxygen -g and change the following options of the generated Doxyfile:

    EXTRACT_ALL            = YES
    HAVE_DOT               = YES
    UML_LOOK               = YES

run doxygen again

Setting Custom ActionBar Title from Fragment

Best event for change title onCreateOptionsMenu

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.general, container,  
    setHasOptionsMenu(true); // <-Add this line
    return view;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    // If use specific menu
    menu.clear();
    inflater.inflate(R.menu.path_list_menu, menu);
    // If use specific menu

    ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Your Fragment");
    super.onCreateOptionsMenu(menu, inflater);
}

Add onClick event to document.createElement("th")

var newTH = document.createElement('th');
newTH.addEventListener( 'click', function(){
  // delete the column here
} );

Overlaying a DIV On Top Of HTML 5 Video

Here is a stripped down example, using as little HTML markup as possible.

The Basics

  • The overlay is provided by the :before pseudo element on the .content container.

  • No z-index is required, :before is naturally layered over the video element.

  • The .content container is position: relative so that the position: absolute overlay is positioned in relation to it.

  • The overlay is stretched to cover the entire .content div width with left / right / bottom and left set to 0.

  • The width of the video is controlled by the width of its container with width: 100%

The Demo

_x000D_
_x000D_
.content {
  position: relative;
  width: 500px;
  margin: 0 auto;
  padding: 20px;
}
.content video {
  width: 100%;
  display: block;
}
.content:before {
  content: '';
  position: absolute;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 5px;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
_x000D_
<div class="content">
  <video id="player" src="https://upload.wikimedia.org/wikipedia/commons/transcoded/1/18/Big_Buck_Bunny_Trailer_1080p.ogv/Big_Buck_Bunny_Trailer_1080p.ogv.360p.vp9.webm" autoplay loop muted></video>
</div>
_x000D_
_x000D_
_x000D_

C multi-line macro: do/while(0) vs scope block

Andrey Tarasevich provides the following explanation:

  1. On Google Groups
  2. On bytes.com

[Minor changes to formatting made. Parenthetical annotations added in square brackets []].

The whole idea of using 'do/while' version is to make a macro which will expand into a regular statement, not into a compound statement. This is done in order to make the use of function-style macros uniform with the use of ordinary functions in all contexts.

Consider the following code sketch:

if (<condition>)
  foo(a);
else
  bar(a);

where foo and bar are ordinary functions. Now imagine that you'd like to replace function foo with a macro of the above nature [named CALL_FUNCS]:

if (<condition>)
  CALL_FUNCS(a);
else
  bar(a);

Now, if your macro is defined in accordance with the second approach (just { and }) the code will no longer compile, because the 'true' branch of if is now represented by a compound statement. And when you put a ; after this compound statement, you finished the whole if statement, thus orphaning the else branch (hence the compilation error).

One way to correct this problem is to remember not to put ; after macro "invocations":

if (<condition>)
  CALL_FUNCS(a)
else
  bar(a);

This will compile and work as expected, but this is not uniform. The more elegant solution is to make sure that macro expand into a regular statement, not into a compound one. One way to achieve that is to define the macro as follows:

#define CALL_FUNCS(x) \
do { \
  func1(x); \
  func2(x); \
  func3(x); \
} while (0)

Now this code:

if (<condition>)
  CALL_FUNCS(a);
else
  bar(a);

will compile without any problems.

However, note the small but important difference between my definition of CALL_FUNCS and the first version in your message. I didn't put a ; after } while (0). Putting a ; at the end of that definition would immediately defeat the entire point of using 'do/while' and make that macro pretty much equivalent to the compound-statement version.

I don't know why the author of the code you quoted in your original message put this ; after while (0). In this form both variants are equivalent. The whole idea behind using 'do/while' version is not to include this final ; into the macro (for the reasons that I explained above).

Android Canvas: drawing too large bitmap

This solution worked for me.

Add these lines in your Manifest application tag

android:largeHeap="true"
android:hardwareAccelerated="false"

    

How to use breakpoints in Eclipse

Here is a video about Debugging with eclipse.

For more details read this page.

Instead of Debugging as Java program, use Debug as Android Application

May help new comers.

How to match, but not capture, part of a regex?

A variation of the expression by @Gumbo that makes use of \K for resetting match positions to prevent the inclusion of number blocks in the match. Usable in PCRE regex flavours.

123-\K(?:(?:apple|banana)(?=-456)|456\K)

Matches:

Match 1  apple
Match 2  banana
Match 3

JQuery find first parent element with specific class prefix

Use .closest() with a selector:

var $div = $('#divid').closest('div[class^="div-a"]');

SQL Server Regular expressions in T-SQL

You can use VBScript regular expression features using OLE Automation. This is way better than the overhead of creating and maintaining an assembly. Please make sure you go through the comments section to get a better modified version of the main one.

http://blogs.msdn.com/b/khen1234/archive/2005/05/11/416392.aspx

DECLARE @obj INT, @res INT, @match BIT;
DECLARE @pattern varchar(255) = '<your regex pattern goes here>';
DECLARE @matchstring varchar(8000) = '<string to search goes here>';
SET @match = 0;

-- Create a VB script component object
EXEC @res = sp_OACreate 'VBScript.RegExp', @obj OUT;

-- Apply/set the pattern to the RegEx object
EXEC @res = sp_OASetProperty @obj, 'Pattern', @pattern;

-- Set any other settings/properties here
EXEC @res = sp_OASetProperty @obj, 'IgnoreCase', 1;

-- Call the method 'Test' to find a match
EXEC @res = sp_OAMethod @obj, 'Test', @match OUT, @matchstring;

-- Don't forget to clean-up
EXEC @res = sp_OADestroy @obj;

If you get SQL Server blocked access to procedure 'sys.sp_OACreate'... error, use sp_reconfigure to enable Ole Automation Procedures. (Yes, unfortunately that is a server level change!)

More information about the Test method is available here

Happy coding

How does bitshifting work in Java?

You can use e.g. this API if you would like to see bitString presentation of your numbers. Uncommons Math

Example (in jruby)

bitString = org.uncommons.maths.binary.BitString.new(java.math.BigInteger.new("12").toString(2))
bitString.setBit(1, true)
bitString.toNumber => 14

edit: Changed api link and add a little example

HTML Script tag: type or language (or omit both)?

The language attribute has been deprecated for a long time, and should not be used.

When W3C was working on HTML5, they discovered all browsers have "text/javascript" as the default script type, so they standardized it to be the default value. Hence, you don't need type either.

For pages in XHTML 1.0 or HTML 4.01 omitting type is considered invalid. Try validating the following:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://example.com/test.js"></script>
</head>
<body/>
</html>

You will be informed of the following error:

Line 4, Column 41: required attribute "type" not specified

So if you're a fan of standards, use it. It should have no practical effect, but, when in doubt, may as well go by the spec.

Fastest way to iterate over all the chars in a String

String.toCharArray() creates new char array, means allocation of memory of string length, then copies original char array of string using System.arraycopy() and then returns this copy to caller. String.charAt() returns character at position i from original copy, that's why String.charAt() will be faster than String.toCharArray(). Although, String.toCharArray() returns copy and not char from original String array, where String.charAt() returns character from original char array. Code below returns value at the specified index of this string.

public char charAt(int index) {
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index];
}

code below returns a newly allocated character array whose length is the length of this string

public char[] toCharArray() {
    // Cannot use Arrays.copyOf because of class initialization order issues
    char result[] = new char[value.length];
    System.arraycopy(value, 0, result, 0, value.length);
    return result;
}

Why does this AttributeError in python occur?

AttributeError is raised when attribute of the object is not available.

An attribute reference is a primary followed by a period and a name:

attributeref ::= primary "." identifier

To return a list of valid attributes for that object, use dir(), e.g.:

dir(scipy)

So probably you need to do simply: import scipy.sparse

Reset auto increment counter in postgres

To set the sequence counter:

setval('product_id_seq', 1453);

If you don't know the sequence name use the pg_get_serial_sequence function:

select pg_get_serial_sequence('product', 'id');
 pg_get_serial_sequence 
------------------------
 public.product_id_seq

The parameters are the table name and the column name.

Or just issue a \d product at the psql prompt:

=> \d product
                         Table "public.product"
 Column |  Type   |                      Modifiers                       
--------+---------+------------------------------------------------------
 id     | integer | not null default nextval('product_id_seq'::regclass)
 name   | text    | 

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

I did a small benchmark on this topic. While many of the other posters have made good points about compatibility, my experience has been that PyPy isn't that much faster for just moving around bits. For many uses of Python, it really only exists to translate bits between two or more services. For example, not many web applications are performing CPU intensive analysis of datasets. Instead, they take some bytes from a client, store them in some sort of database, and later return them to other clients. Sometimes the format of the data is changed.

The BDFL and the CPython developers are a remarkably intelligent group of people and have a managed to help CPython perform excellent in such a scenario. Here's a shameless blog plug: http://www.hydrogen18.com/blog/unpickling-buffers.html . I'm using Stackless, which is derived from CPython and retains the full C module interface. I didn't find any advantage to using PyPy in that case.

Cast object to interface in TypeScript

There's no casting in javascript, so you cannot throw if "casting fails".
Typescript supports casting but that's only for compilation time, and you can do it like this:

const toDo = <IToDoDto> req.body;
// or
const toDo = req.body as IToDoDto;

You can check at runtime if the value is valid and if not throw an error, i.e.:

function isToDoDto(obj: any): obj is IToDoDto {
    return typeof obj.description === "string" && typeof obj.status === "boolean";
}

@Post()
addToDo(@Response() res, @Request() req) {
    if (!isToDoDto(req.body)) {
        throw new Error("invalid request");
    }

    const toDo = req.body as IToDoDto;
    this.toDoService.addToDo(toDo);
    return res.status(HttpStatus.CREATED).end();
}

Edit

As @huyz pointed out, there's no need for the type assertion because isToDoDto is a type guard, so this should be enough:

if (!isToDoDto(req.body)) {
    throw new Error("invalid request");
}

this.toDoService.addToDo(req.body);

The connection to adb is down, and a severe error has occurred

Reinstall everything??? no way! just add the path to SDK tools and platform tools in your classpath from Environment Variables. Then restart Eclipse.

other way go to Devices -> Reset adb, or simply open the task manager and kill the adb.exe process.

Getting DOM node from React child element

React.findDOMNode(this.refs.myExample) mentioned in another answer has been deprectaed.

use ReactDOM.findDOMNode from 'react-dom' instead

import ReactDOM from 'react-dom'
let myExample = ReactDOM.findDOMNode(this.refs.myExample)

How to do a regular expression replace in MySQL?

I think there is an easy way to achieve this and It's working fine for me.

To SELECT rows using REGEX

SELECT * FROM `table_name` WHERE `column_name_to_find` REGEXP 'string-to-find'

To UPDATE rows using REGEX

UPDATE `table_name` SET column_name_to_find=REGEXP_REPLACE(column_name_to_find, 'string-to-find', 'string-to-replace') WHERE column_name_to_find REGEXP 'string-to-find'

REGEXP Reference: https://www.geeksforgeeks.org/mysql-regular-expressions-regexp/

Is there a performance difference between i++ and ++i in C?

From Efficiency versus intent by Andrew Koenig :

First, it is far from obvious that ++i is more efficient than i++, at least where integer variables are concerned.

And :

So the question one should be asking is not which of these two operations is faster, it is which of these two operations expresses more accurately what you are trying to accomplish. I submit that if you are not using the value of the expression, there is never a reason to use i++ instead of ++i, because there is never a reason to copy the value of a variable, increment the variable, and then throw the copy away.

So, if the resulting value is not used, I would use ++i. But not because it is more efficient: because it correctly states my intent.

Is there any ASCII character for <br>?

& is a character; &amp; is a HTML character entity for that character.

<br> is an element. Elements don't get character entities.

In contrast to many answers here, \n or &#13; are not equivalent to <br>. The former denotes a line break in text documents. The latter is intended to denote a line break in HTML documents and is doing that by virtue of its default CSS:

br:before { content: "\A"; white-space: pre-line }

A textual line break can be rendered as an HTML line break or can be treated as whitespace, depending on the CSS white-space property.

Set a default parameter value for a JavaScript function

Sounds of Future

In future, you will be able to "spread" one object to another (currently as of 2019 NOT supported by Edge!) - demonstration how to use that for nice default options regardless of order:

_x000D_
_x000D_
function test(options) {
    var options = {
       // defaults
       url: 'defaultURL',
       some: 'somethingDefault',
       // override with input options
       ...options
    };
    
    var body = document.getElementsByTagName('body')[0];
    body.innerHTML += '<br>' + options.url + ' : ' + options.some;
}
test();
test({});
test({url:'myURL'});
test({some:'somethingOfMine'});
test({url:'overrideURL', some:'andSomething'});
test({url:'overrideURL', some:'andSomething', extra:'noProblem'});
_x000D_
_x000D_
_x000D_

MDN reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

...meanwhile what Edge DOES support is Object.assign() (IE does not, but I really hope we can leave IE behind :) )

Similarly you could do

_x000D_
_x000D_
    function test(options) {
        var options = Object.assign({
           // defaults
           url: 'defaultURL',
           some: 'somethingDefault',
        }, options); // override with input options
        
        var body = document.getElementsByTagName('body')[0];
        body.innerHTML += '<br>' + options.url + ' : ' + options.some;
    }
    test();
    test({});
    test({url:'myURL'});
    test({some:'somethingOfMine'});
    test({url:'overrideURL', some:'andSomething'});
    test({url:'overrideURL', some:'andSomething', extra:'noProblem'});
_x000D_
_x000D_
_x000D_

EDIT: Due to comments regarding const options - the problem with using constant options in the rest of the function is actually not that you can't do that, is just that you can't use the constant variable in its own declaration - you would have to adjust the input naming to something like

function test(input_options){
   const options = {
     // defaults
     someKey:    'someDefaultValue',
     anotherKey: 'anotherDefaultValue',

     // merge-in input options
     ...input_options
   };

   // from now on use options with no problem
}

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

Upgraded from EF5 to EF6 nuget a while back and kept encountering this issue. I'd temp fix it by updating the generated code to reference System.Data.Entity.Core.Objects, but after generation it would be changed back again (as expected since its generated).

This solved the problem for good:

http://msdn.microsoft.com/en-us/data/upgradeef6

If you have any models created with the EF Designer, you will need to update the code generation templates to generate EF6 compatible code. Note: There are currently only EF 6.x DbContext Generator templates available for Visual Studio 2012 and 2013.

  1. Delete existing code-generation templates. These files will typically be named <edmx_file_name>.tt and <edmx_file_name>.Context.tt and be nested under your edmx file in Solution Explorer. You can select the templates in Solution Explorer and press the Del key to delete them.
    Note: In Web Site projects the templates will not be nested under your edmx file, but listed alongside it in Solution Explorer.
    Note: In VB.NET projects you will need to enable 'Show All Files' to be able to see the nested template files.
  2. Add the appropriate EF 6.x code generation template. Open your model in the EF Designer, right-click on the design surface and select Add Code Generation Item...
    • If you are using the DbContext API (recommended) then EF 6.x DbContext Generator will be available under the Data tab.
      Note: If you are using Visual Studio 2012, you will need to install the EF 6 Tools to have this template. See Get Entity Framework for details.
    • If you are using the ObjectContext API then you will need to select the Online tab and search for EF 6.x EntityObject Generator.
  3. If you applied any customizations to the code generation templates you will need to re-apply them to the updated templates.

Reloading/refreshing Kendo Grid

You may try:

    $('#GridName').data('kendoGrid').dataSource.read();
$('#GridName').data('kendoGrid').refresh();

How can I run a program from a batch file without leaving the console open after the program starts?

Look at the START command, you can do this:

START rest-of-your-program-name

For instance, this batch-file will wait until notepad exits:

@echo off
notepad c:\test.txt

However, this won't:

@echo off
start notepad c:\test.txt

Android, How to create option Menu

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

And you should also have the onCreate method in your activity

Add an index (numeric ID) column to large data frame

Using alternative dplyr package:

library("dplyr") # or library("tidyverse")

df <- df %>% mutate(id = row_number())

Disabling buttons on react native

You can enable and disable button or by using condition or directly by default it will be disable : true

 // in calling function of button 
    handledisableenable()
        {
         // set the state for disabling or enabling the button
           if(ifSomeConditionReturnsTrue)
            {
                this.setState({ Isbuttonenable : true })
            }
          else
          {
             this.setState({ Isbuttonenable : false})
          }
        }

<TouchableOpacity onPress ={this.handledisableenable} disabled= 
     {this.state.Isbuttonenable}>

    <Text> Button </Text>
</TouchableOpacity>

How to show image using ImageView in Android

shoud be @drawable/image where image could have any extension like: image.png, image.xml, image.gif. Android will automatically create a reference in R class with its name, so you cannot have in any drawable folder image.png and image.gif.

SQL query to find third highest salary in company

Below query will give accurate answer. Follow and give me comments:

select top 1 salary from (
select DISTINCT  top 3 salary from Table(table name) order by salary  ) as comp
order by personid salary 

LINQ Orderby Descending Query

Just to show it in a different format that I prefer to use for some reason: The first way returns your itemList as an System.Linq.IOrderedQueryable

using(var context = new ItemEntities())
{
    var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
                                .OrderByDescending(x => x.Delivery.SubmissionDate);
}

That approach is fine, but if you wanted it straight into a List Object:

var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
                                .OrderByDescending(x => x.Delivery.SubmissionDate).ToList();

All you have to do is append a .ToList() call to the end of the Query.

Something to note, off the top of my head I can't recall if the !(not) expression is acceptable in the Where() call.

How do you debug React Native?

Very simple just two commands

For IOS $ react-native log-ios
For Android $ react-native log-android

Run a mySQL query as a cron job?

This was a very handy page as I have a requirement to DELETE records from a mySQL table where the expiry date is < Today.

I am on a shared host and CRON did not like the suggestion AndrewKDay. it also said (and I agree) that exposing the password in this way could be insecure.

I then tried turning Events ON in phpMyAdmin but again being on a shared host this was a no no. Sorry fancyPants.

So I turned to embedding the SQL script in a PHP file. I used the example [here][1]

[1]: https://www.w3schools.com/php/php_mysql_create_table.asp stored it in a sub folder somewhere safe and added an empty index.php for good measure. I was then able to test that this PHP file (and my SQL script) was working from the browser URL line.

All good so far. On to CRON. Following the above example almost worked. I ended up calling PHP before the path for my *.php file. Otherwise CRON didn't know what to do with the file.

my cron is set to run once per day and looks like this, modified for security.

00 * * * * php mywebsiteurl.com/wp-content/themes/ForteChildTheme/php/DeleteExpiredAssessment.php

For the final testing with CRON I initially set it to run each minute and had email alerts turned on. This quickly confirmed that it was running as planned and I changed it back to once per day.

Hope this helps.

How is attr_accessible used in Rails 4?

If you prefer attr_accessible, you could use it in Rails 4 too. You should install it like gem:

gem 'protected_attributes'

after that you could use attr_accessible in you models like in Rails 3

Also, and i think that is the best way- using form objects for dealing with mass assignment, and saving nested objects, and you can also use protected_attributes gem that way

class NestedForm
   include  ActiveModel::MassAssignmentSecurity
   attr_accessible :name,
                   :telephone, as: :create_params
   def create_objects(params)
      SomeModel.new(sanitized_params(params, :create_params))
   end
end

Get top n records for each group of grouped results

In other databases you can do this using ROW_NUMBER. MySQL doesn't support ROW_NUMBER but you can use variables to emulate it:

SELECT
    person,
    groupname,
    age
FROM
(
    SELECT
        person,
        groupname,
        age,
        @rn := IF(@prev = groupname, @rn + 1, 1) AS rn,
        @prev := groupname
    FROM mytable
    JOIN (SELECT @prev := NULL, @rn := 0) AS vars
    ORDER BY groupname, age DESC, person
) AS T1
WHERE rn <= 2

See it working online: sqlfiddle


Edit I just noticed that bluefeet posted a very similar answer: +1 to him. However this answer has two small advantages:

  1. It it is a single query. The variables are initialized inside the SELECT statement.
  2. It handles ties as described in the question (alphabetical order by name).

So I'll leave it here in case it can help someone.

Dynamic require in RequireJS, getting "Module name has not been loaded yet for context" error?

The limitation relates to the simplified CommonJS syntax vs. the normal callback syntax:

Loading a module is inherently an asynchronous process due to the unknown timing of downloading it. However, RequireJS in emulation of the server-side CommonJS spec tries to give you a simplified syntax. When you do something like this:

var foomodule = require('foo');
// do something with fooModule

What's happening behind the scenes is that RequireJS is looking at the body of your function code and parsing out that you need 'foo' and loading it prior to your function execution. However, when a variable or anything other than a simple string, such as your example...

var module = require(path); // Call RequireJS require

...then Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax;

var moduleName = 'foo';
require([moduleName], function(fooModule){
    // do something with fooModule
})

Given the above, here is one possible rewrite of your 2nd example to use the standard syntax:

define(['dyn_modules'], function (dynModules) {
    require(dynModules, function(){
        // use arguments since you don't know how many modules you're getting in the callback
        for (var i = 0; i < arguments.length; i++){
            var mymodule = arguments[i];
            // do something with mymodule...
        }
    });

});

EDIT: From your own answer, I see you're using underscore/lodash, so using _.values and _.object can simplify the looping through arguments array as above.

Insert all values of a table into another table in SQL

 Dim ofd As New OpenFileDialog
                ofd.Filter = "*.mdb|*.MDB"
                ofd.FilterIndex = (2)
                ofd.FileName = "bd1.mdb"
                ofd.Title = "SELECCIONE LA BASE DE DATOS ORIGEN (bd1.mdb)"
                ofd.ShowDialog()
                Dim conexion1 = "Driver={Microsoft Access Driver (*.mdb)};DBQ=" + ofd.FileName
                Dim conn As New OdbcConnection()
                conn.ConnectionString = conexion1
                conn.Open()



            'EN ESTE CODIGO SOLO SE AGREGAN LOS DATOS'
            Dim ofd2 As New OpenFileDialog
            ofd2.Filter = "*.mdb|*.MDB"
            ofd2.FilterIndex = (2)
            ofd2.FileName = "bd1.mdb"
            ofd2.Title = "SELECCIONE LA BASE DE DATOS DESTINO (bd1.mdb)"
            ofd2.ShowDialog()
            Dim conexion2 = "Driver={Microsoft Access Driver (*.mdb)};DBQ=" + ofd2.FileName
            Dim conn2 As New OdbcConnection()
            conn2.ConnectionString = conexion2
            Dim cmd2 As New OdbcCommand
            Dim CADENA2 As String

            CADENA2 = "INSERT INTO EXISTENCIA IN '" + ofd2.FileName + "' SELECT * FROM EXISTENCIA IN '" + ofd.FileName + "'"


            cmd2.CommandText = CADENA2
            cmd2.Connection = conn2
            conn2.Open()
            Dim dA2 As New OdbcDataAdapter
            dA2.SelectCommand = cmd2
            Dim midataset2 As New DataSet
            dA2.Fill(midataset2, "EXISTENCIA")

How to get english language word database?

There's no such thing as a "complete" list. Different people have different ways of measuring -- for example, they might include slang, neologisms, multi-word phrases, offensive terms, foreign words, verb conjugations, and so on. Some people have even counted a million words! So you'll have to decide what you want in a word list.

How to disable the ability to select in a DataGridView?

I'd go with this:

private void myDataGridView_SelectionChanged(Object sender, EventArgs e)
{
    dgvSomeDataGridView.ClearSelection();  
}

I don't agree with the broad assertion that no DataGridView should be unselectable. Some UIs are built for tools or touchsreens, and allowing a selection misleads the user to think that selecting will actually get them somewhere.

Setting ReadOnly = true on the control has no impact on whether a cell or row can be selected. And there are visual and functional downsides to setting Enabled = false.

Another option is to set the control selected colors to be exactly what the non-selected colors are, but if you happen to be manipulating the back color of the cell, then this method yields some nasty results as well.

Create intermediate folders if one doesn't exist

Use this code spinet for create intermediate folders if one doesn't exist while creating/editing file:

File outFile = new File("/dir1/dir2/dir3/test.file");
outFile.getParentFile().mkdirs();
outFile.createNewFile();

How do I iterate through the files in a directory in Java?

I like to use Optional and streams to have a net and clear solution, i use the below code to iterate over a directory. the below cases are handled by the code:

  1. handle the case of empty directory
  2. Laziness

but as mentioned by others, you still have to pay attention for outOfMemory in case you have huge folders

    File directoryFile = new File("put your path here");
    Stream<File> files = Optional.ofNullable(directoryFile// directoryFile
                                                          .listFiles(File::isDirectory)) // filter only directories(change with null if you don't need to filter)
                                 .stream()
                                 .flatMap(Arrays::stream);// flatmap from Stream<File[]> to Stream<File>

Grouping functions (tapply, by, aggregate) and the *apply family

In the collapse package recently released on CRAN, I have attempted to compress most of the common apply functionality into just 2 functions:

  1. dapply (Data-Apply) applies functions to rows or (default) columns of matrices and data.frames and (default) returns an object of the same type and with the same attributes (unless the result of each computation is atomic and drop = TRUE). The performance is comparable to lapply for data.frame columns, and about 2x faster than apply for matrix rows or columns. Parallelism is available via mclapply (only for MAC).

Syntax:

dapply(X, FUN, ..., MARGIN = 2, parallel = FALSE, mc.cores = 1L, 
       return = c("same", "matrix", "data.frame"), drop = TRUE)

Examples:

# Apply to columns:
dapply(mtcars, log)
dapply(mtcars, sum)
dapply(mtcars, quantile)
# Apply to rows:
dapply(mtcars, sum, MARGIN = 1)
dapply(mtcars, quantile, MARGIN = 1)
# Return as matrix:
dapply(mtcars, quantile, return = "matrix")
dapply(mtcars, quantile, MARGIN = 1, return = "matrix")
# Same for matrices ...
  1. BY is a S3 generic for split-apply-combine computing with vector, matrix and data.frame method. It is significantly faster than tapply, by and aggregate (an also faster than plyr, on large data dplyr is faster though).

Syntax:

BY(X, g, FUN, ..., use.g.names = TRUE, sort = TRUE,
   expand.wide = FALSE, parallel = FALSE, mc.cores = 1L,
   return = c("same", "matrix", "data.frame", "list"))

Examples:

# Vectors:
BY(iris$Sepal.Length, iris$Species, sum)
BY(iris$Sepal.Length, iris$Species, quantile)
BY(iris$Sepal.Length, iris$Species, quantile, expand.wide = TRUE) # This returns a matrix 
# Data.frames
BY(iris[-5], iris$Species, sum)
BY(iris[-5], iris$Species, quantile)
BY(iris[-5], iris$Species, quantile, expand.wide = TRUE) # This returns a wider data.frame
BY(iris[-5], iris$Species, quantile, return = "matrix") # This returns a matrix
# Same for matrices ...

Lists of grouping variables can also be supplied to g.

Talking about performance: A main goal of collapse is to foster high-performance programming in R and to move beyond split-apply-combine alltogether. For this purpose the package has a full set of C++ based fast generic functions: fmean, fmedian, fmode, fsum, fprod, fsd, fvar, fmin, fmax, ffirst, flast, fNobs, fNdistinct, fscale, fbetween, fwithin, fHDbetween, fHDwithin, flag, fdiff and fgrowth. They perform grouped computations in a single pass through the data (i.e. no splitting and recombining).

Syntax:

fFUN(x, g = NULL, [w = NULL,] TRA = NULL, [na.rm = TRUE,] use.g.names = TRUE, drop = TRUE)

Examples:

v <- iris$Sepal.Length
f <- iris$Species

# Vectors
fmean(v)             # mean
fmean(v, f)          # grouped mean
fsd(v, f)            # grouped standard deviation
fsd(v, f, TRA = "/") # grouped scaling
fscale(v, f)         # grouped standardizing (scaling and centering)
fwithin(v, f)        # grouped demeaning

w <- abs(rnorm(nrow(iris)))
fmean(v, w = w)      # Weighted mean
fmean(v, f, w)       # Weighted grouped mean
fsd(v, f, w)         # Weighted grouped standard-deviation
fsd(v, f, w, "/")    # Weighted grouped scaling
fscale(v, f, w)      # Weighted grouped standardizing
fwithin(v, f, w)     # Weighted grouped demeaning

# Same using data.frames...
fmean(iris[-5], f)                # grouped mean
fscale(iris[-5], f)               # grouped standardizing
fwithin(iris[-5], f)              # grouped demeaning

# Same with matrices ...

In the package vignettes I provide benchmarks. Programming with the fast functions is significantly faster than programming with dplyr or data.table, especially on smaller data, but also on large data.

Is it possible to install Xcode 10.2 on High Sierra (10.13.6)?

Yes it's possible. Follow these steps:

  1. Download Xcode 10.2 via this link (you need to be signed in with your Apple Id): https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_10.2/Xcode_10.2.xip and install it
  2. Edit Xcode.app/Contents/Info.plist and change the Minimum System Version to 10.13.6
  3. Do the same for Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/Info.plist (might require a restart of Xcode and/or Mac OS to make it open the simulator on run)
  4. Replace Xcode.app/Contents/Developer/usr/bin/xcodebuild with the one from 10.1 (or another version you have currently installed, such as 10.0).
  5. If there are problems with the simulator, reboot your Mac

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

I had a similar problem and tried everything suggested above. Then I tried changing the clientCreditialType to Basic and everything worked fine.

<basicHttpBinding>
    <binding name="BINDINGNAMEGOESHERE" >
      <security mode="TransportCredentialOnly">
        <transport clientCredentialType="Basic"></transport>
      </security>
    </binding>
  </basicHttpBinding>

C++ catching all exceptions

Be aware

try{
// ...
} catch (...) {
// ...
}

catches only language-level exceptions, other low-level exceptions/errors like Access Violation and Segmentation Fault wont be caught.

How to add icons to React Native app

You can import react-native-elements and use the font-awesome icons to your react native app

Install

npm install --save react-native-elements

then import that where you want to use icons

import { Icon } from 'react-native-elements'

Use it like

render() {
   return(
    <Icon
      reverse
      name='ios-american-football'
      type='ionicon'
      color='#517fa4'
    />
 );
}

Get first word of string

I 'm using this :

function getFirstWord(str) {
        let spaceIndex = str.indexOf(' ');
        return spaceIndex === -1 ? str : str.substr(0, spaceIndex);
    };

Android global variable

You can extend the base android.app.Application class and add member variables like so:

public class MyApplication extends Application {

    private String someVariable;

    public String getSomeVariable() {
        return someVariable;
    }

    public void setSomeVariable(String someVariable) {
        this.someVariable = someVariable;
    }
}

In your android manifest you must declare the class implementing android.app.Application (add the android:name=".MyApplication" attribute to the existing application tag):

<application 
  android:name=".MyApplication" 
  android:icon="@drawable/icon" 
  android:label="@string/app_name">

Then in your activities you can get and set the variable like so:

// set
((MyApplication) this.getApplication()).setSomeVariable("foo");

// get
String s = ((MyApplication) this.getApplication()).getSomeVariable();

How do I create a dynamic key to be added to a JavaScript object variable

Square brackets:

jsObj['key' + i] = 'example' + 1;

In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0", "5", "207", and so on, are all treated specially in that their existence determines the value of length. And, on top of that, the value of length can be set to remove such properties. Setting the length of an array to 0 effectively removes all properties whose names look like whole numbers.

OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ] operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.

Thus, the way the [ ] operator works in a for loop iterating through an array:

for (var i = 0; i < myArray.length; ++i) {
  var value = myArray[i]; // property access
  // ...
}

is really no different from the way [ ] works when accessing a property whose name is some computed string:

var value = jsObj["key" + i];

The [ ] operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.

When setting property values using [ ], the story is the same except for the special behavior around maintaining the length property. If you set a property with a numeric key on an array instance:

myArray[200] = 5;

then (assuming that "200" is the biggest numeric property name) the length property will be updated to 201 as a side-effect of the property assignment. If the same thing is done to a plain object, however:

myObj[200] = 5;

there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5 in otherwise the exact same way.

One might think that because that length behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:

var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;

var objJSON = JSON.stringify(obj);

the value of "objJSON" will be a string containing just ["hello world"]; the "something" property will be lost.

ES2015:

If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:

var key = 'DYNAMIC_KEY',
    obj = {
        [key]: 'ES6!'
    };

console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }

nodejs mongodb object id to string

When using mongoose .

A representation of the _id is usually in the form (recieved client side)

{ _id: { _bsontype: 'ObjectID', id: <Buffer 5a f1 8f 4b c7 17 0e 76 9a c0 97 aa> },

As you can see there's a buffer in there. The easiest way to convert it is just doing <obj>.toString() or String(<obj>._id)

So for example

var mongoose = require('mongoose')
mongoose.connect("http://localhost/test")
var personSchema = new mongoose.Schema({ name: String })
var Person = mongoose.model("Person", personSchema)
var guy = new Person({ name: "someguy" })
Person.find().then((people) =>{
  people.forEach(person => {
    console.log(typeof person._id) //outputs object
    typeof person._id == 'string'
      ? null
      : sale._id = String(sale._id)  // all _id s will be converted to strings
  })
}).catch(err=>{ console.log("errored") })

How can I send the "&" (ampersand) character via AJAX?

The preferred way is to use a JavaScript library such as jQuery and set your data option as an object, then let jQuery do the encoding, like this:

$.ajax({
  type: "POST",
  url: "/link.json",
  data: { value: poststr },
  error: function(){ alert('some error occured'); }
});

If you can't use jQuery (which is pretty much the standard these days), use encodeURIComponent.

How to calculate md5 hash of a file using javascript

To get the hash of files, there are a lot of options. Normally the problem is that it's really slow to get the hash of big files.

I created a little library that get the hash of files, with the 64kb of the start of the file and the 64kb of the end of it.

Live example: http://marcu87.github.com/hashme/ and library: https://github.com/marcu87/hashme

Count number of matches of a regex in Javascript

(('a a a').match(/b/g) || []).length; // 0
(('a a a').match(/a/g) || []).length; // 3

Based on https://stackoverflow.com/a/48195124/16777 but fixed to actually work in zero-results case.

How to use npm with node.exe?

I've just installed 64 bit Node.js v0.12.0 for Windows 8.1 from here. It's about 8MB and since it's an MSI you just double click to launch. It will automatically set up your environment paths etc.

Then to get the command line it's just [Win-Key]+[S] for search and then enter "node.js" as your search phrase.

Choose the Node.js Command Prompt entry NOT the Node.js entry.

Both will given you a command prompt but only the former will actually work. npm is built into that download so then just npm -whatever at prompt.

PPT to PNG with transparent background

Insert a coloured box the full size of the slide, set colour to white with 100% transparency. select all, right-click save as picture, select PNG and save.

copy/paste inserted colour box to each slide and repeat

Downloading jQuery UI CSS from Google's CDN

Google is hosting jQueryUI css at this link https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery.ui.all.css

If you look at this code directly, it is importing the css using @import which can be slow. You may want to factor the import into its parts to gain a slight performance benefit:

https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery.ui.base.css https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery.ui.theme.css

How to add jQuery to an HTML page?

You need to wrap this in script tags:

<script type='text/javascript'> ... your code ... </script>

That being said, it's important WHEN you execute this code. If you put this in the page BEFORE the HTML elements that it is hooking into then the script will run BEFORE the HTML is actually rendered in the page, so it will fail.

It is common practice to wrap this type of code in a "document ready" block, like so:

<script type='text/javascript'>
$(document).ready(function() {

... your code...

}}
</script>

This ensures that the entire page has rendered in the browser BEFORE your code is executed. It is also a best practice to put the code in the <head> section of your page.

How can I get (query string) parameters from the URL in Next.js?

url prop is deprecated as of Next.js version 6: https://github.com/zeit/next.js/blob/master/errors/url-deprecated.md

To get the query parameters, use getInitialProps:

For stateless components

import Link from 'next/link'
const About = ({query}) => (
  <div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>
)

About.getInitialProps = ({query}) => {
  return {query}
}

export default About;

For regular components

class About extends React.Component {

  static getInitialProps({query}) {
    return {query}
  }

  render() {
    console.log(this.props.query) // The query is available in the props object
    return <div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>

  }
}

The query object will be like: url.com?a=1&b=2&c=3 becomes: {a:1, b:2, c:3}

Double.TryParse or Convert.ToDouble - which is faster and safer?

Double.TryParse IMO.

It is easier for you to handle, You'll know exactly where the error occurred.

Then you can deal with it how you see fit if it returns false (i.e could not convert).

Call to undefined function curl_init().?

The CURL extension ext/curl is not installed or enabled in your PHP installation. Check the manual for information on how to install or enable CURL on your system.

How to encrypt and decrypt file in Android?

Use a CipherOutputStream or CipherInputStream with a Cipher and your FileInputStream / FileOutputStream.

I would suggest something like Cipher.getInstance("AES/CBC/PKCS5Padding") for creating the Cipher class. CBC mode is secure and does not have the vulnerabilities of ECB mode for non-random plaintexts. It should be present in any generic cryptographic library, ensuring high compatibility.

Don't forget to use a Initialization Vector (IV) generated by a secure random generator if you want to encrypt multiple files with the same key. You can prefix the plain IV at the start of the ciphertext. It is always exactly one block (16 bytes) in size.

If you want to use a password, please make sure you do use a good key derivation mechanism (look up password based encryption or password based key derivation). PBKDF2 is the most commonly used Password Based Key Derivation scheme and it is present in most Java runtimes, including Android. Note that SHA-1 is a bit outdated hash function, but it should be fine in PBKDF2, and does currently present the most compatible option.

Always specify the character encoding when encoding/decoding strings, or you'll be in trouble when the platform encoding differs from the previous one. In other words, don't use String.getBytes() but use String.getBytes(StandardCharsets.UTF_8).

To make it more secure, please add cryptographic integrity and authenticity by adding a secure checksum (MAC or HMAC) over the ciphertext and IV, preferably using a different key. Without an authentication tag the ciphertext may be changed in such a way that the change cannot be detected.

Be warned that CipherInputStream may not report BadPaddingException, this includes BadPaddingException generated for authenticated ciphers such as GCM. This would make the streams incompatible and insecure for these kind of authenticated ciphers.

How to automatically close cmd window after batch file execution?

This worked for me. I just wanted to close the command window automatically after exiting the game. I just double click on the .bat file on my desktop. No shortcuts.

taskkill /f /IM explorer.exe
C:\"GOG Games"\Starcraft\Starcraft.exe
start explorer.exe
exit /B

"Logging out" of phpMyAdmin?

The presence of the logout button depends on whether you are required to login or not, in the first place. This is tweakable in PHPMyAdmin config files.

Yet, I don't think that would change anything concerning your error message. You would need to fix the configuration for the message to go away.

Edit: this is the kind of solution you should be searching for. And here are plenty of others for you to explore ^^

How to calculate Date difference in Hive

If you need the difference in seconds (i.e.: you're comparing dates with timestamps, and not whole days), you can simply convert two date or timestamp strings in the format 'YYYY-MM-DD HH:MM:SS' (or specify your string date format explicitly) using unix_timestamp(), and then subtract them from each other to get the difference in seconds. (And can then divide by 60.0 to get minutes, or by 3600.0 to get hours, etc.)

Example:

UNIX_TIMESTAMP('2017-12-05 10:01:30') - UNIX_TIMESTAMP('2017-12-05 10:00:00') AS time_diff -- This will return 90 (seconds). Unix_timestamp converts string dates into BIGINTs. 

More on what you can do with unix_timestamp() here, including how to convert strings with different date formatting: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions

Check if an element is present in a Bash array

If array elements don't contain spaces, another (perhaps more readable) solution would be:

if echo ${arr[@]} | grep -q -w "d"; then 
    echo "is in array"
else 
    echo "is not in array"
fi

Allow multiple roles to access controller action

One possible simplification would be to subclass AuthorizeAttribute:

public class RolesAttribute : AuthorizeAttribute
{
    public RolesAttribute(params string[] roles)
    {
        Roles = String.Join(",", roles);
    }
}

Usage:

[Roles("members", "admin")]

Semantically it is the same as Jim Schmehil's answer.

Using Server.MapPath() inside a static field in ASP.NET MVC

I think you can try this for calling in from a class

 System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");

*----------------Sorry I oversight, for static function already answered the question by adrift*

System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Update

I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()

Solution (tested in static webmethod)

System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/"); Worked

How can I display the current branch and folder path in terminal?

for anyone still looking for this , i just installed ohmyz https://ohmyz.sh/#install and the branches it's showing enter image description here

git: undo all working dir changes including new files

You can do this in two steps:

  1. Revert modified files: git checkout -f
  2. Remove untracked files: git clean -fd

How to get absolute path to file in /resources folder of your project

There are two problems on our way to the absolute path:

  1. The placement found will be not where the source files lie, but where the class is saved. And the resource folder almost surely will lie somewhere in the source folder of the project.
  2. The same functions for retrieving the resource work differently if the class runs in a plugin or in a package directly in the workspace.

The following code will give us all useful paths:

    URL localPackage = this.getClass().getResource("");
    URL urlLoader = YourClassName.class.getProtectionDomain().getCodeSource().getLocation();
    String localDir = localPackage.getPath();
    String loaderDir = urlLoader.getPath();
    System.out.printf("loaderDir = %s\n localDir = %s\n", loaderDir, localDir);

Here both functions that can be used for localization of the resource folder are researched. As for class, it can be got in either way, statically or dynamically.


If the project is not in the plugin, the code if run in JUnit, will print:

loaderDir = /C:.../ws/source.dir/target/test-classes/
 localDir = /C:.../ws/source.dir/target/test-classes/package/

So, to get to src/rest/resources we should go up and down the file tree. Both methods can be used. Notice, we can't use getResource(resourceFolderName), for that folder is not in the target folder. Nobody puts resources in the created folders, I hope.


If the class is in the package that is in the plugin, the output of the same test will be:

loaderDir = /C:.../ws/plugin/bin/
 localDir = /C:.../ws/plugin/bin/package/

So, again we should go up and down the folder tree.


The most interesting is the case when the package is launched in the plugin. As JUnit plugin test, for our example. The output is:

loaderDir = /C:.../ws/plugin/
 localDir = /package/

Here we can get the absolute path only combining the results of both functions. And it is not enough. Between them we should put the local path of the place where the classes packages are, relatively to the plugin folder. Probably, you will have to insert something as src or src/test/resource here.

You can insert the code into yours and see the paths that you have.

What is the maximum length of a table name in Oracle?

In Oracle 12.1 and below: 30 char (bytes, really, as has been stated).

But do not trust me; try this for yourself:

SQL> create table I23456789012345678901234567890 (my_id number);

Table created.



SQL> create table I234567890123456789012345678901(my_id number);


ERROR at line 1:

ORA-00972: identifier is too long

Updated: as stated above, in Oracle 12.2 and later, the maximum object name length is now 128 bytes.

Updating .class file in jar

This tutorial details how to update a jar file

jar -uf jar-file <optional_folder_structure>/input-file(s)     

where 'u' means update.

How to access SVG elements with Javascript

In case you use jQuery you need to wait for $(window).load, because the embedded SVG document might not be yet loaded at $(document).ready

$(window).load(function () {

    //alert("Document loaded, including graphics and embedded documents (like SVG)");
    var a = document.getElementById("alphasvg");

    //get the inner DOM of alpha.svg
    var svgDoc = a.contentDocument;

    //get the inner element by id
    var delta = svgDoc.getElementById("delta");
    delta.addEventListener("mousedown", function(){ alert('hello world!')}, false);
});

what's the easiest way to put space between 2 side-by-side buttons in asp.net

#btnClear{margin-left:100px;}

Or add a class to the buttons and have:

.yourClass{margin-left:100px;}

This achieves this - http://jsfiddle.net/QU93w/

What are the proper permissions for an upload folder with PHP/Apache?

What is important is that the apache user and group should have minimum read access and in some cases execute access. For the rest you can give 0 access.

This is the most safe setting.

How to save RecyclerView's scroll position using RecyclerView.State?

I wanted to save Recycler View's scroll position when navigating away from my list activity and then clicking the back button to navigate back. Many of the solutions provided for this problem were either much more complicated than needed or didn't work for my configuration, so I thought I'd share my solution.

First save your instance state in onPause as many have shown. I think it's worth emphasizing here that this version of onSaveInstanceState is a method from the RecyclerView.LayoutManager class.

private LinearLayoutManager mLayoutManager;
Parcelable state;

        @Override
        public void onPause() {
            super.onPause();
            state = mLayoutManager.onSaveInstanceState();
        }

The key to getting this to work properly is to make sure you call onRestoreInstanceState after you attach your adapter, as some have indicated in other threads. However the actual method call is much simpler than many have indicated.

private void someMethod() {
    mVenueRecyclerView.setAdapter(mVenueAdapter);
    mLayoutManager.onRestoreInstanceState(state);
}

final keyword in method parameters

final means you can't change the value of that variable once it was assigned.

Meanwhile, the use of final for the arguments in those methods means it won't allow the programmer to change their value during the execution of the method. This only means that inside the method the final variables can not be reassigned.

MYSQL Sum Query with IF Condition

How about this?

SUM(IF(PaymentType = "credit card", totalamount, 0)) AS CreditCardTotal

Jenkins not executing jobs (pending - waiting for next executor)

For me I have to restart the executors manually. Click on "Dead" under "Build Executor Status" and push the restart button.

How to find out when a particular table was created in Oracle?

You copy and paste the following code. It will display all the tables with Name and Created Date

SELECT object_name,created FROM user_objects
WHERE object_name LIKE  '%table_name%'
AND object_type = 'TABLE'; 

Note: Replace '%table_name%' with the table name you are looking for.

Shrink a YouTube video to responsive width

If you are using Bootstrap you can also use a responsive embed. This will fully automate making the video(s) responsive.

http://getbootstrap.com/components/#responsive-embed

There's some example code below.

<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="..."></iframe>
</div>

<!-- 4:3 aspect ratio -->
<div class="embed-responsive embed-responsive-4by3">
  <iframe class="embed-responsive-item" src="..."></iframe>
</div>

Is it possible to iterate through JSONArray?

Not with an iterator.

For org.json.JSONArray, you can do:

for (int i = 0; i < arr.length(); i++) {
  arr.getJSONObject(i);
}

For javax.json.JsonArray, you can do:

for (int i = 0; i < arr.size(); i++) {
  arr.getJsonObject(i);
}

How do I get a file's directory using the File object?

In either case, I'd expect file.getParent() (or file.getParentFile()) to give you what you want.

Additionally, if you want to find out whether the original File does exist and is a directory, then exists() and isDirectory() are what you're after.

How to create Select List for Country and States/province in MVC

Designing You Model:

Public class ModelName
{
    ...// Properties
    public IEnumerable<SelectListItem> ListName { get; set; }
}

Prepare and bind List to Model in Controller :

    public ActionResult Index(ModelName model)
    {
        var items = // Your List of data
        model.ListName = items.Select(x=> new SelectListItem() {
                    Text = x.prop,
                    Value = x.prop2
               });
    }

In You View :

@Html.DropDownListFor(m => Model.prop2,Model.ListName)

What does "int 0x80" mean in assembly code?

It tells the cpu to activate interrupt vector 0x80, which on Linux OSes is the system-call interrupt, used to invoke system functions like open() for files, et cetera.

Angular 2: 404 error occur when I refresh through the browser

For people (like me) who really want PathLocationStrategy (i.e. html5Mode) instead of HashLocationStrategy, see How to: Configure your server to work with html5Mode from a third-party wiki:

When you have html5Mode enabled, the # character will no longer be used in your URLs. The # symbol is useful because it requires no server side configuration. Without #, the URL looks much nicer, but it also requires server side rewrites.

Here I only copy three examples from the wiki, in case the Wiki get lost. Other examples can be found by searching keyword "URL rewrite" (e.g. this answer for Firebase).

Apache

<VirtualHost *:80>
    ServerName my-app

    DocumentRoot /path/to/app

    <Directory /path/to/app>
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html to allow HTML5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>

Documentation for rewrite module

nginx

server {
    server_name my-app;

    root /path/to/app;

    location / {
        try_files $uri $uri/ /index.html;
    }
}

Documentation for try_files

IIS

<system.webServer>
  <rewrite>
    <rules> 
      <rule name="Main Rule" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

CryptographicException 'Keyset does not exist', but only through WCF

I hit this in my service fabric project after the cert used to authenticate against our key vault expired and was rotated, which changed the thumbprint. I got this error because I had missed updating the thumbprint in the applicationManifest.xml file in this block which precisely does what other answers have suggested - to given NETWORK SERVICE (which all my exes run as, standard config for azure servicefabric cluster) permissions to access the LOCALMACHINE\MY cert store location.

Note the "X509FindValue" attribute value.

_x000D_
_x000D_
<!-- this block added to allow low priv processes (such as service fabric processes) that run as NETWORK SERVICE to read certificates from the store -->_x000D_
  <Principals>_x000D_
    <Users>_x000D_
      <User Name="NetworkService" AccountType="NetworkService" />_x000D_
    </Users>_x000D_
  </Principals>_x000D_
  <Policies>_x000D_
    <SecurityAccessPolicies>_x000D_
      <SecurityAccessPolicy ResourceRef="AzureKeyvaultClientCertificate" PrincipalRef="NetworkService" GrantRights="Full" ResourceType="Certificate" />_x000D_
    </SecurityAccessPolicies>_x000D_
  </Policies>_x000D_
  <Certificates>_x000D_
    <SecretsCertificate X509FindValue="[[THIS KEY ALSO NEEDS TO BE UPDATED]]" Name="AzureKeyvaultClientCertificate" />_x000D_
  </Certificates>_x000D_
  <!-- end block -->
_x000D_
_x000D_
_x000D_

How to get a Color from hexadecimal Color String

If you define a color in your XML and want to use it to change background color or something this API is the one your are looking for:

 ((TextView) view).setBackgroundResource(R.drawable.your_color_here);

In my sample I used it for TestView

Simple DateTime sql query

Others have already said that date literals in SQL Server require being surrounded with single quotes, but I wanted to add that you can solve your month/day mixup problem two ways (that is, the problem where 25 is seen as the month and 5 the day) :

  1. Use an explicit Convert(datetime, 'datevalue', style) where style is one of the numeric style codes, see Cast and Convert. The style parameter isn't just for converting dates to strings but also for determining how strings are parsed to dates.

  2. Use a region-independent format for dates stored as strings. The one I use is 'yyyymmdd hh:mm:ss', or consider ISO format, yyyy-mm-ddThh:mi:ss.mmm. Based on experimentation, there are NO other language-invariant format string. (Though I think you can include time zone at the end, see the above link).

How to connect wireless network adapter to VMWare workstation?

Use a Linux Live cd/usb and boot an that to be able to directly connect to your wifi hardware or use linux as the main OS with direct access to the wifi card and then use windows as a guest os, I know that this maybe not the ideal way but it will work.

How to convert JTextField to String and String to JTextField?

The JTextField offers a getText() and a setText() method - those are for getting and setting the content of the text field.

Minimum and maximum value of z-index?

http://www.w3.org/TR/CSS21/visuren.html#z-index

'z-index'

Value: auto | <integer> | inherit

http://www.w3.org/TR/CSS21/syndata.html#numbers

Some value types may have integer values (denoted by <integer>) or real number values (denoted by <number>). Real numbers and integers are specified in decimal notation only. An <integer> consists of one or more digits "0" to "9". A <number> can either be an <integer>, or it can be zero or more digits followed by a dot (.) followed by one or more digits. Both integers and real numbers may be preceded by a "-" or "+" to indicate the sign. -0 is equivalent to 0 and is not a negative number.

Note that many properties that allow an integer or real number as a value actually restrict the value to some range, often to a non-negative value.

So basically there are no limitations for z-index value in the CSS standard, but I guess most browsers limit it to signed 32-bit values (-2147483648 to +2147483647) in practice (64 would be a little off the top, and it doesn't make sense to use anything less than 32 bits these days)

How to list all the files in android phone by using adb shell?

just to add the full command:

adb shell ls -R | grep filename

this is actually a pretty fast lookup on Android

How do I unlock a SQLite database?

I had this problem just now, using an SQLite database on a remote server, stored on an NFS mount. SQLite was unable to obtain a lock after the remote shell session I used had crashed while the database was open.

The recipes for recovery suggested above did not work for me (including the idea to first move and then copy the database back). But after copying it to a non-NFS system, the database became usable and not data appears to have been lost.

What is this spring.jpa.open-in-view=true property in Spring Boot?

This property will register an OpenEntityManagerInViewInterceptor, which registers an EntityManager to the current thread, so you will have the same EntityManager until the web request is finished. It has nothing to do with a Hibernate SessionFactory etc.

Is not an enclosing class Java

As stated in the docs:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Vuejs: v-model array in multiple input

If you were asking how to do it in vue2 and make options to insert and delete it, please, have a look an js fiddle

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    finds: [] _x000D_
  },_x000D_
  methods: {_x000D_
    addFind: function () {_x000D_
      this.finds.push({ value: 'def' });_x000D_
    },_x000D_
    deleteFind: function (index) {_x000D_
      console.log(index);_x000D_
      console.log(this.finds);_x000D_
      this.finds.splice(index, 1);_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <h1>Finds</h1>_x000D_
  <div v-for="(find, index) in finds">_x000D_
    <input v-model="find.value">_x000D_
    <button @click="deleteFind(index)">_x000D_
      delete_x000D_
    </button>_x000D_
  </div>_x000D_
  _x000D_
  <button @click="addFind">_x000D_
    New Find_x000D_
  </button>_x000D_
  _x000D_
  <pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is the best way to test for an empty string with jquery-out-of-the-box?

The link you gave seems to be attempting something different to the test you are trying to avoid repeating.

if (a == null || a=='')

tests if the string is an empty string or null. The article you linked to tests if the string consists entirely of whitespace (or is empty).

The test you described can be replaced by:

if (!a)

Because in javascript, an empty string, and null, both evaluate to false in a boolean context.

SSL InsecurePlatform error when using Requests package

I just had a similar issue on a CentOS 5 server where I installed python 2.7.12 in /usr/local on top of a much older version of python2.7. Upgrading to CentOS 6 or 7 isn't an option on this server right now.

Some of the python 2.7 modules were still existing from the older version of python, but pip was failing to upgrade because the newer cryptography package is not supported by the CentOS 5 packages.

Specifically, 'pip install requests[security]' was failing because the openssl version on the CentOS 5 was 0.9.8e which is no longer supported by cryptography > 1.4.0.

To solve the OPs original issue I did:

1) pip install 'cryptography<1.3.5,>1.3.0'.  

This installed cryptography 1.3.4 which works with openssl-0.9.8e. cryptograpy 1.3.4 is also sufficient to satisfy the requirement for the following command.

2) pip install 'requests[security]'

This command now installs because it doesn't try to install cryptography > 1.4.0.

Note that on Centos 5 I also needed to:

yum install openssl-devel

To allow cryptography to build

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

My problem was with TIMEZONE in emulator genymotion. Change TIMEZONE ANDROID EMULATOR equal TIMEZONE SERVER, solved problem.

reference

Spring default behavior for lazy-init

For those coming here and are using Java config you can set the Bean to lazy-init using annotations like this:

In the configuration class:

@Configuration
// @Lazy - For all Beans to load lazily
public class AppConf {

    @Bean
    @Lazy
    public Demo demo() {
        return new Demo();
    }
}

For component scanning and auto-wiring:

@Component
@Lazy
public class Demo {
    ....
    ....
}

@Component
public class B {

    @Autowired
    @Lazy // If this is not here, Demo will still get eagerly instantiated to satisfy this request.
    private Demo demo;

    .......
 }

Hide axis and gridlines Highcharts

If you doesn't want to touch the config object, you just hide the grid by css:

.chart-container .highcharts-grid {
   display: none;
}

Test if remote TCP port is open from a shell script

With netcat you can check whether a port is open like this:

nc my.example.com 80 < /dev/null

The return value of nc will be success if the TCP port was opened, and failure (typically the return code 1) if it could not make the TCP connection.

Some versions of nc will hang when you try this, because they do not close the sending half of their socket even after receiving the end-of-file from /dev/null. On my own Ubuntu laptop (18.04), the netcat-openbsd version of netcat that I have installed offers a workaround: the -N option is necessary to get an immediate result:

nc -N my.example.com 80 < /dev/null

Javascript Regex: How to put a variable inside a regular expression?

const regex = new RegExp(`ReGeX${testVar}ReGeX`);
...
string.replace(regex, "replacement");

Update

Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)

ES6 Update

In 2019, this would usually be written using a template string, and the above code has been updated. The original answer was:

var regex = new RegExp("ReGeX" + testVar + "ReGeX");
...
string.replace(regex, "replacement");

WPF What is the correct way of using SVG files as icons in WPF

Your technique will depend on what XAML object your SVG to XAML converter produces. Does it produce a Drawing? An Image? A Grid? A Canvas? A Path? A Geometry? In each case your technique will be different.

In the examples below I will assume you are using your icon on a button, which is the most common scenario, but note that the same techniques will work for any ContentControl.

Using a Drawing as an icon

To use a Drawing, paint an approriately-sized rectangle with a DrawingBrush:

<Button>
  <Rectangle Width="100" Height="100">
    <Rectangle.Fill>
      <DrawingBrush>
        <DrawingBrush.Drawing>

          <Drawing ... /> <!-- Converted from SVG -->

        </DrawingBrush.Drawing>
      </DrawingBrush>
    </Rectangle.Fill>
  </Rectangle>
</Button>

Using an Image as an icon

An image can be used directly:

<Button>
  <Image ... />  <!-- Converted from SVG -->
</Button>

Using a Grid as an icon

A grid can be used directly:

<Button>
  <Grid ... />  <!-- Converted from SVG -->
</Button>

Or you can include it in a Viewbox if you need to control the size:

<Button>
  <Viewbox ...>
    <Grid ... />  <!-- Converted from SVG -->
  </Viewbox>
</Button>

Using a Canvas as an icon

This is like using an image or grid, but since a canvas has no fixed size you need to specify the height and width (unless these are already set by the SVG converter):

<Button>
  <Canvas Height="100" Width="100">  <!-- Converted from SVG, with additions -->
  </Canvas>
</Button>

Using a Path as an icon

You can use a Path, but you must set the stroke or fill explicitly:

<Button>
  <Path Stroke="Red" Data="..." /> <!-- Converted from SVG, with additions -->
</Button>

or

<Button>
  <Path Fill="Blue" Data="..." /> <!-- Converted from SVG, with additions -->
</Button>

Using a Geometry as an icon

You can use a Path to draw your geometry. If it should be stroked, set the Stroke:

<Button>
  <Path Stroke="Red" Width="100" Height="100">
    <Path.Data>
      <Geometry ... /> <!-- Converted from SVG -->
    </Path.Data>
  </Path>
</Button>

or if it should be filled, set the Fill:

<Button>
  <Path Fill="Blue" Width="100" Height="100">
    <Path.Data>
      <Geometry ... /> <!-- Converted from SVG -->
    </Path.Data>
  </Path>
</Button>

How to data bind

If you're doing the SVG -> XAML conversion in code and want the resulting XAML to appear using data binding, use one of the following:

Binding a Drawing:

<Button>
  <Rectangle Width="100" Height="100">
    <Rectangle.Fill>
      <DrawingBrush Drawing="{Binding Drawing, Source={StaticResource ...}}" />
    </Rectangle.Fill>
  </Rectangle>
</Button>

Binding an Image:

<Button Content="{Binding Image}" />

Binding a Grid:

<Button Content="{Binding Grid}" />

Binding a Grid in a Viewbox:

<Button>
  <Viewbox ...>
    <ContentPresenter Content="{Binding Grid}" />
  </Viewbox>
</Button>

Binding a Canvas:

<Button>
  <ContentPresenter Height="100" Width="100" Content="{Binding Canvas}" />
</Button>

Binding a Path:

<Button Content="{Binding Path}" />  <!-- Fill or stroke must be set in code unless set by the SVG converter -->

Binding a Geometry:

<Button>
  <Path Width="100" Height="100" Data="{Binding Geometry}" />
</Button>

Multiple submit buttons in the same form calling different Servlets

There are several ways to achieve this.

Probably the easiest would be to use JavaScript to change the form's action.

<input type="submit" value="SecondServlet" onclick="form.action='SecondServlet';">

But this of course won't work when the enduser has JS disabled (mobile browsers, screenreaders, etc).


Another way is to put the second button in a different form, which may or may not be what you need, depending on the concrete functional requirement, which is not clear from the question at all.

<form action="FirstServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" value="FirstServlet">
</form>
<form action="SecondServlet" method="Post">
    <input type="submit"value="SecondServlet">
</form>

Note that a form would on submit only send the input data contained in the very same form, not in the other form.


Again another way is to just create another single entry point servlet which delegates further to the right servlets (or preferably, the right business actions) depending on the button pressed (which is by itself available as a request parameter by its name):

<form action="MainServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" name="action" value="FirstServlet">
    <input type="submit" name="action" value="SecondServlet">
</form>

with the following in MainServlet

String action = request.getParameter("action");

if ("FirstServlet".equals(action)) {
    // Invoke FirstServlet's job here.
} else if ("SecondServlet".equals(action)) {
    // Invoke SecondServlet's job here.
}

This is only not very i18n/maintenance friendly. What if you need to show buttons in a different language or change the button values while forgetting to take the servlet code into account?


A slight change is to give the buttons its own fixed and unique name, so that its presence as request parameter could be checked instead of its value which would be sensitive to i18n/maintenance:

<form action="MainServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" name="first" value="FirstServlet">
    <input type="submit" name="second" value="SecondServlet">
</form>

with the following in MainServlet

if (request.getParameter("first") != null) {
    // Invoke FirstServlet's job here.
} else if (request.getParameter("second") != null) {
    // Invoke SecondServlet's job here.
}

Last way would be to just use a MVC framework like JSF so that you can directly bind javabean methods to buttons, but that would require drastic changes to your existing code.

<h:form>
    Last Name: <h:inputText value="#{bean.lastName}" size="20" />
    <br/><br/>
    <h:commandButton value="First" action="#{bean.first}" />
    <h:commandButton value="Second" action="#{bean.Second}" />
</h:form>

with just the following javabean instead of a servlet

@ManagedBean
@RequestScoped
public class Bean {

    private String lastName; // +getter+setter

    public void first() {
        // Invoke original FirstServlet's job here.
    }

    public void second() {
        // Invoke original SecondServlet's job here.
    }

}

The entity cannot be constructed in a LINQ to Entities query

You can project into anonymous type, and then from it to model type

public IEnumerable<Product> GetProducts(int categoryID)
{
    return (from p in Context.Set<Product>()
            where p.CategoryID == categoryID
            select new { Name = p.Name }).ToList()
           .Select(x => new Product { Name = x.Name });
}

Edit: I am going to be a bit more specific since this question got a lot of attention.

You cannot project into model type directly (EF restriction), so there is no way around this. The only way is to project into anonymous type (1st iteration), and then to model type (2nd iteration).

Please also be aware that when you partially load entities in this manner, they cannot be updated, so they should remain detached, as they are.

I never did completely understand why this is not possible, and the answers on this thread do not give strong reasons against it (mostly speaking about partially loaded data). It is correct that in partially loaded state entity cannot be updated, but then, this entity would be detached, so accidental attempts to save them would not be possible.

Consider method I used above: we still have a partially loaded model entity as a result. This entity is detached.

Consider this (wish-to-exist) possible code:

return (from p in Context.Set<Product>()
        where p.CategoryID == categoryID
        select new Product { Name = p.Name }).AsNoTracking().ToList();

This could also result in a list of detached entities, so we would not need to make two iterations. A compiler would be smart to see that AsNoTracking() has been used, which will result in detached entities, so it could allow us to do this. If, however, AsNoTracking() was omitted, it could throw the same exception as it is throwing now, to warn us that we need to be specific enough about the result we want.

Regex to replace everything except numbers and a decimal point

Use this:

document.getElementById(target).value = newVal.replace(/[^0-9.]/g, '');

Resizing image in Java

We're doing this to create thumbnails of images:

  BufferedImage tThumbImage = new BufferedImage( tThumbWidth, tThumbHeight, BufferedImage.TYPE_INT_RGB );
  Graphics2D tGraphics2D = tThumbImage.createGraphics(); //create a graphics object to paint to
  tGraphics2D.setBackground( Color.WHITE );
  tGraphics2D.setPaint( Color.WHITE );
  tGraphics2D.fillRect( 0, 0, tThumbWidth, tThumbHeight );
  tGraphics2D.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR );
  tGraphics2D.drawImage( tOriginalImage, 0, 0, tThumbWidth, tThumbHeight, null ); //draw the image scaled

  ImageIO.write( tThumbImage, "JPG", tThumbnailTarget ); //write the image to a file

Can't connect to local MySQL server through socket '/tmp/mysql.sock

Looked around online too long not to contribute. After trying to type in the mysql prompt from the command line, I was continuing to receive this message:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

This was due to the fact that my local mysql server was no longer running. In order to restart the server, I navigated to

shell> cd /user/local/bin

where my mysql.server was located. From here, simply type:

shell> mysql.server start

This will relaunch the local mysql server.

From there you can reset the root password if need be..

mysql> UPDATE mysql.user SET Password=PASSWORD('MyNewPass')
->                   WHERE User='root';
mysql> FLUSH PRIVILEGES;

How to add image in a TextView text?

com/xyz/customandroid/ TextViewWithImages .java:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.text.Spannable;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;

public class TextViewWithImages extends TextView {

    public TextViewWithImages(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    public TextViewWithImages(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public TextViewWithImages(Context context) {
        super(context);
    }
    @Override
    public void setText(CharSequence text, BufferType type) {
        Spannable s = getTextWithImages(getContext(), text);
        super.setText(s, BufferType.SPANNABLE);
    }

    private static final Spannable.Factory spannableFactory = Spannable.Factory.getInstance();

    private static boolean addImages(Context context, Spannable spannable) {
        Pattern refImg = Pattern.compile("\\Q[img src=\\E([a-zA-Z0-9_]+?)\\Q/]\\E");
        boolean hasChanges = false;

        Matcher matcher = refImg.matcher(spannable);
    while (matcher.find()) {
        boolean set = true;
        for (ImageSpan span : spannable.getSpans(matcher.start(), matcher.end(), ImageSpan.class)) {
            if (spannable.getSpanStart(span) >= matcher.start()
             && spannable.getSpanEnd(span) <= matcher.end()
               ) {
                spannable.removeSpan(span);
            } else {
                set = false;
                break;
            }
        }
        String resname = spannable.subSequence(matcher.start(1), matcher.end(1)).toString().trim();
        int id = context.getResources().getIdentifier(resname, "drawable", context.getPackageName());
        if (set) {
            hasChanges = true;
            spannable.setSpan(  new ImageSpan(context, id),
                                matcher.start(),
                                matcher.end(),
                                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                             );
        }
    }

        return hasChanges;
    }
    private static Spannable getTextWithImages(Context context, CharSequence text) {
        Spannable spannable = spannableFactory.newSpannable(text);
        addImages(context, spannable);
        return spannable;
    }
}

Use:

in res/layout/mylayout.xml:

            <com.xyz.customandroid.TextViewWithImages
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#FFFFFF00"
                android:text="@string/can_try_again"
                android:textSize="12dip"
                style=...
                />

Note that if you place TextViewWithImages.java in some location other than com/xyz/customandroid/, you also must change the package name, com.xyz.customandroid above.

in res/values/strings.xml:

<string name="can_try_again">Press [img src=ok16/] to accept or [img src=retry16/] to retry</string>

where ok16.png and retry16.png are icons in the res/drawable/ folder

How to add images in select list?

With countries, languages or currency you may use emojis.

Works with pretty much every browser/OS that supports the use of emojis.

_x000D_
_x000D_
select {_x000D_
 height: 50px;_x000D_
 line-height: 50px;_x000D_
 font-size: 12pt;_x000D_
}
_x000D_
<select name="countries">_x000D_
    <option value="NL">&emsp;Netherlands</option>_x000D_
    <option value="DE">&emsp;Germany</option>_x000D_
    <option value="FR">&emsp;France</option>_x000D_
    <option value="ES">&emsp;Spain</option>_x000D_
</select>_x000D_
_x000D_
<br /><br />_x000D_
_x000D_
<select name="currency">_x000D_
    <option value="EUR">&emsp;€&emsp;EUR&emsp;</option>_x000D_
    <option value="GBP">&emsp;£&emsp;GBP&emsp;</option>_x000D_
    <option value="USD">&emsp;$&emsp;USD&emsp;</option>_x000D_
    <option value="YEN">&emsp;¥&emsp;YEN&emsp;</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Is it possible to add an array or object to SharedPreferences on Android

For writing:

 private <T> void storeData(String key, T data) {
    ByteArrayOutputStream serializedData = new ByteArrayOutputStream();

    try {
        ObjectOutputStream serializer = new ObjectOutputStream(serializedData);
        serializer.writeObject(data);
    } catch (IOException e) {
        e.printStackTrace();
    }

    SharedPreferences sharedPreferences = getSharedPreferences(TAG, 0);
    SharedPreferences.Editor edit = sharedPreferences.edit();

    edit.putString(key, Base64.encodeToString(serializedData.toByteArray(), Base64.DEFAULT));
    edit.commit();
}

For reading:

private <T> T getStoredData(String key) {
    SharedPreferences sharedPreferences = getSharedPreferences(TAG, 0);
    String serializedData = sharedPreferences.getString(key, null);
    T storedData = null;
    try {
        ByteArrayInputStream input = new ByteArrayInputStream(Base64.decode(serializedData, Base64.DEFAULT));
        ObjectInputStream inputStream = new ObjectInputStream(input);
        storedData = (T)inputStream.readObject();
    } catch (IOException|ClassNotFoundException|java.lang.IllegalArgumentException e) {
        e.printStackTrace();
    }

    return storedData;
}

Pass variables by reference in JavaScript

  1. primitive type variables like strings and numbers are always passed by value.
  2. Arrays and Objects are passed by reference or by value based on these conditions:

    • if you are setting the value of an object or array it is Pass by Value.

      object1 = {prop: "car"}; array1 = [1,2,3];

    • if you are changing a property value of an object or array then it is Pass by Reference.

      object1.prop = "car"; array1[0] = 9;

Code

_x000D_
_x000D_
function passVar(obj1, obj2, num) {_x000D_
    obj1.prop = "laptop"; // will CHANGE original_x000D_
    obj2 = { prop: "computer" }; //will NOT affect original_x000D_
    num = num + 1; // will NOT affect original_x000D_
}_x000D_
_x000D_
var object1 = {_x000D_
    prop: "car"_x000D_
};_x000D_
var object2 = {_x000D_
    prop: "bike"_x000D_
};_x000D_
var number1 = 10;_x000D_
_x000D_
passVar(object1, object2, number1);_x000D_
console.log(object1); //output: Object {item:"laptop"}_x000D_
console.log(object2); //output: Object {item:"bike"}_x000D_
console.log(number1); //ouput: 10
_x000D_
_x000D_
_x000D_

Using "&times" word in html changes to ×

I suspect you did not know that there are different & escapes in HTML. The W3C you can see the codes. &times means × in HTML code. Use &amp;times instead.

SQL Error: ORA-01861: literal does not match format string 01861

If you provide proper date format it should work please recheck once if you have given correct date format in insert values

Hosting a Maven repository on github

Since 2019 you can now use the new functionality called Github package registry.

Basically the process is:

  • generate a new personal access token from the github settings
  • add repository and token info in your settings.xml
  • deploy using

    mvn deploy -Dregistry=https://maven.pkg.github.com/yourusername -Dtoken=yor_token  
    

Read and write into a file using VBScript

Regardless of what you're trying to do there should be no need to read to and write to a file at the same time. It would also use more memory which should always be avoided. I'd suggest reading the entire file using the .ReadAll method and then close it and do whatever you need to do with the data (assuming you read the contents into a variable) and then do a write to the same file and overwrite the file. If you're concerned with having something go wrong when over-writing the current file you could always try to write it to a different file and throw an error if that doesn't work before trying to over-write the original.

How to execute a program or call a system command from Python

If you need the output from the command you are calling, then you can use subprocess.check_output (Python 2.7+).

>>> subprocess.check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'

Also note the shell parameter.

If shell is True, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of ~ to a user’s home directory. However, note that Python itself offers implementations of many shell-like features (in particular, glob, fnmatch, os.walk(), os.path.expandvars(), os.path.expanduser(), and shutil).

CSS: fixed to bottom and centered

A jQuery solution

$(function(){
    $(window).resize(function(){
        placeFooter();
    });
    placeFooter();
    // hide it before it's positioned
    $('#footer').css('display','inline');
});

function placeFooter() {    
    var windHeight = $(window).height();
    var footerHeight = $('#footer').height();
    var offset = parseInt(windHeight) - parseInt(footerHeight);
    $('#footer').css('top',offset);
}

<div id='footer' style='position: fixed; display: none;'>I am a footer</div>

Sometimes it's easier to implement JS than to hack old CSS.

http://jsfiddle.net/gLhEZ/

how to change any data type into a string in python

str is meant to produce a string representation of the object's data. If you're writing your own class and you want str to work for you, add:

def __str__(self):
    return "Some descriptive string"

print str(myObj) will call myObj.__str__().

repr is a similar method, which generally produces information on the class info. For most core library object, repr produces the class name (and sometime some class information) between angle brackets. repr will be used, for example, by just typing your object into your interactions pane, without using print or anything else.

You can define the behavior of repr for your own objects just like you can define the behavior of str:

def __repr__(self):
    return "Some descriptive string"

>>> myObj in your interactions pane, or repr(myObj), will result in myObj.__repr__()

How to check if user input is not an int value

try this code [updated]:

Scanner scan = null;
       int range, smallest = 0, input;

     for(;;){
         boolean error=false;
        scan = new Scanner(System.in);
        System.out.print("Enter an integer between 1-100:  ");


            if(!scan.hasNextInt()) {
                System.out.println("Invalid input!");                      
                continue;
            }
         range = scan.nextInt();
            if(range < 1) {
                System.out.println("Invalid input!");
                error=true;
            }
        if(error)
        {
        //do nothing
        }
        else
        {
       break;
        }

        }
             for(int ii = 1; ii <= range; ii++) {
            scan = new Scanner(System.in);
            System.out.print("Enter value " + ii + ": ");

            if(!scan.hasNextInt()) {
                System.out.println("Invalid input!"); 
               ii--;
                continue;
            } 
        }

Cannot hide status bar in iOS7

In Info Plist file Add a row for following property

Property Name : View controller-based status bar appearance

Value : NO

REST API Token-based Authentication

Let me seperate up everything and solve approach each problem in isolation:

Authentication

For authentication, baseauth has the advantage that it is a mature solution on the protocol level. This means a lot of "might crop up later" problems are already solved for you. For example, with BaseAuth, user agents know the password is a password so they don't cache it.

Auth server load

If you dispense a token to the user instead of caching the authentication on your server, you are still doing the same thing: Caching authentication information. The only difference is that you are turning the responsibility for the caching to the user. This seems like unnecessary labor for the user with no gains, so I recommend to handle this transparently on your server as you suggested.

Transmission Security

If can use an SSL connection, that's all there is to it, the connection is secure*. To prevent accidental multiple execution, you can filter multiple urls or ask users to include a random component ("nonce") in the URL.

url = username:[email protected]/api/call/nonce

If that is not possible, and the transmitted information is not secret, I recommend securing the request with a hash, as you suggested in the token approach. Since the hash provides the security, you could instruct your users to provide the hash as the baseauth password. For improved robustness, I recommend using a random string instead of the timestamp as a "nonce" to prevent replay attacks (two legit requests could be made during the same second). Instead of providing seperate "shared secret" and "api key" fields, you can simply use the api key as shared secret, and then use a salt that doesn't change to prevent rainbow table attacks. The username field seems like a good place to put the nonce too, since it is part of the auth. So now you have a clean call like this:

nonce = generate_secure_password(length: 16);
one_time_key = nonce + '-' + sha1(nonce+salt+shared_key);
url = username:[email protected]/api/call

It is true that this is a bit laborious. This is because you aren't using a protocol level solution (like SSL). So it might be a good idea to provide some kind of SDK to users so at least they don't have to go through it themselves. If you need to do it this way, I find the security level appropriate (just-right-kill).

Secure secret storage

It depends who you are trying to thwart. If you are preventing people with access to the user's phone from using your REST service in the user's name, then it would be a good idea to find some kind of keyring API on the target OS and have the SDK (or the implementor) store the key there. If that's not possible, you can at least make it a bit harder to get the secret by encrypting it, and storing the encrypted data and the encryption key in seperate places.

If you are trying to keep other software vendors from getting your API key to prevent the development of alternate clients, only the encrypt-and-store-seperately approach almost works. This is whitebox crypto, and to date, no one has come up with a truly secure solution to problems of this class. The least you can do is still issue a single key for each user so you can ban abused keys.

(*) EDIT: SSL connections should no longer be considered secure without taking additional steps to verify them.

Remove Project from Android Studio

  1. Go to your Android project directory

    C:\Users\HP\AndroidStudioProjects
    

    Screenshot

  2. Delete which one you need to delete

  3. Restart Android Studio

Why doesn't git recognize that my file has been changed, therefore git add not working

I had this issue. Mine wasn't working because I was putting my files in the .git folder inside my project.

linux shell script: split string, put them in an array then loop through them

Here's a variation on ashirazi's answer which doesn't rely on $IFS. It does have its own issues which I ouline below.

sentence="one;two;three"
sentence=${sentence//;/$'\n'}  # change the semicolons to white space
for word in $sentence
do
    echo "$word"
done

Here I've used a newline, but you could use a tab "\t" or a space. However, if any of those characters are in the text it will be split there, too. That's the advantage of $IFS - it can not only enable a separator, but disable the default ones. Just make sure you save its value before you change it - as others have suggested.

Why is it string.join(list) instead of list.join(string)?

- in "-".join(my_list) declares that you are converting to a string from joining elements a list.It's result-oriented. (just for easy memory and understanding)

I made an exhaustive cheatsheet of methods_of_string for your reference.

string_methods_44 = {
    'convert': ['join','split', 'rsplit','splitlines', 'partition', 'rpartition'],
    'edit': ['replace', 'lstrip', 'rstrip', 'strip'],
    'search': ['endswith', 'startswith', 'count', 'index', 'find','rindex', 'rfind',],
    'condition': ['isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isnumeric','isidentifier',
                  'islower','istitle', 'isupper','isprintable', 'isspace', ],
    'text': ['lower', 'upper', 'capitalize', 'title', 'swapcase',
             'center', 'ljust', 'rjust', 'zfill', 'expandtabs','casefold'],
    'encode': ['translate', 'maketrans', 'encode'],
    'format': ['format', 'format_map']}

How to join two tables by multiple columns in SQL?

No, just include the different fields in the "ON" clause of 1 inner join statement:

SELECT * from Evalulation e JOIN Value v ON e.CaseNum = v.CaseNum
    AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum

Tab separated values in awk

Should this not work?

echo "LOAD_SETTLED    LOAD_INIT       2011-01-13 03:50:01" | awk '{print $1}'

Set timeout for webClient.DownloadFile()

My answer comes from here

You can make a derived class, which will set the timeout property of the base WebRequest class:

using System;
using System.Net;

public class WebDownload : WebClient
{
    /// <summary>
    /// Time in milliseconds
    /// </summary>
    public int Timeout { get; set; }

    public WebDownload() : this(60000) { }

    public WebDownload(int timeout)
    {
        this.Timeout = timeout;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request != null)
        {
            request.Timeout = this.Timeout;
        }
        return request;
    }
}

and you can use it just like the base WebClient class.

SyntaxError: Use of const in strict mode?

The use of const in strict mode is available with the release of Chrome 41. Currently, Chrome 41 Beta is already released and supports it.

Android Open External Storage directory(sdcard) for storing file

Try using

new File(Environment.getExternalStorageDirectory(),"somefilename");

And don't forget to add WRITE_EXTERNAL STORAGE and READ_EXTERNAL STORAGE permissions

check if variable empty

<?php

$nothing = NULL;
$something = '';
$array = array(1,2,3);

// Create a function that checks if a variable is set or empty, and display "$variable_name is SET|EMPTY"
function  check($var) {
    if (isset($var)) {
        echo 'Variable is SET'. PHP_EOL;
  } elseif (empty($var)) { 
        echo 'Variable is empty' . PHP_EOL;

   } 

} 

check($nothing);
check($something);
check($array);

Finding the median of an unsorted array

As wikipedia says, Median-of-Medians is theoretically o(N), but it is not used in practice because the overhead of finding "good" pivots makes it too slow.
http://en.wikipedia.org/wiki/Selection_algorithm

Here is Java source for a Quickselect algorithm to find the k'th element in an array:

/**
 * Returns position of k'th largest element of sub-list.
 * 
 * @param list list to search, whose sub-list may be shuffled before
 *            returning
 * @param lo first element of sub-list in list
 * @param hi just after last element of sub-list in list
 * @param k
 * @return position of k'th largest element of (possibly shuffled) sub-list.
 */
static int select(double[] list, int lo, int hi, int k) {
    int n = hi - lo;
    if (n < 2)
        return lo;

    double pivot = list[lo + (k * 7919) % n]; // Pick a random pivot

    // Triage list to [<pivot][=pivot][>pivot]
    int nLess = 0, nSame = 0, nMore = 0;
    int lo3 = lo;
    int hi3 = hi;
    while (lo3 < hi3) {
        double e = list[lo3];
        int cmp = compare(e, pivot);
        if (cmp < 0) {
            nLess++;
            lo3++;
        } else if (cmp > 0) {
            swap(list, lo3, --hi3);
            if (nSame > 0)
                swap(list, hi3, hi3 + nSame);
            nMore++;
        } else {
            nSame++;
            swap(list, lo3, --hi3);
        }
    }
    assert (nSame > 0);
    assert (nLess + nSame + nMore == n);
    assert (list[lo + nLess] == pivot);
    assert (list[hi - nMore - 1] == pivot);
    if (k >= n - nMore)
        return select(list, hi - nMore, hi, k - nLess - nSame);
    else if (k < nLess)
        return select(list, lo, lo + nLess, k);
    return lo + k;
}

I have not included the source of the compare and swap methods, so it's easy to change the code to work with Object[] instead of double[].

In practice, you can expect the above code to be o(N).

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

SQLite supports replacing a row if it already exists:

INSERT OR REPLACE INTO [...blah...]

You can shorten this to

REPLACE INTO [...blah...]

This shortcut was added to be compatible with the MySQL REPLACE INTO expression.

How to click a browser button with JavaScript automatically?

this will work ,simple and easy

 `<form method="POST">
<input  type="submit" onclick="myFunction()" class="save" value="send" name="send" id="send" style="width:20%;">
</form>
<script language ="javascript" >
function myFunction() {
setInterval(function() {document.getElementById("send").click();}, 10000);    
}
</script>

`

Markdown open a new window link

You can edit the generated markup and add

target = "_blank"

Issue with adding common code as git submodule: "already exists in the index"

Removing submodule manually involves number of steps and this worked for me.

Assuming you are in the project root directory and sample git module name is "c3-pro-ios-framework"

Remove the files associated to the submodule

rm -rf .git/modules/c3-pro-ios-framework/

Remove any references to submodule in config

vim .git/config

enter image description here

Remove .gitmodules

rm -rf .gitmodules

Remove it from the cache without the "git"

git rm --cached c3-pro-ios-framework

Add submodule

git submodule add https://github.com/chb/c3-pro-ios-framework.git

How to delete all records from table in sqlite with Android?

try this code to delete all data from a table..

String selectQuery = "DELETE FROM table_name ";
Cursor cursor = data1.getReadableDatabase().rawQuery(selectQuery, null);

Detect a finger swipe through JavaScript on the iPhone and Android

Simple vanilla JS example for horizontal swipe:

let touchstartX = 0;
let touchendX = 0;

const slider = document.getElementById('slider');

function handleGesture() {
  if (touchendX < touchstartX) alert('swiped left!');
  if (touchendX > touchstartX) alert('swiped right!');
}

slider.addEventListener('touchstart', e => {
  touchstartX = e.changedTouches[0].screenX;
});

slider.addEventListener('touchend', e => {
  touchendX = e.changedTouches[0].screenX;
  handleGesture();
});

You can use pretty same logic for vertical swipe.

How to check identical array in most efficient way?

So, what's wrong with checking each element iteratively?

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

How to convert milliseconds into a readable date?

Using the library Datejs you can accomplish this quite elegantly, with its toString format specifiers: http://jsfiddle.net/TeRnM/1/.

var date = new Date(1324339200000);

date.toString("MMM dd"); // "Dec 20"

How to print (using cout) a number in binary form?

Using old C++ version, you can use this snippet :

template<typename T>
string toBinary(const T& t)
{
  string s = "";
  int n = sizeof(T)*8;
  for(int i=n-1; i>=0; i--)
  {
    s += (t & (1 << i))?"1":"0";
  }
  return s;
}

int main()
{
  char a, b;

  short c;
  a = -58;
  c = -315;

  b = a >> 3;

  cout << "a = " << a << " => " << toBinary(a) << endl;
  cout << "b = " << b << " => " << toBinary(b) << endl;
  cout << "c = " << c << " => " << toBinary(c) << endl;
}

a = => 11000110
b = => 11111000
c = -315 => 1111111011000101

Grant execute permission for a user on all stored procedures in database?

Create a role add this role to users, and then you can grant execute to all the routines in one shot to this role.

CREATE ROLE <abc>
GRANT EXECUTE TO <abc>

EDIT
This works in SQL Server 2005, I'm not sure about backward compatibility of this feature, I'm sure anything later than 2005 should be fine.

Returning a value even if no result

You can use COALESCE

SELECT COALESCE(SUM(column),0)
FROM   table

SOAP or REST for Web Services?

It's a good question... I don't want to lead you astray, so I'm open to other people's answers as much as you are. For me, it really comes down to cost of overhead and what the use of the API is. I prefer consuming web services when creating client software, however I don't like the weight of SOAP. REST, I believe, is lighter weight but I don't enjoy working with it from a client perspective nearly as much.

I'm curious as to what others think.

How to make a vertical SeekBar in Android?

In my case, I used an ordinary seekBar and just flipped out the layout.

seekbark_layout.xml - my layout that containts seekbar which we need to make vertical.

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

<SeekBar
    android:id="@+id/seekBar"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"/>

</RelativeLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.vgfit.seekbarexample.MainActivity">

<View
    android:id="@+id/headerView"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:background="@color/colorAccent"/>

<View
    android:id="@+id/bottomView"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_alignParentBottom="true"
    android:background="@color/colorAccent"/>

<include
    layout="@layout/seekbar_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/bottomView"
    android:layout_below="@id/headerView"/>

 </RelativeLayout>

And in MainActivity I rotate seekbar_layout:

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.RelativeLayout
import kotlinx.android.synthetic.main.seekbar_layout.*


class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    rootView.post {
        val w = rootView.width
        val h = rootView.height

        rootView.rotation = 270.0f
        rootView.translationX = ((w - h) / 2).toFloat()
        rootView.translationY = ((h - w) / 2).toFloat()

        val lp = rootView.layoutParams as RelativeLayout.LayoutParams
        lp.height = w
        lp.width = h
        rootView.requestLayout()
    }
}
}

As a result we have necessary vertical seekbar: enter image description here

Split string into string array of single characters

I believe this is what you're looking for:

char[] characters = "this is a test".ToCharArray();

Phone number formatting an EditText in Android

Simply Use This :

In Java Code :

editText.addTextChangedListener(new PhoneNumberFormattingTextWatcher());

In XML Code :

<EditText
    android:id="@+id/etPhoneNumber"
    android:inputType="phone"/>

This code work for me. It'll auto format when text changed in edit text.

Comparing double values in C#

From the documentation:

Precision in Comparisons The Equals method should be used with caution, because two apparently equivalent values can be unequal due to the differing precision of the two values. The following example reports that the Double value .3333 and the Double returned by dividing 1 by 3 are unequal.

...

Rather than comparing for equality, one recommended technique involves defining an acceptable margin of difference between two values (such as .01% of one of the values). If the absolute value of the difference between the two values is less than or equal to that margin, the difference is likely to be due to differences in precision and, therefore, the values are likely to be equal. The following example uses this technique to compare .33333 and 1/3, the two Double values that the previous code example found to be unequal.

So if you really need a double, you should use the techique described on the documentation. If you can, change it to a decimal. It' will be slower, but you won't have this type of problem.

Python Progress Bar

The code below is a quite general solution and also has a time elapsed and time remaining estimate. You can use any iterable with it. The progress bar has a fixed size of 25 characters but it can show updates in 1% steps using full, half, and quarter block characters. The output looks like this:

 18% |¦¦¦¦¦                    | \ [0:00:01, 0:00:06]

Code with example:

import sys, time
from numpy import linspace

def ProgressBar(iterObj):
  def SecToStr(sec):
    m, s = divmod(sec, 60)
    h, m = divmod(m, 60)
    return u'%d:%02d:%02d'%(h, m, s)
  L = len(iterObj)
  steps = {int(x):y for x,y in zip(linspace(0, L, min(100,L), endpoint=False),
                                   linspace(0, 100, min(100,L), endpoint=False))}
  qSteps = ['', u'\u258E', u'\u258C', u'\u258A'] # quarter and half block chars
  startT = time.time()
  timeStr = '   [0:00:00, -:--:--]'
  activity = [' -',' \\',' |',' /']
  for nn,item in enumerate(iterObj):
    if nn in steps:
      done = u'\u2588'*int(steps[nn]/4.0)+qSteps[int(steps[nn]%4)]
      todo = ' '*(25-len(done))
      barStr = u'%4d%% |%s%s|'%(steps[nn], done, todo)
    if nn>0:
      endT = time.time()
      timeStr = ' [%s, %s]'%(SecToStr(endT-startT),
                             SecToStr((endT-startT)*(L/float(nn)-1)))
    sys.stdout.write('\r'+barStr+activity[nn%4]+timeStr); sys.stdout.flush()
    yield item
  barStr = u'%4d%% |%s|'%(100, u'\u2588'*25)
  timeStr = '   [%s, 0:00:00]\n'%(SecToStr(time.time()-startT))
  sys.stdout.write('\r'+barStr+timeStr); sys.stdout.flush()

# Example
s = ''
for c in ProgressBar(list('Disassemble and reassemble this string')):
  time.sleep(0.2)
  s += c
print(s)

Suggestions for improvements or other comments are appreciated. Cheers!

Could pandas use column as index?

Yes, with set_index you can make Locality your row index.

data.set_index('Locality', inplace=True)

If inplace=True is not provided, set_index returns the modified dataframe as a result.

Example:

> import pandas as pd
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
                     ['ABERFELDIE', 534000, 600000]],
                    columns=['Locality', 2005, 2006])

> df
     Locality    2005    2006
0  ABBOTSFORD  427000  448000
1  ABERFELDIE  534000  600000

> df.set_index('Locality', inplace=True)
> df
              2005    2006
Locality                  
ABBOTSFORD  427000  448000
ABERFELDIE  534000  600000

> df.loc['ABBOTSFORD']
2005    427000
2006    448000
Name: ABBOTSFORD, dtype: int64

> df.loc['ABBOTSFORD'][2005]
427000

> df.loc['ABBOTSFORD'].values
array([427000, 448000])

> df.loc['ABBOTSFORD'].tolist()
[427000, 448000]

Facebook page automatic "like" URL (for QR Code)

This has changed, it's now fb://profile/(profileID)

Counting the number of non-NaN elements in a numpy ndarray in Python

Quick-to-write alterantive

Even though is not the fastest choice, if performance is not an issue you can use:

sum(~np.isnan(data)).

Performance:

In [7]: %timeit data.size - np.count_nonzero(np.isnan(data))
10 loops, best of 3: 67.5 ms per loop

In [8]: %timeit sum(~np.isnan(data))
10 loops, best of 3: 154 ms per loop

In [9]: %timeit np.sum(~np.isnan(data))
10 loops, best of 3: 140 ms per loop

JSON - Iterate through JSONArray

for (int i = 0; i < getArray.length(); i++) {
            JSONObject objects = getArray.getJSONObject(i);
            Iterator key = objects.keys();
            while (key.hasNext()) {
                String k = key.next().toString();
                System.out.println("Key : " + k + ", value : "
                        + objects.getString(k));
            }
            // System.out.println(objects.toString());
            System.out.println("-----------");

        }

Hope this helps someone

Automatic creation date for Django model form objects?

Well, the above answer is correct, auto_now_add and auto_now would do it, but it would be better to make an abstract class and use it in any model where you require created_at and updated_at fields.

class TimeStampMixin(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

Now anywhere you want to use it you can do a simple inherit and you can use timestamp in any model you make like.

class Posts(TimeStampMixin):
    name = models.CharField(max_length=50)
    ...
    ...

In this way, you can leverage object-oriented reusability, in Django DRY(don't repeat yourself)

SHA-1 fingerprint of keystore certificate

Try this with your user & pass

keytool -list -v -keystore {path of jks file} -alias {keyname} -storepass {keypassword} -keypass {aliaspassword}

Exe

keytool -list -v -keystore "E:\AndroidStudioProject\ParathaApp\key.jks" -alias key0 -storepass mks@1 -keypass golu@1

Creating a list of pairs in java

Sounds like you need to create your own pair class (see discussion here). Then make a List of that pair class you created

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

Trevor Sullivan has a write-up on how to add a command called Copy-ItemWithProgress to PowerShell on Robocopy.

Convert Pixels to Points

There are 72 points per inch; if it is sufficient to assume 96 pixels per inch, the formula is rather simple:

points = pixels * 72 / 96

There is a way to get the configured pixels per inch of your display in Windows using GetDeviceCaps. Microsoft has a guide called "Developing DPI-Aware Applications", look for the section "Creating DPI-Aware Fonts".

The W3C has defined the pixel measurement px as exactly 1/96th of 1in regardless of the actual resolution of your display, so the above formula should be good for all web work.

Change the jquery show()/hide() animation?

You can also use a fadeIn/FadeOut Combo, too....

$('.test').bind('click', function(){
    $('.div1').fadeIn(500); 
    $('.div2').fadeOut(500);
    $('.div3').fadeOut(500);
    return false;
});

Convert Mercurial project to Git

I had a similar task to do, but it contained some aspects that were not sufficiently covered by the other answers here:

  • I wanted to convert all (in my case: two, or in general: more than one) branches of my repo.
  • I had non-ASCII and (being a Windows user) non-UTF8-encoded characters (for the curious: German umlaute) in my commit messages and file names.

I did not try fast-export and hg-fast-export, since they require that you have Python and some Mercurial Python modules on your machine, which I didn't have.

I did try hg-init with TortoiseHG, and this answer gave me a good start. But it looked like it only converts the current branch, not all at once (*). So I read the hg-init docs and this blog post and added

[git]  
branch_bookmark_suffix=_bookmark

to my mercurial.ini, and did

hg bookmarks -r default master  
hg bookmarks -r my_branch my_branch_bookmark  
hg gexport

(Repeat the 2nd line for every branch you want to convert, and repeat it again if you should happen to do another commit before executing the 3rd line). This creates a folder git within .hg, which turns out to be a bare Git repo with all the exported branches. I could clone this repo and had a working copy as desired.

Or almost...

Running

git status

on my working copy showed all files with non-ASCII characters in their names as untracked files. So I continued researching and followed this advice:

git rm -rf --cached \*  
git add --all
git commit 

And finally the repo was ready to be pushed up to Bitbucket :-)

I also tried the Github importer as mentioned in this answer. I used Bitbucket as the source system, and Github did quite a good job, i.e. it converted all branches automatically. However, it showed '?'-characters for all non-ASCII characters in my commit messages (Web-UI and locally) and filenames (Web-UI only), and while I could fix the filenames as described above, I had no idea what to do with the commit messages, and so I'd prefer the hg-init approach. Without the encoding issue the Github importer would have been a perfect and fast solution (as long as you have a paid Github account or can tolerate that your repo is public for as long as it takes to pull it from Github to your local machine).


(*) So it looked like before I discovered that I have to bookmark all the branches I want to export. If you do and push to a bare (!) repo, like the linked answer says, you get all the branches.

Add Favicon with React and Webpack

Adding your favicon simply into to the public folder should do. Make sure the favicon is named as favicon.ico.

How can I create directory tree in C++/Linux?

mkdir -p /dir/to/the/file

touch /dir/to/the/file/thefile.ending

How to make JQuery-AJAX request synchronous

Can you try this,

var ajaxSubmit = function(formE1) {

            var password = $.trim($('#employee_password').val());

             $.ajax({
                type: "POST",
                async: "false",
                url: "checkpass.php",
                data: "password="+password,
                success: function(html) {
                    var arr=$.parseJSON(html);
                    if(arr == "Successful")
                    { 
                         **$("form[name='form']").submit();**
                        return true;
                    }
                    else
                    {    return false;
                    }
                }
            });
              **return false;**
        }

How do I get a list of locked users in an Oracle database?

select username,
       account_status 
  from dba_users 
 where lock_date is not null;

This will actually give you the list of locked users.

What is useState() in React?

Thanks loelsonk, i did so

_x000D_
_x000D_
const [dataAction, setDataAction] = useState({name: '', description: ''});_x000D_
_x000D_
    const _handleChangeName = (data) => {_x000D_
        if(data.name)_x000D_
            setDataAction( prevState  => ({ ...prevState,   name : data.name }));_x000D_
        if(data.description)_x000D_
            setDataAction( prevState  => ({ ...prevState,   description : data.description }));_x000D_
    };_x000D_
    _x000D_
    ....return (_x000D_
    _x000D_
          <input onChange={(event) => _handleChangeName({name: event.target.value})}/>_x000D_
          <input onChange={(event) => _handleChangeName({description: event.target.value})}/>_x000D_
    )
_x000D_
_x000D_
_x000D_

Adding an arbitrary line to a matplotlib plot in ipython notebook

Using vlines:

import numpy as np
np.random.seed(5)
x = arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
p =  plot(x, y, "o")
vlines(70,100,250)

The basic call signatures are:

vlines(x, ymin, ymax)
hlines(y, xmin, xmax)

How are zlib, gzip and zip related? What do they have in common and how are they different?

ZIP is a file format used for storing an arbitrary number of files and folders together with lossless compression. It makes no strict assumptions about the compression methods used, but is most frequently used with DEFLATE.

Gzip is both a compression algorithm based on DEFLATE but less encumbered with potential patents et al, and a file format for storing a single compressed file. It supports compressing an arbitrary number of files and folders when combined with tar. The resulting file has an extension of .tgz or .tar.gz and is commonly called a tarball.

zlib is a library of functions encapsulating DEFLATE in its most common LZ77 incarnation.

Redirect on select option in select box

Because the first option is already selected, the change event is never fired. Add an empty value as the first one and check for empty in the location assignment.

Here's an example:

https://jsfiddle.net/bL5sq/

_x000D_
_x000D_
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">_x000D_
  <option value="">Select...</option>_x000D_
  <option value="https://google.com">Google</option>_x000D_
  <option value="https://yahoo.com">Yahoo</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How do I determine the current operating system with Node.js

You are looking for the OS native module for Node.js:

v4: https://nodejs.org/dist/latest-v4.x/docs/api/os.html#os_os_platform

or v5 : https://nodejs.org/dist/latest-v5.x/docs/api/os.html#os_os_platform

os.platform()

Returns the operating system platform. Possible values are 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'. Returns the value of process.platform.

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

Update: req.param() is now deprecated, so going forward do not use this answer.


Your answer is the preferred way to do it, however I thought I'd point out that you can also access url, post, and route parameters all with req.param(parameterName, defaultValue).

In your case:

var color = req.param('color');

From the express guide:

lookup is performed in the following order:

  • req.params
  • req.body
  • req.query

Note the guide does state the following:

Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.

However in practice I've actually found req.param() to be clear enough and makes certain types of refactoring easier.

RegEx: Grabbing values between quotation marks

I've been using the following with great success:

(["'])(?:(?=(\\?))\2.)*?\1

It supports nested quotes as well.

For those who want a deeper explanation of how this works, here's an explanation from user ephemient:

([""']) match a quote; ((?=(\\?))\2.) if backslash exists, gobble it, and whether or not that happens, match a character; *? match many times (non-greedily, as to not eat the closing quote); \1 match the same quote that was use for opening.

jQuery: Adding two attributes via the .attr(); method

Should work:

.attr({
    target:"nw", 
    title:"Opens in a new window",
    "data-value":"internal link" // attributes which contain dash(-) should be covered in quotes.
});

Note:

" When setting multiple attributes, the quotes around attribute names are optional.

WARNING: When setting the 'class' attribute, you must always use quotes!

From the jQuery documentation (Sep 2016) for .attr:

Attempting to change the type attribute on an input or button element created via document.createElement() will throw an exception on Internet Explorer 8 or older.

Edit:
For future reference... To get a single attribute you would use

var strAttribute = $(".something").attr("title");

To set a single attribute you would use

$(".something").attr("title","Test");

To set multiple attributes you need to wrap everything in { ... }

$(".something").attr( { title:"Test", alt:"Test2" } );

Edit - If you're trying to get/set the 'checked' attribute from a checkbox...

You will need to use prop() as of jQuery 1.6+

the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

...the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does

So to get the checked status of a checkbox, you should use:

$('#checkbox1').prop('checked'); // Returns true/false

Or to set the checkbox as checked or unchecked you should use:

$('#checkbox1').prop('checked', true); // To check it
$('#checkbox1').prop('checked', false); // To uncheck it

How to get the number of columns in a matrix?

Use the size() function.

>> size(A,2)

Ans =

   3

The second argument specifies the dimension of which number of elements are required which will be '2' if you want the number of columns.

Official documentation.

Send inline image in email

In addition to the comments above, I have the following additional comments:

  • Do not mix Attachments and AlternativeView, use one or the other. If you mix them, the inline attachments will be rendered as unknown downloads.
  • While Outlook and Google allow standard HTML-style "cid:att-001" this does NOT work on iPhone (late 2016 patch level), rather use pure alpha numeric "cid:att-001" -> "cid:att001"

As an aside: Outlook (even Office 2015) rendering (still the clear majority for business users) requires the use of TABLE TR TD style HTML, as it does not fully support the HTML box model.

How to check if BigDecimal variable == 0 in java?

BigDecimal.ZERO.setScale(2).equals(new BigDecimal("0.00"));

Test if a string contains any of the strings from an array

if (Arrays.asList(array).contains(string))

Pressing Ctrl + A in Selenium WebDriver

The simplest answer in C# (if you are C# inclined).

Actions action = new Actions(); 
action.KeyDown(OpenQA.Selenium.Keys.Control).SendKeys("a").KeyUp(OpenQA.Selenium.Keys.Control).perform();

This answer is almost given by Hari Reddy, but I have fixed the case which he'd got wrong on some keywords, added the KeyUp or you get in a mess leaving the control key down.

I've also added the clarification on OpenQA.Selenium.Keys, because you may also be using Windows.Forms on the same class as I was an require this clarity.

Lastly, I type "a" because I found that to be the simplest way and I can see no suggestion from the OP that they don't want the simplest answer.

Many thanks to Hari Reddy though as I was a novice in Actions class usage and I was writing many different commands. Chaining them together the way he showed is quicker :-)

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

If Inferring the Constraints still gives you the error, just use this code:

app:layout_constraintBottom_toBottomOf="parent"

Java - Change int to ascii

In Java, you really want to use Integer.toString to convert an integer to its corresponding String value. If you are dealing with just the digits 0-9, then you could use something like this:

private static final char[] DIGITS =
    {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

private static char getDigit(int digitValue) {
   assertInRange(digitValue, 0, 9);
   return DIGITS[digitValue];
}

Or, equivalently:

private static int ASCII_ZERO = 0x30;

private static char getDigit(int digitValue) {
  assertInRange(digitValue, 0, 9);
  return ((char) (digitValue + ASCII_ZERO));
}

How to select specific form element in jQuery?

I prefer an id descendant selector of your #form2, like this:

$("#form2 #name").val("Hello World!");

http://api.jquery.com/descendant-selector/

Passing an array as a function parameter in JavaScript

you can use spread operator in a more basic form

[].concat(...array)

in the case of functions that return arrays but are expected to pass as arguments

Example:

function expectArguments(...args){
  return [].concat(...args);
}

JSON.stringify(expectArguments(1,2,3)) === JSON.stringify(expectArguments([1,2,3]))

Could not resolve all dependencies for configuration ':classpath'

You should have gradle-wrapper.properties inside gradle/wrapper folder. Make sure you are using the right distributionURL, and the latest one. It should look something like this :

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

Pure JavaScript: a function like jQuery's isNumeric()

var str = 'test343',
    isNumeric = /^[-+]?(\d+|\d+\.\d*|\d*\.\d+)$/;

isNumeric.test(str);

How to echo out table rows from the db (php)

 $result= mysql_query("SELECT * FROM MY_TABLE");
 while($row = mysql_fetch_array($result)){
      echo $row['whatEverColumnName'];
 }

An efficient way to Base64 encode a byte array?

Byte[] -> String: use system.convert.tobase64string

Convert.ToBase64String(byte[] data)

String -> Byte[]: use system.convert.frombase64string

Convert.FromBase64String(string data)

Given final block not properly padded

depending on the cryptography algorithm you are using, you may have to add some padding bytes at the end before encrypting a byte array so that the length of the byte array is multiple of the block size:

Specifically in your case the padding schema you chose is PKCS5 which is described here: http://www.rsa.com/products/bsafe/documentation/cryptoj35html/doc/dev_guide/group_CJ_SYM__PAD.html

(I assume you have the issue when you try to encrypt)

You can choose your padding schema when you instantiate the Cipher object. Supported values depend on the security provider you are using.

By the way are you sure you want to use a symmetric encryption mechanism to encrypt passwords? Wouldn't be a one way hash better? If you really need to be able to decrypt passwords, DES is quite a weak solution, you may be interested in using something stronger like AES if you need to stay with a symmetric algorithm.

How To Save Canvas As An Image With canvas.toDataURL()?

Instead of imageElement.src = myImage; you should use window.location = myImage;

And even after that the browser will display the image itself. You can right click and use "Save Link" for downloading the image.

Check this link for more information.

Format date as dd/MM/yyyy using pipes

If anyone can looking to display date with time in AM or PM in angular 6 then this is for you.

{{date | date: 'dd/MM/yyyy hh:mm a'}}

Output

enter image description here

Pre-defined format options

Examples are given in en-US locale.

'short': equivalent to 'M/d/yy, h:mm a' (6/15/15, 9:03 AM).
'medium': equivalent to 'MMM d, y, h:mm:ss a' (Jun 15, 2015, 9:03:01 AM).
'long': equivalent to 'MMMM d, y, h:mm:ss a z' (June 15, 2015 at 9:03:01 AM GMT+1).
'full': equivalent to 'EEEE, MMMM d, y, h:mm:ss a zzzz' (Monday, June 15, 2015 at 9:03:01 AM GMT+01:00).
'shortDate': equivalent to 'M/d/yy' (6/15/15).
'mediumDate': equivalent to 'MMM d, y' (Jun 15, 2015).
'longDate': equivalent to 'MMMM d, y' (June 15, 2015).
'fullDate': equivalent to 'EEEE, MMMM d, y' (Monday, June 15, 2015).
'shortTime': equivalent to 'h:mm a' (9:03 AM).
'mediumTime': equivalent to 'h:mm:ss a' (9:03:01 AM).
'longTime': equivalent to 'h:mm:ss a z' (9:03:01 AM GMT+1).
'fullTime': equivalent to 'h:mm:ss a zzzz' (9:03:01 AM GMT+01:00).

Reference Link

Telegram Bot - how to get a group chat id?

If you are implementing your bot, keep stored a group name -> id table, and ask it with a command. Then you can also send per name.

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

Bro, I had the same problem. Thing is I built a query builder, quite an complex one that build his predicates dynamically pending on what parameters had been set and cached the queries. Anyways, before I built my query builder, I had a non object oriented procedural code build the same thing (except of course he didn't cache queries and use parameters) that worked flawless. Now when my builder tried to do the very same thing, my PostgreSQL threw this fucked up error that you received too. I examined my generated SQL code and found no errors. Strange indeed.

My search soon proved that it was one particular predicate in the WHERE clause that caused this error. Yet this predicate was built by code that looked like, well almost, exactly as how the procedural code looked like before this exception started to appear out of nowhere.

But I saw one thing I had done differently in my builder as opposed to what the procedural code did previously. It was the order of the predicates he put in the WHERE clause! So I started to move this predicate around and soon discovered that indeed the order of predicates had much to say. If I had this predicate all alone, my query worked (but returned an erroneous result-match of course), if I put him with just one or the other predicate it worked sometimes, didn't work other times. Moreover, mimicking the previous order of the procedural code didn't work either. What finally worked was to put this demonic predicate at the start of my WHERE clause, as the first predicate added! So again if I haven't made myself clear, the order my predicates where added to the WHERE method/clause was creating this exception.