Programs & Examples On #Collaborative

How do I list all tables in all databases in SQL Server in a single result set?

I realize this is a very old thread, but it was very helpful when I had to put together some system documentation for several different servers that were hosting different versions of Sql Server. I ended up creating 4 stored procedures which I am posting here for the benefit of the community. We use Dynamics NAV so the two stored procedures with NAV in the name split the Nav company out of the table name. Enjoy...

2 of 4 - ListServerDatabaseTables

USE [YourDatabase]
GO

SET QUOTED_IDENTIFIER ON
GO

ALTER PROC [dbo].[ListServerDatabaseTables]
(
    @SearchDatabases varchar(max) = NULL,  
    @SearchSchema sysname = NULL,
    @SearchTables varchar(max) = NULL,
    @ExcludeSystemDatabases bit = 1,
    @Sql varchar(max) OUTPUT
)
AS BEGIN

/**************************************************************************************************************************************
* Lists all of the database tables for a given server.
*   Parameters
*       SearchDatabases - Comma delimited list of database names for which to search - converted into series of Like statements
*                         Defaults to null  
*       SearchSchema - Schema name for which to search
*                      Defaults to null 
*       SearchTables - Comma delimited list of table names for which to search - converted into series of Like statements
*                      Defaults to null 
*       ExcludeSystemDatabases - 1 to exclude system databases, otherwise 0
*                          Defaults to 1
*       Sql - Output - the stored proc generated sql
*
*   Adapted from answer by KM answered May 21 '10 at 13:33
*   From: How do I list all tables in all databases in SQL Server in a single result set?
*   Link: https://stackoverflow.com/questions/2875768/how-do-i-list-all-tables-in-all-databases-in-sql-server-in-a-single-result-set
*
**************************************************************************************************************************************/

    SET NOCOUNT ON

    DECLARE @l_CompoundLikeStatement varchar(max) = ''
    DECLARE @l_TableName sysname
    DECLARE @l_DatabaseName sysname

    DECLARE @l_Index int

    DECLARE @l_UseAndText bit = 0

    DECLARE @AllTables table (ServerName sysname, DbName sysname, SchemaName sysname, TableName sysname)

    SET @Sql = 
        'select @@ServerName as ''ServerName'', ''?'' as ''DbName'', s.name as ''SchemaName'', t.name as ''TableName'' ' + char(13) +
        'from [?].sys.tables t inner join ' + char(13) + 
        '     sys.schemas s on t.schema_id = s.schema_id '

    -- Comma delimited list of database names for which to search
    IF @SearchDatabases IS NOT NULL BEGIN
        SET @l_CompoundLikeStatement = char(13) + 'where (' + char(13)
        WHILE LEN(LTRIM(RTRIM(@SearchDatabases))) > 0 BEGIN
            SET @l_Index = CHARINDEX(',', @SearchDatabases)
            IF @l_Index = 0 BEGIN
                SET @l_DatabaseName = LTRIM(RTRIM(@SearchDatabases))
            END ELSE BEGIN
                SET @l_DatabaseName = LTRIM(RTRIM(LEFT(@SearchDatabases, @l_Index - 1)))
            END

            SET @SearchDatabases = LTRIM(RTRIM(REPLACE(LTRIM(RTRIM(REPLACE(@SearchDatabases, @l_DatabaseName, ''))), ',', '')))
            SET @l_CompoundLikeStatement = @l_CompoundLikeStatement + char(13) + ' ''?'' like ''' + @l_DatabaseName + '%'' COLLATE Latin1_General_CI_AS or '
        END

        -- Trim trailing Or and add closing right parenthesis )
        SET @l_CompoundLikeStatement = LTRIM(RTRIM(@l_CompoundLikeStatement))
        SET @l_CompoundLikeStatement = LEFT(@l_CompoundLikeStatement, LEN(@l_CompoundLikeStatement) - 2) + ')'

        SET @Sql = @Sql + char(13) +
            @l_CompoundLikeStatement

        SET @l_UseAndText = 1
    END

    -- Search schema
    IF @SearchSchema IS NOT NULL BEGIN
        SET @Sql = @Sql + char(13)
        SET @Sql = @Sql + CASE WHEN @l_UseAndText = 1 THEN '  and ' ELSE 'where ' END +
            's.name LIKE ''' + @SearchSchema + ''' COLLATE Latin1_General_CI_AS'
        SET @l_UseAndText = 1
    END

    -- Comma delimited list of table names for which to search
    IF @SearchTables IS NOT NULL BEGIN
        SET @l_CompoundLikeStatement = char(13) + CASE WHEN @l_UseAndText = 1 THEN '  and (' ELSE 'where (' END + char(13) 
        WHILE LEN(LTRIM(RTRIM(@SearchTables))) > 0 BEGIN
            SET @l_Index = CHARINDEX(',', @SearchTables)
            IF @l_Index = 0 BEGIN
                SET @l_TableName = LTRIM(RTRIM(@SearchTables))
            END ELSE BEGIN
                SET @l_TableName = LTRIM(RTRIM(LEFT(@SearchTables, @l_Index - 1)))
            END

            SET @SearchTables = LTRIM(RTRIM(REPLACE(LTRIM(RTRIM(REPLACE(@SearchTables, @l_TableName, ''))), ',', '')))
            SET @l_CompoundLikeStatement = @l_CompoundLikeStatement + char(13) + ' t.name like ''$' + @l_TableName + ''' COLLATE Latin1_General_CI_AS or '
        END

        -- Trim trailing Or and add closing right parenthesis )
        SET @l_CompoundLikeStatement = LTRIM(RTRIM(@l_CompoundLikeStatement))
        SET @l_CompoundLikeStatement = LEFT(@l_CompoundLikeStatement, LEN(@l_CompoundLikeStatement) - 2) + ' )'

        SET @Sql = @Sql + char(13) +
            @l_CompoundLikeStatement

        SET @l_UseAndText = 1
    END

    IF @ExcludeSystemDatabases = 1 BEGIN
        SET @Sql = @Sql + char(13)
        SET @Sql = @Sql + case when @l_UseAndText = 1 THEN '  and ' ELSE 'where ' END +
            '''?'' not in (''master'' COLLATE Latin1_General_CI_AS, ''model'' COLLATE Latin1_General_CI_AS, ''msdb'' COLLATE Latin1_General_CI_AS, ''tempdb'' COLLATE Latin1_General_CI_AS)' 
    END

/*  PRINT @Sql  */

    INSERT INTO @AllTables 
    EXEC sp_msforeachdb @Sql

    SELECT * FROM @AllTables ORDER BY DbName COLLATE Latin1_General_CI_AS, SchemaName COLLATE Latin1_General_CI_AS, TableName COLLATE Latin1_General_CI_AS
END

break/exit script

Perhaps you just want to stop executing a long script at some point. ie. like you want to hard code an exit() in C or Python.

print("this is the last message")
stop()
print("you should not see this")

jQuery to serialize only elements within a div

No problem. Just use the following. This will behave exactly like serializing a form but using a div's content instead.

$('#divId :input').serialize();

Check https://jsbin.com/xabureladi/1 for a demonstration (https://jsbin.com/xabureladi/1/edit for the code)

Selecting multiple columns/fields in MySQL subquery

Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..

FROM TABLE A

The other way is

FROM (SELECT col as name1, col2 as name2 FROM ...) B

Notice that the select clause and the parentheses around it are a table, a virtual table.

So, using your second code example (I am guessing at the columns you are hoping to retrieve here):

SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)

Notice that your real table attribute is the first table in this join, and that this virtual table I've called b is the second table.

This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.

SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
 SELECT count(*) AS langcount,  at.attribute
 FROM attributeTranslation at
 GROUP BY at.attribute
) c ON (a.id = c.attribute)

See how that goes? You've generated a virtual table c containing two columns, joined it to the other two, used one of the columns for the ON clause, and returned the other as a column in your result set.

ArrayList insertion and retrieval order

Yes it remains the same. but why not easily test it? Make an ArrayList, fill it and then retrieve the elements!

Rendering partial view on button click in ASP.NET MVC

So here is the controller code.

public IActionResult AddURLTest()
{
    return ViewComponent("AddURL");
}

You can load it using JQuery load method.

$(document).ready (function(){
    $("#LoadSignIn").click(function(){
        $('#UserControl').load("/Home/AddURLTest");
    });
});

source code link

Create a Date with a set timezone without using a string representation

Simply Set the Time Zone and Get Back According

new Date().toLocaleString("en-US", {timeZone: "America/New_York"})

Other Time-zones are as Following

var world_timezones =
[
    'Europe/Andorra',
    'Asia/Dubai',
    'Asia/Kabul',
    'Europe/Tirane',
    'Asia/Yerevan',
    'Antarctica/Casey',
    'Antarctica/Davis',
    'Antarctica/DumontDUrville', 
    'Antarctica/Mawson',
    'Antarctica/Palmer',
    'Antarctica/Rothera',
    'Antarctica/Syowa',
    'Antarctica/Troll',
    'Antarctica/Vostok',
    'America/Argentina/Buenos_Aires',
    'America/Argentina/Cordoba',
    'America/Argentina/Salta',
    'America/Argentina/Jujuy',
    'America/Argentina/Tucuman',
    'America/Argentina/Catamarca',
    'America/Argentina/La_Rioja',
    'America/Argentina/San_Juan',
    'America/Argentina/Mendoza',
    'America/Argentina/San_Luis',
    'America/Argentina/Rio_Gallegos',
    'America/Argentina/Ushuaia',
    'Pacific/Pago_Pago',
    'Europe/Vienna',
    'Australia/Lord_Howe',
    'Antarctica/Macquarie',
    'Australia/Hobart',
    'Australia/Currie',
    'Australia/Melbourne',
    'Australia/Sydney',
    'Australia/Broken_Hill',
    'Australia/Brisbane',
    'Australia/Lindeman',
    'Australia/Adelaide',
    'Australia/Darwin',
    'Australia/Perth',
    'Australia/Eucla',
    'Asia/Baku',
    'America/Barbados',
    'Asia/Dhaka',
    'Europe/Brussels',
    'Europe/Sofia',
    'Atlantic/Bermuda',
    'Asia/Brunei',
    'America/La_Paz',
    'America/Noronha',
    'America/Belem',
    'America/Fortaleza',
    'America/Recife',
    'America/Araguaina',
    'America/Maceio',
    'America/Bahia',
    'America/Sao_Paulo',
    'America/Campo_Grande',
    'America/Cuiaba',
    'America/Santarem',
    'America/Porto_Velho',
    'America/Boa_Vista',
    'America/Manaus',
    'America/Eirunepe',
    'America/Rio_Branco',
    'America/Nassau',
    'Asia/Thimphu',
    'Europe/Minsk',
    'America/Belize',
    'America/St_Johns',
    'America/Halifax',
    'America/Glace_Bay',
    'America/Moncton',
    'America/Goose_Bay',
    'America/Blanc-Sablon',
    'America/Toronto',
    'America/Nipigon',
    'America/Thunder_Bay',
    'America/Iqaluit',
    'America/Pangnirtung',
    'America/Atikokan',
    'America/Winnipeg',
    'America/Rainy_River',
    'America/Resolute',
    'America/Rankin_Inlet',
    'America/Regina',
    'America/Swift_Current',
    'America/Edmonton',
    'America/Cambridge_Bay',
    'America/Yellowknife',
    'America/Inuvik',
    'America/Creston',
    'America/Dawson_Creek',
    'America/Fort_Nelson',
    'America/Vancouver',
    'America/Whitehorse',
    'America/Dawson',
    'Indian/Cocos',
    'Europe/Zurich',
    'Africa/Abidjan',
    'Pacific/Rarotonga',
    'America/Santiago',
    'America/Punta_Arenas',
    'Pacific/Easter',
    'Asia/Shanghai',
    'Asia/Urumqi',
    'America/Bogota',
    'America/Costa_Rica',
    'America/Havana',
    'Atlantic/Cape_Verde',
    'America/Curacao',
    'Indian/Christmas',
    'Asia/Nicosia',
    'Asia/Famagusta',
    'Europe/Prague',
    'Europe/Berlin',
    'Europe/Copenhagen',
    'America/Santo_Domingo',
    'Africa/Algiers',
    'America/Guayaquil',
    'Pacific/Galapagos',
    'Europe/Tallinn',
    'Africa/Cairo',
    'Africa/El_Aaiun',
    'Europe/Madrid',
    'Africa/Ceuta',
    'Atlantic/Canary',
    'Europe/Helsinki',
    'Pacific/Fiji',
    'Atlantic/Stanley',
    'Pacific/Chuuk',
    'Pacific/Pohnpei',
    'Pacific/Kosrae',
    'Atlantic/Faroe',
    'Europe/Paris',
    'Europe/London',
    'Asia/Tbilisi',
    'America/Cayenne',
    'Africa/Accra',
    'Europe/Gibraltar',
    'America/Godthab',
    'America/Danmarkshavn',
    'America/Scoresbysund',
    'America/Thule',
    'Europe/Athens',
    'Atlantic/South_Georgia',
    'America/Guatemala',
    'Pacific/Guam',
    'Africa/Bissau',
    'America/Guyana',
    'Asia/Hong_Kong',
    'America/Tegucigalpa',
    'America/Port-au-Prince',
    'Europe/Budapest',
    'Asia/Jakarta',
    'Asia/Pontianak',
    'Asia/Makassar',
    'Asia/Jayapura',
    'Europe/Dublin',
    'Asia/Jerusalem',
    'Asia/Kolkata',
    'Indian/Chagos',
    'Asia/Baghdad',
    'Asia/Tehran',
    'Atlantic/Reykjavik',
    'Europe/Rome',
    'America/Jamaica',
    'Asia/Amman',
    'Asia/Tokyo',
    'Africa/Nairobi',
    'Asia/Bishkek',
    'Pacific/Tarawa',
    'Pacific/Enderbury',
    'Pacific/Kiritimati',
    'Asia/Pyongyang',
    'Asia/Seoul',
    'Asia/Almaty',
    'Asia/Qyzylorda',
    'Asia/Qostanay', 
    'Asia/Aqtobe',
    'Asia/Aqtau',
    'Asia/Atyrau',
    'Asia/Oral',
    'Asia/Beirut',
    'Asia/Colombo',
    'Africa/Monrovia',
    'Europe/Vilnius',
    'Europe/Luxembourg',
    'Europe/Riga',
    'Africa/Tripoli',
    'Africa/Casablanca',
    'Europe/Monaco',
    'Europe/Chisinau',
    'Pacific/Majuro',
    'Pacific/Kwajalein',
    'Asia/Yangon',
    'Asia/Ulaanbaatar',
    'Asia/Hovd',
    'Asia/Choibalsan',
    'Asia/Macau',
    'America/Martinique',
    'Europe/Malta',
    'Indian/Mauritius',
    'Indian/Maldives',
    'America/Mexico_City',
    'America/Cancun',
    'America/Merida',
    'America/Monterrey',
    'America/Matamoros',
    'America/Mazatlan',
    'America/Chihuahua',
    'America/Ojinaga',
    'America/Hermosillo',
    'America/Tijuana',
    'America/Bahia_Banderas',
    'Asia/Kuala_Lumpur',
    'Asia/Kuching',
    'Africa/Maputo',
    'Africa/Windhoek',
    'Pacific/Noumea',
    'Pacific/Norfolk',
    'Africa/Lagos',
    'America/Managua',
    'Europe/Amsterdam',
    'Europe/Oslo',
    'Asia/Kathmandu',
    'Pacific/Nauru',
    'Pacific/Niue',
    'Pacific/Auckland',
    'Pacific/Chatham',
    'America/Panama',
    'America/Lima',
    'Pacific/Tahiti',
    'Pacific/Marquesas',
    'Pacific/Gambier',
    'Pacific/Port_Moresby',
    'Pacific/Bougainville',
    'Asia/Manila',
    'Asia/Karachi',
    'Europe/Warsaw',
    'America/Miquelon',
    'Pacific/Pitcairn',
    'America/Puerto_Rico',
    'Asia/Gaza',
    'Asia/Hebron',
    'Europe/Lisbon',
    'Atlantic/Madeira',
    'Atlantic/Azores',
    'Pacific/Palau',
    'America/Asuncion',
    'Asia/Qatar',
    'Indian/Reunion',
    'Europe/Bucharest',
    'Europe/Belgrade',
    'Europe/Kaliningrad',
    'Europe/Moscow',
    'Europe/Simferopol',
    'Europe/Kirov',
    'Europe/Astrakhan',
    'Europe/Volgograd',
    'Europe/Saratov',
    'Europe/Ulyanovsk',
    'Europe/Samara',
    'Asia/Yekaterinburg',
    'Asia/Omsk',
    'Asia/Novosibirsk',
    'Asia/Barnaul',
    'Asia/Tomsk',
    'Asia/Novokuznetsk',
    'Asia/Krasnoyarsk',
    'Asia/Irkutsk',
    'Asia/Chita',
    'Asia/Yakutsk',
    'Asia/Khandyga',
    'Asia/Vladivostok',
    'Asia/Ust-Nera',
    'Asia/Magadan',
    'Asia/Sakhalin',
    'Asia/Srednekolymsk',
    'Asia/Kamchatka',
    'Asia/Anadyr',
    'Asia/Riyadh',
    'Pacific/Guadalcanal',
    'Indian/Mahe',
    'Africa/Khartoum',
    'Europe/Stockholm',
    'Asia/Singapore',
    'America/Paramaribo',
    'Africa/Juba',
    'Africa/Sao_Tome',
    'America/El_Salvador',
    'Asia/Damascus',
    'America/Grand_Turk',
    'Africa/Ndjamena',
    'Indian/Kerguelen',
    'Asia/Bangkok',
    'Asia/Dushanbe',
    'Pacific/Fakaofo',
    'Asia/Dili',
    'Asia/Ashgabat',
    'Africa/Tunis',
    'Pacific/Tongatapu',
    'Europe/Istanbul',
    'America/Port_of_Spain',
    'Pacific/Funafuti',
    'Asia/Taipei',
    'Europe/Kiev',
    'Europe/Uzhgorod',
    'Europe/Zaporozhye',
    'Pacific/Wake',
    'America/New_York',
    'America/Detroit',
    'America/Kentucky/Louisville',
    'America/Kentucky/Monticello',
    'America/Indiana/Indianapolis',
    'America/Indiana/Vincennes',
    'America/Indiana/Winamac',
    'America/Indiana/Marengo',
    'America/Indiana/Petersburg',
    'America/Indiana/Vevay',
    'America/Chicago',
    'America/Indiana/Tell_City',
    'America/Indiana/Knox',
    'America/Menominee',
    'America/North_Dakota/Center',
    'America/North_Dakota/New_Salem',
    'America/North_Dakota/Beulah',
    'America/Denver',
    'America/Boise',
    'America/Phoenix',
    'America/Los_Angeles',
    'America/Anchorage',
    'America/Juneau',
    'America/Sitka',
    'America/Metlakatla',
    'America/Yakutat',
    'America/Nome',
    'America/Adak',
    'Pacific/Honolulu',
    'America/Montevideo',
    'Asia/Samarkand',
    'Asia/Tashkent',
    'America/Caracas',
    'Asia/Ho_Chi_Minh',
    'Pacific/Efate',
    'Pacific/Wallis',
    'Pacific/Apia',
    'Africa/Johannesburg'
];

Detecting Browser Autofill

My solution is:

    $.fn.onAutoFillEvent = function (callback) {
        var el = $(this),
            lastText = "",
            maxCheckCount = 10,
            checkCount = 0;

        (function infunc() {
            var text = el.val();

            if (text != lastText) {
                lastText = text;
                callback(el);
            }
            if (checkCount > maxCheckCount) {
                return false;
            }
            checkCount++;
            setTimeout(infunc, 100);
        }());
    };

  $(".group > input").each(function (i, element) {
      var el = $(element);

      el.onAutoFillEvent(
          function () {
              el.addClass('used');
          }
      );
  });

MySQL 'Order By' - sorting alphanumeric correctly

I had some good results with

SELECT alphanumeric, integer FROM sorting_test ORDER BY CAST(alphanumeric AS UNSIGNED), alphanumeric ASC

Load json from local file with http.get() in angular 2

I found that the simplest way to achieve this is by adding the file.json under folder: assets.

No need to edit: .angular-cli.json

Service

@Injectable()
export class DataService {
  getJsonData(): Promise<any[]>{
    return this.http.get<any[]>('http://localhost:4200/assets/data.json').toPromise();
  }
}

Component

private data: any[];

constructor(private dataService: DataService) {}

ngOnInit() {
    data = [];
    this.dataService.getJsonData()
      .then( result => {
        console.log('ALL Data: ', result);
        data = result;
      })
      .catch( error => {
        console.log('Error Getting Data: ', error);
      });
  }

Extra:

Ideally, you only want to have this in a dev environment so to be bulletproof. create a variable on your environment.ts

export const environment = {
  production: false,
  baseAPIUrl: 'http://localhost:4200/assets/data.json'
};

Then replace the URL on the http.get for ${environment.baseAPIUrl}

And the environment.prod.ts can have the production API URL.

Hope this helps!

How to use ? : if statements with Razor and inline code blocks

In most cases the solution of CD.. will work perfectly fine. However I had a bit more twisted situation:

 @(String.IsNullOrEmpty(Model.MaidenName) ? "&nbsp;" : Model.MaidenName)

This would print me "&nbsp;" in my page, respectively generate the source &amp;nbsp;. Now there is a function Html.Raw("&nbsp;") which is supposed to let you write source code, except in this constellation it throws a compiler error:

Compiler Error Message: CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Web.IHtmlString' and 'string'

So I ended up writing a statement like the following, which is less nice but works even in my case:

@if (String.IsNullOrEmpty(Model.MaidenName)) { @Html.Raw("&nbsp;") } else { @Model.MaidenName } 

Note: interesting thing is, once you are inside the curly brace, you have to restart a Razor block.

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications?

objective-c is the primary language used.

i believe there is a mono touch framework that can be used with c#

Adobe also is working in some tools, one is this iPhone Packager which can utilize actionscript code

How to create strings containing double quotes in Excel formulas?

Have you tried escaping with a double-quote?

= "Maurice ""The Rocket"" Richard"

How to set the 'selected option' of a select dropdown list with jquery

One thing I don't think anyone has mentioned, and a stupid mistake I've made in the past (especially when dynamically populating selects). jQuery's .val() won't work for a select input if there isn't an option with a value that matches the value supplied.

Here's a fiddle explaining -> http://jsfiddle.net/go164zmt/

<select id="example">
    <option value="0">Test0</option>
    <option value="1">Test1</option>
</select>

$("#example").val("0");
alert($("#example").val());
$("#example").val("1");
alert($("#example").val());

//doesn't exist
$("#example").val("2");
//and thus returns null
alert($("#example").val());

Converting a character code to char (VB.NET)

You could use the Chr(int) function

Set IDENTITY_INSERT ON is not working

Here's Microsoft's write up on using SET IDENTITY_INSERT, which might be helpful to others seeing this post if they, like me, found this post when trying to recreate deleted records while maintaining the original identity column value.

to recreate deleted records with original identity column value: http://msdn.microsoft.com/en-us/library/aa259221(v=sql.80).aspx

How to generate .NET 4.0 classes from xsd?

The command that worked in my case was:

xsd /c your.xsd 

Iterating through a list to render multiple widgets in Flutter?

You can use ListView to render a list of items. But if you don't want to use ListView, you can create a method which returns a list of Widgets (Texts in your case) like below:

var list = ["one", "two", "three", "four"];

    @override
    Widget build(BuildContext context) {
      return new MaterialApp(
          home: new Scaffold(
        appBar: new AppBar(
          title: new Text('List Test'),
        ),
        body: new Center(
          child: new Column( // Or Row or whatever :)
            children: createChildrenTexts(),
          ),
        ),
      ));
    }

     List<Text> createChildrenTexts() {
    /// Method 1
//    List<Text> childrenTexts = List<Text>();
//    for (String name in list) {
//      childrenTexts.add(new Text(name, style: new TextStyle(color: Colors.red),));
//    }
//    return childrenTexts;

    /// Method 2
    return list.map((text) => Text(text, style: TextStyle(color: Colors.blue),)).toList();
  }

C# Threading - How to start and stop a thread

This is how I do it...

public class ThreadA {
    public ThreadA(object[] args) {
        ...
    }
    public void Run() {
        while (true) {
            Thread.sleep(1000); // wait 1 second for something to happen.
            doStuff();
            if(conditionToExitReceived) // what im waiting for...
                break;
        }
        //perform cleanup if there is any...
    }
}

Then to run this in its own thread... ( I do it this way because I also want to send args to the thread)

private void FireThread(){
    Thread thread = new Thread(new ThreadStart(this.startThread));
    thread.start();
}
private void (startThread){
    new ThreadA(args).Run();
}

The thread is created by calling "FireThread()"

The newly created thread will run until its condition to stop is met, then it dies...

You can signal the "main" with delegates, to tell it when the thread has died.. so you can then start the second one...

Best to read through : This MSDN Article

How to get Printer Info in .NET?

This should work.

using System.Drawing.Printing;

...

PrinterSettings ps = new PrinterSettings();
ps.PrinterName = "The printer name"; // Load the appropriate printer's setting

After that, the various properties of PrinterSettings can be read.

Note that ps.isValid() can see if the printer actually exists.

Edit: One additional comment. Microsoft recommends you use a PrintDocument and modify its PrinterSettings rather than creating a PrinterSettings directly.

How to tell a Mockito mock object to return something different the next time it is called?

First of all don't make the mock static. Make it a private field. Just put your setUp class in the @Before not @BeforeClass. It might be run a bunch, but it's cheap.

Secondly, the way you have it right now is the correct way to get a mock to return something different depending on the test.

Switching the order of block elements with CSS

Update: Two lightweight CSS solutions:

Using flex, flex-flow and order:

Example1: Demo Fiddle

    body{
        display:flex;
        flex-flow: column;
    }
    #blockA{
        order:4;
    }
    #blockB{
        order:3;
    }
    #blockC{
        order:2;
    }

Alternatively, reverse the Y scale:

Example2: Demo Fiddle

body{
    -webkit-transform: scaleY(-1);
    transform: scaleY(-1);
}
div{
    -webkit-transform: scaleY(-1);
    transform: scaleY(-1);
}

C# switch statement limitations - why?

Microsoft finally heard you!

Now with C# 7 you can:

switch(shape)
{
case Circle c:
    WriteLine($"circle with radius {c.Radius}");
    break;
case Rectangle s when (s.Length == s.Height):
    WriteLine($"{s.Length} x {s.Height} square");
    break;
case Rectangle r:
    WriteLine($"{r.Length} x {r.Height} rectangle");
    break;
default:
    WriteLine("<unknown shape>");
    break;
case null:
    throw new ArgumentNullException(nameof(shape));
}

java.lang.NoClassDefFoundError in junit

The reason for this is "hamcrest-core" jar is not in classpath as it doesn't comes directly with junit jar. So there are two ways to resolve this:

  1. select project -> buildpath -> add libraries and select junit (It contains both junit & hamcrest-core)
  2. download hamcrest-core from maven repo and add this to your classpath.

How to increase editor font size?

Very Simple .

Go to File then Settings then Select Editor then Font and change the size .

File -> Settings -> Editor -> Colors & Fonts -> Font.

How to get the size of the current screen in WPF?

I created a little wrapper around the Screen from System.Windows.Forms, currently everything works... Not sure about the "device independent pixels", though.

public class WpfScreen
{
    public static IEnumerable<WpfScreen> AllScreens()
    {
        foreach (Screen screen in System.Windows.Forms.Screen.AllScreens)
        {
            yield return new WpfScreen(screen);
        }
    }

    public static WpfScreen GetScreenFrom(Window window)
    {
        WindowInteropHelper windowInteropHelper = new WindowInteropHelper(window);
        Screen screen = System.Windows.Forms.Screen.FromHandle(windowInteropHelper.Handle);
        WpfScreen wpfScreen = new WpfScreen(screen);
        return wpfScreen;
    }

    public static WpfScreen GetScreenFrom(Point point)
    {
        int x = (int) Math.Round(point.X);
        int y = (int) Math.Round(point.Y);

        // are x,y device-independent-pixels ??
        System.Drawing.Point drawingPoint = new System.Drawing.Point(x, y);
        Screen screen = System.Windows.Forms.Screen.FromPoint(drawingPoint);
        WpfScreen wpfScreen = new WpfScreen(screen);

        return wpfScreen;
    }

    public static WpfScreen Primary
    {
        get { return new WpfScreen(System.Windows.Forms.Screen.PrimaryScreen); }
    }

    private readonly Screen screen;

    internal WpfScreen(System.Windows.Forms.Screen screen)
    {
        this.screen = screen;
    }

    public Rect DeviceBounds
    {
        get { return this.GetRect(this.screen.Bounds); }
    }

    public Rect WorkingArea
    {
        get { return this.GetRect(this.screen.WorkingArea); }
    }

    private Rect GetRect(Rectangle value)
    {
        // should x, y, width, height be device-independent-pixels ??
        return new Rect
                   {
                       X = value.X,
                       Y = value.Y,
                       Width = value.Width,
                       Height = value.Height
                   };
    }

    public bool IsPrimary
    {
        get { return this.screen.Primary; }
    }

    public string DeviceName
    {
        get { return this.screen.DeviceName; }
    }
}

Resize Google Maps marker icon image

If the original size is 100 x 100 and you want to scale it to 50 x 50, use scaledSize instead of Size.

var icon = {
    url: "../res/sit_marron.png", // url
    scaledSize: new google.maps.Size(50, 50), // scaled size
    origin: new google.maps.Point(0,0), // origin
    anchor: new google.maps.Point(0, 0) // anchor
};

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(lat, lng),
    map: map,
    icon: icon
});

Convert java.time.LocalDate into java.util.Date type

Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

That assumes your date chooser uses the system default timezone to transform dates into strings.

HTTP Error 503. The service is unavailable. App pool stops on accessing website

If you have McAfee HIPS and if you see the following error in event viewer application log:

The Module DLL C:\Windows\System32\inetsrv\HipIISEngineStub.dll failed to load.
The data is the error.

Then the following resolved the issue in my case: https://kc.mcafee.com/corporate/index?page=content&id=KB72677&actp=LIST

Quote from the page:

  1. Click Start, Run, type explorer and click OK.
  2. Navigate to: %windir%\system32\inetsrv\config
  3. Open the file applicationHost.config as Administrator for editing in Notepad.
  4. Edit the <globalModules> section and remove the following line:
    <add name="MfeEngine" image="%windir%\System32\inetsrv\HipIISEngineStub.dll" />

  5. Edit the <modules> section and remove the following line:
    <add name="MfeEngine" />

  6. After you have finished editing the applicationHost.config file, save the file, then restart the IIS server using iisreset or by restarting the system.

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

You can use the following command to change your file mode back. git add --chmod=+x -- filename Then commit to the branch.

how to make twitter bootstrap submenu to open on the left side?

If you're using LESS CSS, I wrote a little mixin to move the dropdown with the connecting arrow:

.dropdown-menu-shift( @num-pixels, @arrow-position: 10px ) {  // mixin to shift the dropdown menu
    left: @num-pixels;
    &:before { left: -@num-pixels + @arrow-position; }        // triangle outline
    &:after  { left: -@num-pixels + @arrow-position + 1px; }  // triangle internal
}

Then to move a .dropdown-menu with an id of dropdown-menu-x for example, you can do:

#dropdown-menu-x {
    .dropdown-menu-shift( -100px );
}

Pass correct "this" context to setTimeout callback?

In browsers other than Internet Explorer, you can pass parameters to the function together after the delay:

var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);

So, you can do this:

var timeoutID = window.setTimeout(function (self) {
  console.log(self); 
}, 500, this);

This is better in terms of performance than a scope lookup (caching this into a variable outside of the timeout / interval expression), and then creating a closure (by using $.proxy or Function.prototype.bind).

The code to make it work in IEs from Webreflection:

/*@cc_on
(function (modifierFn) {
  // you have to invoke it as `window`'s property so, `window.setTimeout`
  window.setTimeout = modifierFn(window.setTimeout);
  window.setInterval = modifierFn(window.setInterval);
})(function (originalTimerFn) {
    return function (callback, timeout){
      var args = [].slice.call(arguments, 2);
      return originalTimerFn(function () { 
        callback.apply(this, args) 
      }, timeout);
    }
});
@*/

How and when to use SLEEP() correctly in MySQL?

SELECT ...
SELECT SLEEP(5);
SELECT ...

But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?

"Cannot create an instance of OLE DB provider" error as Windows Authentication user

In SQL Server Enterprise Manager, open \Server Objects\Linked Servers\Providers, right click on the OraOLEDB.Oracle provider, select properties and check the "Allow inprocess" option. Recreate your linked server and test again.

You can also execute the following query if you don't have access to SQL Server Management Studio :

EXEC master.dbo.sp_MSset_oledb_prop N'OraOLEDB.Oracle', N'AllowInProcess', 1

node.js, socket.io with SSL

Use a secure URL for your initial connection, i.e. instead of "http://" use "https://". If the WebSocket transport is chosen, then Socket.IO should automatically use "wss://" (SSL) for the WebSocket connection too.

Update:

You can also try creating the connection using the 'secure' option:

var socket = io.connect('https://localhost', {secure: true});

if var == False

Python uses not instead of ! for negation.

Try

if not var: 
    print "learnt stuff"

instead

Common CSS Media Queries Break Points

Your break points look really good. I've tried 768px on Samsung tablets and it goes beyond that, so I really like the 961px. You don't necessarily need all of them if you use responsive CSS techniques, like % width/max-width for blocks and images (text as well).

Difference between nVidia Quadro and Geforce cards?

Hardware wise the Quadro and GeForce cards are often idential. Indeed it is sometimes possible to convert some models from GeForce into Quadro by simply uploading new firmware and changing a couple resistor jumpers.

The difference is in the intended market and hence cost.

Quadro cards are intended for CAD. High end CAD software still uses OpenGL, whereas games and lower end CAD software use Direct3D (aka DirectX).

Quadro cards simply have firmware that is optimised for OpenGL. In the early days OpenGL was better and faster than Direct3D but now there is little difference. Gaming cards only support a very limited set of OpenGL, hence they don't run it very well.

CAD companies, e.g. Dassault with SolidWorks actively push high end cards by offering no support for DirectX with any level of performance.

Other CAD companies such as Altium, with Altium Designer, made the decision that forcing their customers to buy more expensive cards is not worthwhile when Direct3D is as good (if not better these days) than OpenGL.

Because of the cost, there are often other differences in the hardware, such as less use of overclocking, more memory etc, but these have relatively minor effects compared with the firmware support.

Force a screen update in Excel VBA

Specifically, if you are dealing with a UserForm, then you might try the Repaint method. You might encounter an issue with DoEvents if you are using event triggers in your form. For instance, any keys pressed while a function is running will be sent by DoEvents The keyboard input will be processed before the screen is updated, so if you are changing cells on a spreadsheet by holding down one of the arrow keys on the keyboard, then the cell change event will keep firing before the main function finishes.

A UserForm will not be refreshed in some cases, because DoEvents will fire the events; however, Repaint will update the UserForm and the user will see the changes on the screen even when another event immediately follows the previous event.

In the UserForm code it is as simple as:

Me.Repaint

Can you append strings to variables in PHP?

PHP syntax is little different in case of concatenation from JavaScript. Instead of (+) plus a (.) period is used for string concatenation.

<?php

$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
    $selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
    $selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;

?>

Where is JAVA_HOME on macOS Mojave (10.14) to Lion (10.7)?

For OS X you can do:

export JAVA_HOME=`/System/Library/Frameworks/JavaVM.framework/Versions/Current/commands/java_home`

How to make a list of n numbers in Python and randomly select any number?

You can create the enumeration of the elements by something like this:

mylist = list(xrange(10))

Then you can use the random.choice function to select your items:

import random
...
random.choice(mylist)

As Asim Ihsan correctly stated, my answer did not address the full problem of the OP. To remove the values from the list, simply list.remove() can be called:

import random
...
value = random.choice(mylist)
mylist.remove(value)

As takataka pointed out, the xrange builtin function was renamed to range in Python 3.

Is ncurses available for windows?

Such a thing probably does not exist "as-is". It doesn't really exist on Linux or other UNIX-like operating systems either though.

ncurses is only a library that helps you manage interactions with the underlying terminal environment. But it doesn't provide a terminal emulator itself.

The thing that actually displays stuff on the screen (which in your requirement is listed as "native resizable win32 windows") is usually called a Terminal Emulator. If you don't like the one that comes with Windows (you aren't alone; no person on Earth does) there are a few alternatives. There is Console, which in my experience works sometimes and appears to just wrap an underlying Windows terminal emulator (I don't know for sure, but I'm guessing, since there is a menu option to actually get access to that underlying terminal emulator, and sure enough an old crusty Windows/DOS box appears which mirrors everything in the Console window).

A better option

Another option, which may be more appealing is puttycyg. It hooks in to Putty (which, coming from a Linux background, is pretty close to what I'm used to, and free) but actually accesses an underlying cygwin instead of the Windows command interpreter (CMD.EXE). So you get all the benefits of Putty's awesome terminal emulator, as well as nice ncurses (and many other) libraries provided by cygwin. Add a couple command line arguments to the Shortcut that launches Putty (or the Batch file) and your app can be automatically launched without going through Putty's UI.

How to automatically crop and center an image

I created an angularjs directive using @Russ's and @Alex's answers

Could be interesting in 2014 and beyond :P

html

<div ng-app="croppy">
  <cropped-image src="http://placehold.it/200x200" width="100" height="100"></cropped-image>
</div>

js

angular.module('croppy', [])
  .directive('croppedImage', function () {
      return {
          restrict: "E",
          replace: true,
          template: "<div class='center-cropped'></div>",
          link: function(scope, element, attrs) {
              var width = attrs.width;
              var height = attrs.height;
              element.css('width', width + "px");
              element.css('height', height + "px");
              element.css('backgroundPosition', 'center center');
              element.css('backgroundRepeat', 'no-repeat');
              element.css('backgroundImage', "url('" + attrs.src + "')");
          }
      }
  });

fiddle link

Class Diagrams in VS 2017

A further note on Dmitry's 2017 answer. I opened up

C:\Program Files (x86)\Microsoft Visual 
Studio\2017\Community\MSBuild\Microsoft\VisualStudio\Managed\ 
Microsoft.CSharp.DesignTime.targets 

and went to the <ProjectCapability> element. I already had this:

<ProjectCapability Include="
                          CSharp;
                          Managed;
                          ClassDesigner**;**" />

with ClassDesigner already there, and yet I was still unable to drag items to my hack-made Diagram.cd using the XML editing method Dmitry mentioned (

Manually create text file, say MyClasses.cd with following content:

<?xml version="1.0" encoding="utf-8"?> <ClassDiagram MajorVersion="1"
> MinorVersion="1">
>     <Font Name="Segoe UI" Size="9" /> </ClassDiagram>

). But when I took off the semicolon off 'ClassDesigner' in that element then reopened Visual Studio, voila, I was able to drag classes from my Solution Explorer to my Diagram.cd window.

So in conclusion, this element in Microsoft.CSharp.DesignTime.targets worked:

<ProjectCapability Include="
                              CSharp;
                              Managed;
                              ClassDesigner" />

I am using VS 2019, version 16.1.5.

Is there a method for String conversion to Title Case?

If I may submit my take on the solution...

The following method is based on the one that dfa posted. It makes the following major change (which is suited to the solution I needed at the time): it forces all characters in the input string into lower case unless it is immediately preceded by an "actionable delimiter" in which case the character is coerced into upper case.

A major limitation of my routine is that it makes the assumption that "title case" is uniformly defined for all locales and is represented by the same case conventions I have used and so it is less useful than dfa's code in that respect.

public static String toDisplayCase(String s) {

    final String ACTIONABLE_DELIMITERS = " '-/"; // these cause the character following
                                                 // to be capitalized
    
    StringBuilder sb = new StringBuilder();
    boolean capNext = true;

    for (char c : s.toCharArray()) {
        c = (capNext)
                ? Character.toUpperCase(c)
                : Character.toLowerCase(c);
        sb.append(c);
        capNext = (ACTIONABLE_DELIMITERS.indexOf((int) c) >= 0); // explicit cast not needed
    }
    return sb.toString();
}

TEST VALUES

a string

maRTin o'maLLEY

john wilkes-booth

YET ANOTHER STRING

OUTPUTS

A String

Martin O'Malley

John Wilkes-Booth

Yet Another String

HTML input arrays

As far as I know, there isn't anything on the HTML specs because browsers aren't supposed to do anything different for these fields. They just send them as they normally do and PHP is the one that does the parsing into an array, as do other languages.

How to increment a datetime by one day?

date = datetime.datetime(2003,8,1,12,4,5)
for i in range(5): 
    date += datetime.timedelta(days=1)
    print(date) 

Cannot refer to a non-final variable inside an inner class defined in a different method

One solution I have noticed isn't mentioned (unless I missed it, if I did please correct me), is the use of a class variable. Ran into this issue attempting to run a new thread within a method: new Thread(){ Do Something }.

Calling doSomething() from the following will work. You do not necessarily have to declare it final, just need to change the scope of the variable so it is not collected before the innerclass. This is unless of course your process is huge and changing the scope might create some sort of conflict. I didn't want to make my variable final as it was in no way a final/constant.

public class Test
{

    protected String var1;
    protected String var2;

    public void doSomething()
    {
        new Thread()
        {
            public void run()
            {
                System.out.println("In Thread variable 1: " + var1);
                System.out.println("In Thread variable 2: " + var2);
            }
        }.start();
    }

}

Is there a way to provide named parameters in a function call in JavaScript?

Another way would be to use attributes of a suitable object, e.g. like so:

function plus(a,b) { return a+b; };

Plus = { a: function(x) { return { b: function(y) { return plus(x,y) }}}, 
         b: function(y) { return { a: function(x) { return plus(x,y) }}}};

sum = Plus.a(3).b(5);

Of course for this made up example it is somewhat meaningless. But in cases where the function looks like

do_something(some_connection_handle, some_context_parameter, some_value)

it might be more useful. It also could be combined with "parameterfy" idea to create such an object out of an existing function in a generic way. That is for each parameter it would create a member that can evaluate to a partial evaluated version of the function.

This idea is of course related to Schönfinkeling aka Currying.

UEFA/FIFA scores API

http://api.football-data.org/index is free and useful. The API is in active development, stable and recently the first versioned release called alpha was put online. Check the blog section to follow updates and changes.

VBoxManage: error: Failed to create the host-only adapter

Windows 10 Pro VirtualBox 5.2.12

In my case I had to edit the Host Only Ethernet Adapter in the VirtualBox GUI. Click Global Tools -> Host Network Manager -> Select the ethernet adapter, then click Properties. Mine was set to configure automatically, and the IP address it was trying to use was different than what I was trying to use with drupal-vm and vagrant. I just had to change that to manual and correct the IP address. I hope this helps someone else.

Xampp MySQL not starting - "Attempting to start MySQL service..."

I can share how I solved the problem in my case.

It seems that somehow I had mySQL Server 5.7 installed. It didn't show on Add/Remove Programs list in Windows tough so I wasn't aware of it. I marked that after I looked up the XAMPP log.

Just after XAMPP launched it has shown in the log that there is a conflict in mySQL and indicated the folder where my mySQL Server 5.7 is installed. I removed mySQL 5.7 manually from Program Files (x86) and ProgramData folder, restarted and XAMPP mySQL started normally then.

I've tried only stopping the mySQL service but for me it didn't work. Only manually deleting all mySQL 5.7 folders seemed to have helped.

What is the best algorithm for overriding GetHashCode?

Up until recently my answer would have been very close to Jon Skeet's here. However, I recently started a project which used power-of-two hash tables, that is hash tables where the size of the internal table is 8, 16, 32, etc. There's a good reason for favouring prime-number sizes, but there are some advantages to power-of-two sizes too.

And it pretty much sucked. So after a bit of experimentation and research I started re-hashing my hashes with the following:

public static int ReHash(int source)
{
  unchecked
  {
    ulong c = 0xDEADBEEFDEADBEEF + (ulong)source;
    ulong d = 0xE2ADBEEFDEADBEEF ^ c;
    ulong a = d += c = c << 15 | c >> -15;
    ulong b = a += d = d << 52 | d >> -52;
    c ^= b += a = a << 26 | a >> -26;
    d ^= c += b = b << 51 | b >> -51;
    a ^= d += c = c << 28 | c >> -28;
    b ^= a += d = d << 9 | d >> -9;
    c ^= b += a = a << 47 | a >> -47;
    d ^= c += b << 54 | b >> -54;
    a ^= d += c << 32 | c >> 32;
    a += d << 25 | d >> -25;
    return (int)(a >> 1);
  }
}

And then my power-of-two hash table didn't suck any more.

This disturbed me though, because the above shouldn't work. Or more precisely, it shouldn't work unless the original GetHashCode() was poor in a very particular way.

Re-mixing a hashcode can't improve a great hashcode, because the only possible effect is that we introduce a few more collisions.

Re-mixing a hash code can't improve a terrible hash code, because the only possible effect is we change e.g. a large number of collisions on value 53 to a large number of value 18,3487,291.

Re-mixing a hash code can only improve a hash code that did at least fairly well in avoiding absolute collisions throughout its range (232 possible values) but badly at avoiding collisions when modulo'd down for actual use in a hash table. While the simpler modulo of a power-of-two table made this more apparent, it was also having a negative effect with the more common prime-number tables, that just wasn't as obvious (the extra work in rehashing would outweigh the benefit, but the benefit would still be there).

Edit: I was also using open-addressing, which would also have increased the sensitivity to collision, perhaps more so than the fact it was power-of-two.

And well, it was disturbing how much the string.GetHashCode() implementations in .NET (or study here) could be improved this way (on the order of tests running about 20-30 times faster due to fewer collisions) and more disturbing how much my own hash codes could be improved (much more than that).

All the GetHashCode() implementations I'd coded in the past, and indeed used as the basis of answers on this site, were much worse than I'd throught. Much of the time it was "good enough" for much of the uses, but I wanted something better.

So I put that project to one side (it was a pet project anyway) and started looking at how to produce a good, well-distributed hash code in .NET quickly.

In the end I settled on porting SpookyHash to .NET. Indeed the code above is a fast-path version of using SpookyHash to produce a 32-bit output from a 32-bit input.

Now, SpookyHash is not a nice quick to remember piece of code. My port of it is even less so because I hand-inlined a lot of it for better speed*. But that's what code reuse is for.

Then I put that project to one side, because just as the original project had produced the question of how to produce a better hash code, so that project produced the question of how to produce a better .NET memcpy.

Then I came back, and produced a lot of overloads to easily feed just about all of the native types (except decimal†) into a hash code.

It's fast, for which Bob Jenkins deserves most of the credit because his original code I ported from is faster still, especially on 64-bit machines which the algorithm is optimised for‡.

The full code can be seen at https://bitbucket.org/JonHanna/spookilysharp/src but consider that the code above is a simplified version of it.

However, since it's now already written, one can make use of it more easily:

public override int GetHashCode()
{
  var hash = new SpookyHash();
  hash.Update(field1);
  hash.Update(field2);
  hash.Update(field3);
  return hash.Final().GetHashCode();
}

It also takes seed values, so if you need to deal with untrusted input and want to protect against Hash DoS attacks you can set a seed based on uptime or similar, and make the results unpredictable by attackers:

private static long hashSeed0 = Environment.TickCount;
private static long hashSeed1 = DateTime.Now.Ticks;
public override int GetHashCode()
{
  //produce different hashes ever time this application is restarted
  //but remain consistent in each run, so attackers have a harder time
  //DoSing the hash tables.
  var hash = new SpookyHash(hashSeed0, hashSeed1);
  hash.Update(field1);
  hash.Update(field2);
  hash.Update(field3);
  return hash.Final().GetHashCode();
}

*A big surprise in this is that hand-inlining a rotation method that returned (x << n) | (x >> -n) improved things. I would have been sure that the jitter would have inlined that for me, but profiling showed otherwise.

decimal isn't native from the .NET perspective though it is from the C#. The problem with it is that its own GetHashCode() treats precision as significant while its own Equals() does not. Both are valid choices, but not mixed like that. In implementing your own version, you need to choose to do one, or the other, but I can't know which you'd want.

‡By way of comparison. If used on a string, the SpookyHash on 64 bits is considerably faster than string.GetHashCode() on 32 bits which is slightly faster than string.GetHashCode() on 64 bits, which is considerably faster than SpookyHash on 32 bits, though still fast enough to be a reasonable choice.

Base64 Decoding in iOS 7+

In case you want to write fallback code, decoding from base64 has been present in iOS since the very beginning by caveat of NSURL:

NSURL *URL = [NSURL URLWithString:
      [NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
           base64String]];

return [NSData dataWithContentsOfURL:URL];

Python convert csv to xlsx

With my library pyexcel,

 $ pip install pyexcel pyexcel-xlsx

you can do it in one command line:

from pyexcel.cookbook import merge_all_to_a_book
# import pyexcel.ext.xlsx # no longer required if you use pyexcel >= 0.2.2 
import glob


merge_all_to_a_book(glob.glob("your_csv_directory/*.csv"), "output.xlsx")

Each csv will have its own sheet and the name will be their file name.

How to enable Google Play App Signing

There is a much simpler solution that will take a minute.

  1. In google play console, select Release management -> App signing
  2. Choose the first option, the one with Generate encrypted private key with Android Studio (or something like that; I cannot turn back to see that page anymore)
  3. In Android Studio generate your Android App Bundle (.aap file) from Build -> Generate Signed Bundle / APK..., choose Android App Bundle option and don't forget to check Export Encrypted key (needed to enroll your app Google Play App signing) option. If you do not have a keystore generated, generate one ad-hoc.
  4. Now the "tricky" part. After the .aap is generated, Android Studio will pop up a notification in the bottom right corner containing a path to the location where the .aap file is saved. In the same notification, if you will expand it you will find another link to the path where the private key was saved (called private_key.pepk). If you miss this notification, don't worry, just open Event Log window by clicking the Event Log button on the bottom right side and you will find the same info. Open that location.For me was C:\Users\yourUser\.android

enter image description here

  1. Go back in browser and press APP SIGNING PRIVATE KEY button and browse to the private key location on your computer.

Done!

Now you are able to upload your release that you generated earlier :) Good luck!

Git: Pull from other remote

upstream in the github example is just the name they've chosen to refer to that repository. You may choose any that you like when using git remote add. Depending on what you select for this name, your git pull usage will change. For example, if you use:

git remote add upstream git://github.com/somename/original-project.git

then you would use this to pull changes:

git pull upstream master

But, if you choose origin for the name of the remote repo, your commands would be:

To name the remote repo in your local config: git remote add origin git://github.com/somename/original-project.git

And to pull: git pull origin master

Sorting a DropDownList? - C#, ASP.NET

You may not have access to the SQL, but if you have the DataSet or DataTable, you can certainly call the Sort() method.

How do I syntax check a Bash script without running it?

Time changes everything. Here is a web site which provide online syntax checking for shell script.

I found it is very powerful detecting common errors.

enter image description here

About ShellCheck

ShellCheck is a static analysis and linting tool for sh/bash scripts. It's mainly focused on handling typical beginner and intermediate level syntax errors and pitfalls where the shell just gives a cryptic error message or strange behavior, but it also reports on a few more advanced issues where corner cases can cause delayed failures.

Haskell source code is available on GitHub!

Convert int to ASCII and back in Python

>>> ord("a")
97
>>> chr(97)
'a'

What exactly is nullptr?

How is it a keyword and an instance of a type?

This isn't surprising. Both true and false are keywords and as literals they have a type ( bool ). nullptr is a pointer literal of type std::nullptr_t, and it's a prvalue (you cannot take the address of it using &).

  • 4.10 about pointer conversion says that a prvalue of type std::nullptr_t is a null pointer constant, and that an integral null pointer constant can be converted to std::nullptr_t. The opposite direction is not allowed. This allows overloading a function for both pointers and integers, and passing nullptr to select the pointer version. Passing NULL or 0 would confusingly select the int version.

  • A cast of nullptr_t to an integral type needs a reinterpret_cast, and has the same semantics as a cast of (void*)0 to an integral type (mapping implementation defined). A reinterpret_cast cannot convert nullptr_t to any pointer type. Rely on the implicit conversion if possible or use static_cast.

  • The Standard requires that sizeof(nullptr_t) be sizeof(void*).

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

Some workaround solutions are:

1. Split up IN clause

Split IN clause to multiple IN clauses where literals are less than 1000 and combine them using OR clauses:

Split the original "WHERE" clause from one "IN" condition to several "IN" condition:

Select id from x where id in (1, 2, ..., 1000,…,1500);

To:

Select id from x where id in (1, 2, ..., 999) OR id in (1000,...,1500);

2. Use tuples

The limit of 1000 applies to sets of single items: (x) IN ((1), (2), (3), ...). There is no limit if the sets contain two or more items: (x, 0) IN ((1,0), (2,0), (3,0), ...):

Select id from x where (x.id, 0) IN ((1, 0), (2, 0), (3, 0),.....(n, 0));

3. Use temporary table

Select id from x where id in (select id from <temporary-table>);

What is a reasonable code coverage % for unit tests (and why)?

I don't think there can be such a B/W rule.
Code should be reviewed, with particular attention to the critical details.
However, if it hasn't been tested, it has a bug!

Is there a Google Chrome-only CSS hack?

You could use javascript. The other answers to date seem to also target Safari.

if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
    alert("You'll only see this in Chrome");
    $('#someID').css('background-position', '10px 20px');
}

I lose my data when the container exits

You need to commit the changes you make to the container and then run it. Try this:

sudo docker pull ubuntu

sudo docker run ubuntu apt-get install -y ping

Then get the container id using this command:

sudo docker ps -l

Commit changes to the container:

sudo docker commit <container_id> iman/ping 

Then run the container:

sudo docker run iman/ping ping www.google.com

This should work.

Strip HTML from Text JavaScript

I have created a working regular expression myself:

str=str.replace(/(<\?[a-z]*(\s[^>]*)?\?(>|$)|<!\[[a-z]*\[|\]\]>|<!DOCTYPE[^>]*?(>|$)|<!--[\s\S]*?(-->|$)|<[a-z?!\/]([a-z0-9_:.])*(\s[^>]*)?(>|$))/gi, ''); 

Angular2 change detection: ngOnChanges not firing for nested object

When you are manipulating the data like:

this.data.profiles[i].icon.url = '';

Then you should use in order to detect changes:

let array = this.data.profiles.map(x => Object.assign({}, x)); // It will detect changes

Since angular ngOnchanges not be able to detect changes in array, objects then we have to assign a new reference. Works everytime!

How do I set a program to launch at startup

I found adding a shortcut to the startup folder to be the easiest way for me. I had to add a reference to "Windows Script Host Object Model" and "Microsoft.CSharp" and then used this code:

IWshRuntimeLibrary.WshShell shell = new IWshRuntimeLibrary.WshShell();
string shortcutAddress = Environment.GetFolderPath(Environment.SpecialFolder.Startup) + @"\MyAppName.lnk";
System.Reflection.Assembly curAssembly = System.Reflection.Assembly.GetExecutingAssembly();

IWshRuntimeLibrary.IWshShortcut shortcut = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(shortcutAddress);
shortcut.Description = "My App Name";
shortcut.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
shortcut.TargetPath = curAssembly.Location;
shortcut.IconLocation = AppDomain.CurrentDomain.BaseDirectory + @"MyIconName.ico";
shortcut.Save();

JavaScript/jQuery - How to check if a string contain specific words

indexOf/includes should not be used for finding whole words:

It does not know the difference between find a word or just a part of a word:

"has a word".indexOf('wor')  // 6
"has a word".includes('wor') // true

Check if a single word (whole word) is in the string

Find a real whole word, not just if the letters of that word are somewhere in the string.

_x000D_
_x000D_
const wordInString = (s, word) => new RegExp('\\b' + word + '\\b', 'i').test(s);

// tests
[
  '',            // true
  ' ',           // true
  'did',         // true
  'id',          // flase
  'yo ',         // flase
  'you',         // true
  'you not'      // true
].forEach(q => console.log(
  wordInString('dID You, or did you NOt, gEt WHy?', q) 
))

console.log(
  wordInString('did you, or did you not, get why?', 'you') // true
)
_x000D_
_x000D_
_x000D_

Check if all words are in the string

_x000D_
_x000D_
var stringHasAll = (s, query) => 
  // convert the query to array of "words" & checks EVERY item is contained in the string
  query.split(' ').every(q => new RegExp('\\b' + q + '\\b', 'i').test(s)); 


// tests
[
  '',            // true
  ' ',           // true
  'aa',          // true
  'aa ',         // true
  ' aa',         // true
  'd b',         // false
  'aaa',         // false
  'a b',         // false
  'a a a a a ',  // false
].forEach(q => console.log(
  stringHasAll('aA bB cC dD', q) 
))
_x000D_
_x000D_
_x000D_

Scala Doubles, and Precision

It's actually very easy to handle using Scala f interpolator - https://docs.scala-lang.org/overviews/core/string-interpolation.html

Suppose we want to round till 2 decimal places:

scala> val sum = 1 + 1/4D + 1/7D + 1/10D + 1/13D
sum: Double = 1.5697802197802198

scala> println(f"$sum%1.2f")
1.57

Finding blocking/locking queries in MS SQL (mssql)

Use the script: sp_blocker_pss08 or SQL Trace/Profiler and the Blocked Process Report event class.

proper way to logout from a session in PHP

<?php
// Initialize the session.
session_start();
// Unset all of the session variables.
unset($_SESSION['username']);
// Finally, destroy the session.    
session_destroy();

// Include URL for Login page to login again.
header("Location: login.php");
exit;
?>

Concatenating bits in VHDL

You are not allowed to use the concatenation operator with the case statement. One possible solution is to use a variable within the process:

process(b0,b1,b2,b3)
   variable bcat : std_logic_vector(0 to 3);
begin
   bcat := b0 & b1 & b2 & b3;
   case bcat is
      when "0000" => x <= 1;
      when others => x <= 2;
   end case;
end process;

Which terminal command to get just IP address and nothing else?

This will give you all IPv4 interfaces, including the loopback 127.0.0.1:

ip -4 addr | grep -oP '(?<=inet\s)\d+(\.\d+){3}'

This will only show eth0:

ip -4 addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'

And this way you can get IPv6 addresses:

ip -6 addr | grep -oP '(?<=inet6\s)[\da-f:]+'

Only eth0 IPv6:

ip -6 addr show eth0 | grep -oP '(?<=inet6\s)[\da-f:]+'

Using Python's list index() method on a list of tuples or objects?

Those list comprehensions are messy after a while.

I like this Pythonic approach:

from operator import itemgetter

def collect(l, index):
   return map(itemgetter(index), l)

# And now you can write this:
collect(tuple_list,0).index("cherry")   # = 1
collect(tuple_list,1).index("3")        # = 2

If you need your code to be all super performant:

# Stops iterating through the list as soon as it finds the value
def getIndexOfTuple(l, index, value):
    for pos,t in enumerate(l):
        if t[index] == value:
            return pos

    # Matches behavior of list.index
    raise ValueError("list.index(x): x not in list")

getIndexOfTuple(tuple_list, 0, "cherry")   # = 1

How to document a method with parameter(s)?

Building upon the type-hints answer (https://stackoverflow.com/a/9195565/2418922), which provides a better structured way to document types of parameters, there exist also a structured manner to document both type and descriptions of parameters:

def copy_net(
    infile: (str, 'The name of the file to send'),
    host: (str, 'The host to send the file to'),
    port: (int, 'The port to connect to')):

    pass

example adopted from: https://pypi.org/project/autocommand/

convert strtotime to date time format in php

Use date() function to get the desired date

<?php
// set default timezone
date_default_timezone_set('UTC');

//define date and time
$strtotime = 1307595105;

// output
echo date('d M Y H:i:s',$strtotime);

// more formats
echo date('c',$strtotime); // ISO 8601 format
echo date('r',$strtotime); // RFC 2822 format
?>

Recommended online tool for strtotime to date conversion:

http://freeonlinetools24.com/

How to install the Six module in Python2.7

I had the same question for macOS.

But the root cause was not installing Six. My macOS shipped Python version 2.7 was being usurped by a Python2 version I inherited by installing a package via brew.

I fixed my issue with: $ brew uninstall python@2

Some context on here: https://bugs.swift.org/browse/SR-1061

How to align center the text in html table row?

Here is an example with CSS and inline style attributes:

_x000D_
_x000D_
td _x000D_
{_x000D_
    height: 50px; _x000D_
    width: 50px;_x000D_
}_x000D_
_x000D_
#cssTable td _x000D_
{_x000D_
    text-align: center; _x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<table border="1">_x000D_
    <tr>_x000D_
        <td style="text-align: center; vertical-align: middle;">Text</td>_x000D_
        <td style="text-align: center; vertical-align: middle;">Text</td>_x000D_
    </tr>_x000D_
</table>_x000D_
_x000D_
<table border="1" id="cssTable">_x000D_
    <tr>_x000D_
        <td>Text</td>_x000D_
        <td>Text</td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/j2h3xo9k/

EDIT: The valign attribute is deprecated in HTML5 and should not be used.

Expansion of variables inside single quotes in a command in Bash

Below is what worked for me -

QUOTE="'"
hive -e "alter table TBL_NAME set location $QUOTE$TBL_HDFS_DIR_PATH$QUOTE"

Evaluating string "3*(4+2)" yield int 18

You could fairly easily run this through the CSharpCodeProvider with suitable fluff wrapping it (a type and a method, basically). Likewise you could go through VB etc - or JavaScript, as another answer has suggested. I don't know of anything else built into the framework at this point.

I'd expect that .NET 4.0 with its support for dynamic languages may well have better capabilities on this front.

How to initialize a static array?

If you are creating an array then there is no difference, however, the following is neater:

String[] suit = {
  "spades", 
  "hearts", 
  "diamonds", 
  "clubs"  
};

But, if you want to pass an array into a method you have to call it like this:

myMethod(new String[] {"spades", "hearts"});

myMethod({"spades", "hearts"}); //won't compile!

HTTPS connection Python

Why haven't you tried httplib.HTTPSConnection? It doesn't do SSL validation but this isn't required to connect over https. Your code works fine with https connection:

>>> import httplib
>>> conn = httplib.HTTPSConnection("mail.google.com")
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
200 OK

multiple ways of calling parent method in php

Unless I am misunderstanding the question, I would almost always use $this->get_species because the subclass (in this case dog) could overwrite that method since it does extend it. If the class dog doesn't redefine the method then both ways are functionally equivalent but if at some point in the future you decide you want the get_species method in dog should print "dog" then you would have to go back through all the code and change it.

When you use $this it is actually part of the object which you created and so will always be the most up-to-date as well (if the property being used has changed somehow in the lifetime of the object) whereas using the parent class is calling the static class method.

JPA Native Query select and cast object

When your native query is based on joins, in that case you can get the result as list of objects and process it.

one simple example.

@Autowired
EntityManager em;

    String nativeQuery = "select name,age from users where id=?";   
    Query query = em.createNativeQuery(nativeQuery);
    query.setParameter(1,id);

    List<Object[]> list = query.getResultList();

    for(Object[] q1 : list){

        String name = q1[0].toString();
        //..
        //do something more on 
     }

ORA-28001: The password has expired

Just go to the machine where your database resides, search windows -> search SqlPlus Type the user name, then type password, it will prompt you to give new password. On providing new password, it will say successfully changed the password.

Reading Excel file using node.js

There are a few different libraries doing parsing of Excel files (.xlsx). I will list two projects I find interesting and worth looking into.

Node-xlsx

Excel parser and builder. It's kind of a wrapper for a popular project JS-XLSX, which is a pure javascript implementation from the Office Open XML spec.

node-xlsx project page

Example for parsing file

var xlsx = require('node-xlsx');

var obj = xlsx.parse(__dirname + '/myFile.xlsx'); // parses a file

var obj = xlsx.parse(fs.readFileSync(__dirname + '/myFile.xlsx')); // parses a buffer

ExcelJS

Read, manipulate and write spreadsheet data and styles to XLSX and JSON. It's an active project. At the time of writing the latest commit was 9 hours ago. I haven't tested this myself, but the api looks extensive with a lot of possibilites.

exceljs project page

Code example:

// read from a file
var workbook = new Excel.Workbook();
workbook.xlsx.readFile(filename)
    .then(function() {
        // use workbook
    });

// pipe from stream
var workbook = new Excel.Workbook();
stream.pipe(workbook.xlsx.createInputStream());

How to correctly catch change/focusOut event on text input in React.js?

If you want to only trigger validation when the input looses focus you can use onBlur

Trivia: React <17 listens to blur event and >=17 listens to focusout event.

C# winforms combobox dynamic autocomplete

I've found Max Lambertini's answer very helpful, but have modified his HandleTextChanged method as such:

    //I like min length set to 3, to not give too many options 
    //after the first character or two the user types
    public Int32 AutoCompleteMinLength {get; set;}

    private void HandleTextChanged() {
        var txt = comboBox.Text;
        if (txt.Length < AutoCompleteMinLength)
            return;

        //The GetMatches method can be whatever you need to filter 
        //table rows or some other data source based on the typed text.
        var matches = GetMatches(comboBox.Text.ToUpper());

        if (matches.Count() > 0) {
            //The inside of this if block has been changed to allow
            //users to continue typing after the auto-complete results
            //are found.
            comboBox.Items.Clear();
            comboBox.Items.AddRange(matches);
            comboBox.DroppedDown = true;
            Cursor.Current = Cursors.Default;
            comboBox.Select(txt.Length, 0);
            return;
        }
        else {
            comboBox.DroppedDown = false;
            comboBox.SelectionStart = txt.Length;
        }
    }

getting only name of the class Class.getName()

or programmaticaly

String s = String.class.getName();
s = s.substring(s.lastIndexOf('.') + 1);

Save PL/pgSQL output from PostgreSQL to a CSV file

If you have longer query and you like to use psql then put your query to a file and use the following command:

psql -d my_db_name -t -A -F";" -f input-file.sql -o output-file.csv

RGB to hex and hex to RGB

In case this helps anyone, my API has functions for those conversions.

<script src="http://api.xlww.net/xQuery/xQuery.js"></script>
<script>
  x.init();
  var rgb=new x.rgb(37,255,83);
  alert(rgb.hex);
  var hex=new x.hex("#ffa500");
  alert("("+hex.rgb[0]+","+hex.rgb[1]+","+hex.rgb[2]+")");
</script>

How to get the directory of the currently running file?

Gustavo Niemeyer's answer is great. But in Windows, runtime proc is mostly in another dir, like this:

"C:\Users\XXX\AppData\Local\Temp"

If you use relative file path, like "/config/api.yaml", this will use your project path where your code exists.

How to quickly form groups (quartiles, deciles, etc) by ordering column(s) in a data frame

There's a handy ntile function in package dplyr. It's flexible in the sense that you can very easily define the number of *tiles or "bins" you want to create.

Load the package (install first if you haven't) and add the quartile column:

library(dplyr)
temp$quartile <- ntile(temp$value, 4)  

Or, if you want to use dplyr syntax:

temp <- temp %>% mutate(quartile = ntile(value, 4))

Result in both cases is:

temp
#   name       value quartile
#1     a -0.56047565        1
#2     b -0.23017749        2
#3     c  1.55870831        4
#4     d  0.07050839        2
#5     e  0.12928774        3
#6     f  1.71506499        4
#7     g  0.46091621        3
#8     h -1.26506123        1
#9     i -0.68685285        1
#10    j -0.44566197        2
#11    k  1.22408180        4
#12    l  0.35981383        3

data:

Note that you don't need to create the "quartile" column in advance and use set.seed to make the randomization reproducible:

set.seed(123)
temp <- data.frame(name=letters[1:12], value=rnorm(12))

Cookie blocked/not saved in IFRAME in Internet Explorer

I was able to make the evil eye go away by simply adding this small header to the site in the IFrame (PHP solution):

header('P3P: CP="NOI ADM DEV COM NAV OUR STP"');

Remember to press ctrl+F5 to reload your site or Explorer may still show the evil eye, despite the fact that it's working fine. This is probably the main reason why I had so many problems getting it to work.

No policy file was neccesary at all.

Edit: I found a nice blog entry that explains the problem with cookies in IFrames. It also has a quick fix in C# code: Frames, ASPX Pages and Rejected Cookies

What's a good way to extend Error in JavaScript?

As some people have said, it's fairly easy with ES6:

class CustomError extends Error { }

So I tried that within my app, (Angular, Typescript) and it just didn't work. After some time I've found that the problem is coming from Typescript :O

See https://github.com/Microsoft/TypeScript/issues/13965

It's very disturbing because if you do:

class CustomError extends Error {}
?

try {
  throw new CustomError()
} catch(e) {
  if (e instanceof CustomError) {
    console.log('Custom error');
  } else {
    console.log('Basic error');
  }
}

In node or directly into your browser it'll display: Custom error

Try to run that with Typescript in your project on on Typescript playground, it'll display Basic error...

The solution is to do the following:

class CustomError extends Error {
  // we have to do the following because of: https://github.com/Microsoft/TypeScript/issues/13965
  // otherwise we cannot use instanceof later to catch a given type
  public __proto__: Error;

  constructor(message?: string) {
    const trueProto = new.target.prototype;
    super(message);

    this.__proto__ = trueProto;
  }
}

Parsing JSON in Spring MVC using Jackson JSON

I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar

import net.sf.json.JSONObject;
...

public void send()
{
    //put attributes
    Map m = New HashMap();
    m.put("send_to","[email protected]");
    m.put("email_subject","this is a test email");
    m.put("email_content","test email content");

    //generate JSON Object
    JSONObject json = JSONObject.fromObject(content);
    String message = json.toString();
    ...
}

public void receive(String jsonMessage)
{
    //parse attributes
    JSONObject json = JSONObject.fromObject(jsonMessage);
    String to = (String) json.get("send_to");
    String title = (String) json.get("email_subject");
    String content = (String) json.get("email_content");
    ...
}

More samples here http://json-lib.sourceforge.net/usage.html

CMake not able to find OpenSSL library

Please install openssl from below link:
https://code.google.com/p/openssl-for-windows/downloads/list
then set the variables below:

OPENSSL_ROOT_DIR=D:/softwares/visualStudio/openssl-0.9.8k_WIN32
OPENSSL_INCLUDE_DIR=D:/softwares/visualStudio/openssl-0.9.8k_WIN32/include
OPENSSL_LIBRARIES=D:/softwares/visualStudio/openssl-0.9.8k_WIN32/lib

Run a command over SSH with JSch

The example provided by Mykhaylo Adamovych is very thorough and exposes most of the major features of JSch. I packaged this code (with attribution, of course) into an open-source library called Remote Session. I added JavaDoc and custom exceptions, and I also provided a facility to specify custom session parameters (RemoteConfig).

One feature that Mykhaylo's code doesn't demonstrate is how to provide an "identity" for remote system interactions. This is critical if you're going to execute commands that require super-user access (i.e. - sudo). Remote Session adds this capability in its SessionHolder.newSession() implementation:

RemoteConfig remoteConfig = RemoteConfig.getConfig();
Path keyPath = remoteConfig.getKeyPath();

if (keyPath == null) {
    throw new RemoteCredentialsUnspecifiedException();
}

String keyPass = remoteConfig.getString(RemoteSettings.SSH_KEY_PASS.key());
if (keyPass != null) {
    Path pubPath = keyPath.resolveSibling(keyPath.getFileName() + ".pub");
    jsch.addIdentity(keyPath.toString(), pubPath.toString(), keyPass.getBytes());
} else {
    jsch.addIdentity(keyPath.toString());
}

Note that this behavior is bypassed if the remote system URL includes credentials.

Another feature that Remote Session demonstrates is how to provide a known-hosts file:

if ( ! remoteConfig.getBoolean(RemoteSettings.IGNORE_KNOWN_HOSTS.key())) {
    Path knownHosts = keyPath.resolveSibling("known_hosts");
    if (knownHosts.toFile().exists()) {
        jsch.setKnownHosts(knownHosts.toString());
    }
}

Remote Session also adds a ChannelStream class that encapsulates input/output operation for the channel attached to this session. This provides the ability to accumulate the output from the remote session until a specified prompt is received:

private boolean appendAndCheckFor(String prompt, StringBuilder input, Logger logger) throws InterruptedException, IOException {
    String recv = readChannel(false);
    if ( ! ((recv == null) || recv.isEmpty())) {
        input.append(recv);
        if (logger != null) {
            logger.debug(recv);
        }
        if (input.toString().contains(prompt)) {
            return false;
        }
    }
    return !channel.isClosed();
}

Nothing too complicated, but this can greatly simplify the implementation of interactive remote operations.

Convert an array into an ArrayList

List<Card> list = new ArrayList<Card>(Arrays.asList(hand));

How do I check if a property exists on a dynamic anonymous type in c#?

This works also for DynamicJsonObject:

  public static bool PropertyExists(dynamic settings, string name)
  {
    if (settings is ExpandoObject)
      return ((IDictionary<string, object>)settings).ContainsKey(name);
    else if (settings is DynamicJsonObject)
      return ((DynamicJsonObject)settings).GetDynamicMemberNames().Contains(name);

    return settings.GetType().GetProperty(name) != null;
  }

Visual Studio Code open tab in new window

You can also hit Win+Shift+[n]. N being the position the app is in the taskbar. Eg if its pinned as the first app hit WIn+Shift+1 and windows will open a new instance. This works for all applications.

I agree tho all of these workarounds shouldn't be necessary. Pretty much every other app can drag tabs out as a window I can't think of anything I used that doesn't and VSCode should be implementing ubiquitous functions we expect to be there.

How to get size in bytes of a CLOB column in Oracle?

It only works till 4000 byte, What if the clob is bigger than 4000 bytes then we use this

declare
v_clob_size clob;

begin

      v_clob_size:= (DBMS_LOB.getlength(v_clob)) / 1024 / 1024;
      DBMS_OUTPUT.put_line('CLOB Size   ' || v_clob_size);   
end;

or

select (DBMS_LOB.getlength(your_column_name))/1024/1024 from your_table

How to implement a confirmation (yes/no) DialogPreference?

Android comes with a built-in YesNoPreference class that does exactly what you want (a confirm dialog with yes and no options). See the official source code here.

Unfortunately, it is in the com.android.internal.preference package, which means it is a part of Android's private APIs and you cannot access it from your application (private API classes are subject to change without notice, hence the reason why Google does not let you access them).

Solution: just re-create the class in your application's package by copy/pasting the official source code from the link I provided. I've tried this, and it works fine (there's no reason why it shouldn't).

You can then add it to your preferences.xml like any other Preference. Example:

<com.example.myapp.YesNoPreference
    android:dialogMessage="Are you sure you want to revert all settings to their default values?"
    android:key="com.example.myapp.pref_reset_settings_key"
    android:summary="Revert all settings to their default values."
    android:title="Reset Settings" />

Which looks like this:

screenshot

"Default Activity Not Found" on Android Studio upgrade

Go to manifest file and then go merge manifest file see error and solve manifest issue

clean project and run

Parse v. TryParse

TryParse and the Exception Tax

Parse throws an exception if the conversion from a string to the specified datatype fails, whereas TryParse explicitly avoids throwing an exception.

SQL Server Script to create a new user

Full admin rights for the whole server, or a specific database? I think the others answered for a database, but for the server:

USE [master];
GO
CREATE LOGIN MyNewAdminUser 
    WITH PASSWORD    = N'abcd',
    CHECK_POLICY     = OFF,
    CHECK_EXPIRATION = OFF;
GO
EXEC sp_addsrvrolemember 
    @loginame = N'MyNewAdminUser', 
    @rolename = N'sysadmin';

You may need to leave off the CHECK_ parameters depending on what version of SQL Server Express you are using (it is almost always useful to include this information in your question).

Can someone give an example of cosine similarity, in a very simple, graphical way?

For simplicity I am reducing the vector a and b:

Let :
    a : [1, 1, 0]
    b : [1, 0, 1]

Then cosine similarity (Theta):

 (Theta) = (1*1 + 1*0 + 0*1)/sqrt((1^2 + 1^2))* sqrt((1^2 + 1^2)) = 1/2 = 0.5

then inverse of cos 0.5 is 60 degrees.

How to attach source or JavaDoc in eclipse for any jar file e.g. JavaFX?

In addition to the answer of @dhroove (would have written a comment if I had 50 rep...)

The link has changed to: http://docs.oracle.com/javafx/2/api/

At least my eclipse wasn't able to use the link from him.

Unable to open debugger port in IntelliJ

I had the same problem and this solution also did the trick for me: Provide the IP 127.0.0.1 in the Intellij Debug configuration instead of the host name "localhost", in case you're using this hostname.

Xcode 10: A valid provisioning profile for this executable was not found

In my case, Device date-time was set to a future date. Changing the date setting to "automatic" fixed the issue.

How to add a new row to an empty numpy array

Here is my solution:

arr = []
arr.append([1,2,3])
arr.append([4,5,6])
np_arr = np.array(arr)

Can grep show only words that match search pattern?

grep command for only matching and perl

grep -o -P 'th.*? ' filename

Using CSS how to change only the 2nd column of a table

on this web http://quirksmode.org/css/css2/columns.html i found that easy way

<table>
<col style="background-color: #6374AB; color: #ffffff" />
<col span="2" style="background-color: #07B133; color: #ffffff;" />
<tr>..

Draggable div without jQuery UI

Here's another updated code:

$(document).ready(function() {
    var $dragging = null;
    $('body').on("mousedown", "div", function(e) {
        $(this).attr('unselectable', 'on').addClass('draggable');
        var el_w = $('.draggable').outerWidth(),
            el_h = $('.draggable').outerHeight();
        $('body').on("mousemove", function(e) {
            if ($dragging) {
                $dragging.offset({
                    top: e.pageY - el_h / 2,
                    left: e.pageX - el_w / 2
                });
            }
        });
        $dragging = $(e.target);
    }).on("mouseup", ".draggable", function(e) {
        $dragging = null;
        $(this).removeAttr('unselectable').removeClass('draggable');
    });
});?

Demo: http://jsfiddle.net/tovic/Jge9z/31/


I've created a simple plugin to this thread.

// Simple JQuery Draggable Plugin
// https://plus.google.com/108949996304093815163/about
// Usage: $(selector).drags();
// Options:
// handle            => your dragging handle.
//                      If not defined, then the whole body of the
//                      selected element will be draggable
// cursor            => define your draggable element cursor type
// draggableClass    => define the draggable class
// activeHandleClass => define the active handle class
//
// Update: 26 February 2013
// 1. Move the `z-index` manipulation from the plugin to CSS declaration
// 2. Fix the laggy effect, because at the first time I made this plugin,
//    I just use the `draggable` class that's added to the element
//    when the element is clicked to select the current draggable element. (Sorry about my bad English!)
// 3. Move the `draggable` and `active-handle` class as a part of the plugin option
// Next update?? NEVER!!! Should create a similar plugin that is not called `simple`!

(function($) {
    $.fn.drags = function(opt) {

        opt = $.extend({
            handle: "",
            cursor: "move",
            draggableClass: "draggable",
            activeHandleClass: "active-handle"
        }, opt);

        var $selected = null;
        var $elements = (opt.handle === "") ? this : this.find(opt.handle);

        $elements.css('cursor', opt.cursor).on("mousedown", function(e) {
            if(opt.handle === "") {
                $selected = $(this);
                $selected.addClass(opt.draggableClass);
            } else {
                $selected = $(this).parent();
                $selected.addClass(opt.draggableClass).find(opt.handle).addClass(opt.activeHandleClass);
            }
            var drg_h = $selected.outerHeight(),
                drg_w = $selected.outerWidth(),
                pos_y = $selected.offset().top + drg_h - e.pageY,
                pos_x = $selected.offset().left + drg_w - e.pageX;
            $(document).on("mousemove", function(e) {
                $selected.offset({
                    top: e.pageY + pos_y - drg_h,
                    left: e.pageX + pos_x - drg_w
                });
            }).on("mouseup", function() {
                $(this).off("mousemove"); // Unbind events from document
                if ($selected !== null) {
                    $selected.removeClass(opt.draggableClass);
                    $selected = null;
                }
            });
            e.preventDefault(); // disable selection
        }).on("mouseup", function() {
            if(opt.handle === "") {
                $selected.removeClass(opt.draggableClass);
            } else {
                $selected.removeClass(opt.draggableClass)
                    .find(opt.handle).removeClass(opt.activeHandleClass);
            }
            $selected = null;
        });

        return this;

    };
})(jQuery);

Demo: http://tovic.github.io/dte-project/jquery-draggable/index.html

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

Attempt to write a readonly database - Django w/ SELinux error

In short, it happens when the application which writes to the sqlite database does not have write permission.

This can be solved in three ways:

  1. Granting ownership of db.sqlite3 file and its parent directory (thereby write access also) to the user using chown (Eg: chown username db.sqlite3 )
  2. Running the webserver (often gunicorn) as root user (run the command sudo -i before you run gunicorn or django runserver)
  3. Allowing read and write access to all users by running command chmod 777 db.sqlite3 (Dangerous option)

Never go for the third option unless you are running the webserver in a local machine or the data in the database is not at all important for you.

Second option is also not recommended. But you can go for it, if you are sure that your application is not vulnerable for code injection attack.

How do I open a Visual Studio project in design view?

My problem, it showed an error called "The class Form1 can be designed, but is not the first class in the file. Visual Studio requires that designers use the first class in the file. Move the class code so that it is the first class in the file and try loading the designer again. ". So I moved the Form class to the first one and it worked. :)

How do you POST to a page using the PHP header() function?

In addition to what Salaryman said, take a look at the classes in PEAR, there are HTTP request classes there that you can use even if you do not have the cURL extension installed in your PHP distribution.

Express-js wildcard routing to cover everything under and including a path

The connect router has now been removed (https://github.com/senchalabs/connect/issues/262), the author stating that you should use a framework on top of connect (like Express) for routing.

Express currently treats app.get("/foo*") as app.get(/\/foo(.*)/), removing the need for two separate routes. This is in contrast to the previous answer (referring to the now removed connect router) which stated that "* in a path is replaced with .+".

Update: Express now uses the "path-to-regexp" module (since Express 4.0.0) which maintains the same behavior in the version currently referenced. It's unclear to me whether the latest version of that module keeps the behavior, but for now this answer stands.

How to handle configuration in Go

I usually use JSON for more complicated data structures. The downside is that you easily end up with a bunch of code to tell the user where the error was, various edge cases and what not.

For base configuration (api keys, port numbers, ...) I've had very good luck with the gcfg package. It is based on the git config format.

From the documentation:

Sample config:

; Comment line
[section]
name = value # Another comment
flag # implicit value for bool is true

Go struct:

type Config struct {
    Section struct {
            Name string
            Flag bool
    }
}

And the code needed to read it:

var cfg Config
err := gcfg.ReadFileInto(&cfg, "myconfig.gcfg")

It also supports slice values, so you can allow specifying a key multiple times and other nice features like that.

Create a HTML table where each TR is a FORM

If you can use javascript and strictly require it on your web, you can put textboxes, checkboxes and whatever on each row of your table and at the end of each row place button (or link of class rowSubmit) "save". Without any FORM tag. Form than will be simulated by JS and Ajax like this:

<script type="text/javascript">
$(document).ready(function(){
  $(".rowSubmit").click(function()
  {
     var form = '<form><table><tr>' + $(this).closest('tr').html() + '</tr></table></form>';
     var serialized = $(form).serialize(); 
     $.get('url2action', serialized, function(data){
       // ... can be empty
     }); 
   });
});        
</script>

What do you think?

PS: If you write in jQuery this:

$("valid HTML string")
$(variableWithValidHtmlString)

It will be turned into jQuery object and you can work with it as you are used to in jQuery.

What IDE to use for Python?

Results

Spreadsheet version

spreadsheet screenshot

Alternatively, in plain text: (also available as a a screenshot)

                         Bracket Matching -.  .- Line Numbering
                          Smart Indent -.  |  |  .- UML Editing / Viewing
         Source Control Integration -.  |  |  |  |  .- Code Folding
                    Error Markup -.  |  |  |  |  |  |  .- Code Templates
  Integrated Python Debugging -.  |  |  |  |  |  |  |  |  .- Unit Testing
    Multi-Language Support -.  |  |  |  |  |  |  |  |  |  |  .- GUI Designer (Qt, Eric, etc)
   Auto Code Completion -.  |  |  |  |  |  |  |  |  |  |  |  |  .- Integrated DB Support
     Commercial/Free -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  .- Refactoring
   Cross Platform -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom              |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |  |  |  |  |*many plugins
Editra            |Y |F |Y |Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |
Emacs             |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
Eric Ide          |Y |F |Y |  |Y |Y |  |Y |  |Y |  |Y |  |Y |  |  |  |
Geany             |Y |F |Y*|Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |*very limited
Gedit             |Y |F |Y¹|Y |  |  |  |Y |Y |Y |  |  |Y²|  |  |  |  |¹with plugin; ²sort of
Idle              |Y |F |Y |  |Y |  |  |Y |Y |  |  |  |  |  |  |  |  |
IntelliJ          |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit             |Y |F |  |Y |  |  |  |  |Y |Y |  |Y |  |  |  |  |  |
KDevelop          |Y |F |Y*|Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |*no type inference
Komodo            |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |Y |  |
NetBeans*         |Y |F |Y |Y |Y |  |Y |Y |Y |Y |Y |Y |Y |Y |  |  |Y |*pre-v7.0
Notepad++         |W |F |Y |Y |  |Y*|Y*|Y*|Y |Y |  |Y |Y*|  |  |  |  |*with plugin
Pfaide            |W |C |Y |Y |  |  |  |Y |Y |Y |  |Y |Y |  |  |  |  |
PIDA              |LW|F |Y |Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |VIM based
PTVS              |W |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |  |  |Y*|  |Y |*WPF bsed
PyCharm           |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse)   |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
PyScripter        |W |F |Y |  |Y |Y |  |Y |Y |Y |  |Y |Y |Y |  |  |  |
PythonWin         |W |F |Y |  |Y |  |  |Y |Y |  |  |Y |  |  |  |  |  |
SciTE             |Y |F¹|  |Y |  |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |¹Mac version is
ScriptDev         |W |C |Y |Y |Y |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |    commercial
Spyder            |Y |F |Y |  |Y |Y |  |Y |Y |Y |  |  |  |  |  |  |  |
Sublime Text      |Y |CF|Y |Y |  |Y |Y |Y |Y |Y |  |Y |Y |Y*|  |  |  |extensible w/Python,
TextMate          |M |F |  |Y |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |    *PythonTestRunner
UliPad            |Y |F |Y |Y |Y |  |  |Y |Y |  |  |  |Y |Y |  |  |  |
Vim               |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |
Visual Studio     |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde           |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |*support for C
Zeus              |W |C |  |  |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   Cross Platform -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
     Commercial/Free -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  '- Refactoring
   Auto Code Completion -'  |  |  |  |  |  |  |  |  |  |  |  |  '- Integrated DB Support
    Multi-Language Support -'  |  |  |  |  |  |  |  |  |  |  '- GUI Designer (Qt, Eric, etc)
  Integrated Python Debugging -'  |  |  |  |  |  |  |  |  '- Unit Testing
                    Error Markup -'  |  |  |  |  |  |  '- Code Templates
         Source Control Integration -'  |  |  |  |  '- Code Folding
                          Smart Indent -'  |  |  '- UML Editing / Viewing
                         Bracket Matching -'  '- Line Numbering

Acronyms used:

 L  - Linux
 W  - Windows
 M  - Mac
 C  - Commercial
 F  - Free
 CF - Commercial with Free limited edition
 ?  - To be confirmed

I don't mention basics like syntax highlighting as I expect these by default.


This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.

PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?

We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Submit edits to the spreadsheet

Getting list of pixel values from PIL

Not PIL, but scipy.misc.imread might still be interesting:

import scipy.misc
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
print(im.shape)

gives

(480, 640, 3)

so it is (height, width, channels). So you can iterate over it by

for y in range(im.shape[0]):
    for x in range(im.shape[1]):
        color = tuple(im[y][x])
        r, g, b = color

Java - sending HTTP parameters via POST method easily

In a GET request, the parameters are sent as part of the URL.

In a POST request, the parameters are sent as a body of the request, after the headers.

To do a POST with HttpURLConnection, you need to write the parameters to the connection after you have opened the connection.

This code should get you started:

String urlParameters  = "param1=a&param2=b&param3=c";
byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
int    postDataLength = postData.length;
String request        = "http://example.com/index.php";
URL    url            = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
   wr.write( postData );
}

How to concatenate int values in java?

StringBuffer sb = new StringBuffer();
sb.append(a).append(b).append(c)...

Keeping the values as an int is preferred thou, as the other answers show you.

C# how to use enum with switch

 public enum Operator
    {
        PLUS, MINUS, MULTIPLY, DIVIDE
    }

    public class Calc
    {
        public void Calculate(int left, int right, Operator op)
        {

            switch (op)
            {
                case Operator.DIVIDE:
                    //Divide
                    break;
                case Operator.MINUS:
                    //Minus
                    break;
                case Operator.MULTIPLY:
                    //...
                    break;
                case Operator.PLUS:
                    //;;
                    break;
                default:
                    throw new InvalidOperationException("Couldn't process operation: " + op);
            }
        }
    }

Using iText to convert HTML to PDF

When I needed HTML to PDF conversion earlier this year, I tried the trial of Winnovative HTML to PDF converter (I think ExpertPDF is the same product, too). It worked great so we bought a license at that company. I don't go into it too in depth after that.

Gridview with two columns and auto resized images

another simple approach with modern built-in stuff like PercentRelativeLayout is now available for new users who hit this problem. thanks to android team for release this item.

<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
app:layout_widthPercent="50%">

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="#55000000"
        android:paddingBottom="15dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:textColor="@android:color/white" />

</FrameLayout>

and for better performance you can use some stuff like picasso image loader which help you to fill whole width of every image parents. for example in your adapter you should use this:

int width= context.getResources().getDisplayMetrics().widthPixels;
    com.squareup.picasso.Picasso
            .with(context)
            .load("some url")
            .centerCrop().resize(width/2,width/2)
            .error(R.drawable.placeholder)
            .placeholder(R.drawable.placeholder)
            .into(item.drawableId);

now you dont need CustomImageView Class anymore.

P.S i recommend to use ImageView in place of Type Int in class Item.

hope this help..

Running bash script from within python

If sleep.sh has the shebang #!/bin/sh and it has appropriate file permissions -- run chmod u+rx sleep.sh to make sure and it is in $PATH then your code should work as is:

import subprocess

rc = subprocess.call("sleep.sh")

If the script is not in the PATH then specify the full path to it e.g., if it is in the current working directory:

from subprocess import call

rc = call("./sleep.sh")

If the script has no shebang then you need to specify shell=True:

rc = call("./sleep.sh", shell=True)

If the script has no executable permissions and you can't change it e.g., by running os.chmod('sleep.sh', 0o755) then you could read the script as a text file and pass the string to subprocess module instead:

with open('sleep.sh', 'rb') as file:
    script = file.read()
rc = call(script, shell=True)

Difference between string and text in rails?

If you are using oracle... STRING will be created as VARCHAR(255) column and TEXT, as a CLOB.

NATIVE_DATABASE_TYPES = {
    primary_key: "NUMBER(38) NOT NULL PRIMARY KEY",
    string: { name: "VARCHAR2", limit: 255 },
    text: { name: "CLOB" },
    ntext: { name: "NCLOB" },
    integer: { name: "NUMBER", limit: 38 },
    float: { name: "BINARY_FLOAT" },
    decimal: { name: "DECIMAL" },
    datetime: { name: "TIMESTAMP" },
    timestamp: { name: "TIMESTAMP" },
    timestamptz: { name: "TIMESTAMP WITH TIME ZONE" },
    timestampltz: { name: "TIMESTAMP WITH LOCAL TIME ZONE" },
    time: { name: "TIMESTAMP" },
    date: { name: "DATE" },
    binary: { name: "BLOB" },
    boolean: { name: "NUMBER", limit: 1 },
    raw: { name: "RAW", limit: 2000 },
    bigint: { name: "NUMBER", limit: 19 }
}

https://github.com/rsim/oracle-enhanced/blob/master/lib/active_record/connection_adapters/oracle_enhanced_adapter.rb

Ambiguous overload call to abs(double)

Its boils down to this: math.h is from C and was created over 10 years ago. In math.h, due to its primitive nature, the abs() function is "essentially" just for integer types and if you wanted to get the absolute value of a double, you had to use fabs(). When C++ was created it took math.h and made it cmath. cmath is essentially math.h but improved for C++. It improved things like having to distinguish between fabs() and abs, and just made abs() for both doubles and integer types. In summary either: Use math.h and use abs() for integers, fabs() for doubles or use cmath and just have abs for everything (easier and recommended)

Hope this helps anyone who is having the same problem!

Removing double quotes from a string in Java

String withoutQuotes_line1 = line1.replace("\"", "");

have a look here

Dictionary with list of strings as value

A simpler way of doing it is:

var dictionary = list.GroupBy(it => it.Key).ToDictionary(dict => dict.Key, dict => dict.Select(item => item.value).ToList());

How to extract the substring between two markers?

Typescript. Gets string in between two other strings.

Searches shortest string between prefixes and postfixes

prefixes - string / array of strings / null (means search from the start).

postfixes - string / array of strings / null (means search until the end).

public getStringInBetween(str: string, prefixes: string | string[] | null,
                          postfixes: string | string[] | null): string {

    if (typeof prefixes === 'string') {
        prefixes = [prefixes];
    }

    if (typeof postfixes === 'string') {
        postfixes = [postfixes];
    }

    if (!str || str.length < 1) {
        throw new Error(str + ' should contain ' + prefixes);
    }

    let start = prefixes === null ? { pos: 0, sub: '' } : this.indexOf(str, prefixes);
    const end = postfixes === null ? { pos: str.length, sub: '' } : this.indexOf(str, postfixes, start.pos + start.sub.length);

    let value = str.substring(start.pos + start.sub.length, end.pos);
    if (!value || value.length < 1) {
        throw new Error(str + ' should contain string in between ' + prefixes + ' and ' + postfixes);
    }

    while (true) {
        try {
            start = this.indexOf(value, prefixes);
        } catch (e) {
            break;
        }
        value = value.substring(start.pos + start.sub.length);
        if (!value || value.length < 1) {
            throw new Error(str + ' should contain string in between ' + prefixes + ' and ' + postfixes);
        }
    }

    return value;
}

Operator overloading on class templates

You must specify that the friend is a template function:

MyClass<T>& operator+=<>(const MyClass<T>& classObj);

See this C++ FAQ Lite answer for details.

xml.LoadData - Data at the root level is invalid. Line 1, position 1

The hidden character is probably BOM. The explanation to the problem and the solution can be found here, credits to James Schubert, based on an answer by James Brankin found here.

Though the previous answer does remove the hidden character, it also removes the whole first line. The more precise version would be:

string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
if (xml.StartsWith(_byteOrderMarkUtf8))
{
    xml = xml.Remove(0, _byteOrderMarkUtf8.Length);
}

I encountered this problem when fetching an XSLT file from Azure blob and loading it into an XslCompiledTransform object. On my machine the file looked just fine, but after uploading it as a blob and fetching it back, the BOM character was added.

bootstrap 3 - how do I place the brand in the center of the navbar?

css:

.navbar-header {
    float: left;
    padding: 15px;
    text-align: center;
    width: 100%;
}
.navbar-brand {float:none;}

html:

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">
    <a class="navbar-brand" href="#">Brand</a>
  </div>
</nav>

CSS filter: make color image with transparency white

To my knowledge, there is sadly no CSS filter to colorise an element (perhaps with the use of some SVG filter magic, but I'm somewhat unfamiliar with that) and even if that wasn't the case, filters are basically only supported by webkit browsers.

With that said, you could still work around this and use a canvas to modify your image. Basically, you can draw an image element onto a canvas and then loop through the pixels, modifying the respective RGBA values to the colour you want.

However, canvases do come with some restrictions. Most importantly, you have to make sure that the image src comes from the same domain as the page. Otherwise the browser won't allow you to read or modify the pixel data of the canvas.

Here's a JSFiddle changing the colour of the JSFiddle logo.

_x000D_
_x000D_
//Base64 source, but any local source will work_x000D_
var src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAgCAYAAACGhPFEAAAABGdBTUEAALGPC/xhBQAABzhJREFUWAnNWAtwXFUZ/v9zs4GUJJu+k7tb5DFAGWO1aal1sJUiY3FQQaWidqgPLAMqYzd9CB073VodhCa7KziiFgWhzvAYQCiCD5yK4gOTDnZK2ymdZoruppu0afbu0pBs7p7f7yy96W662aw2QO/Mzj2P//Gd/5z/+89dprfzubnTN332Re+xiKawllxWucm+9O4eCi9xT8ctn45yKd3AXX1BPsu3XIiuY+K5kDmrUA7jORb5m2baLm7uscNrJr9eOF9Je8JAz9ySnFHlq9nEpG6CYx+RdJDQDtKymxT1iWZLFDUy0/kkfDUxzYVzV0hvHZLs946Gph+uBLCRmRDQdjTVwmw9DZCNMPi4KzqWbPX/sxwIu71vlrKq10HnZizwTSFZngj5f1NOx5s7bdB2LHWDEusBOD487LrX9qyd8qpnvJL3zGjqAh+pR4W4RVhu715Vv2U8PTWeQLn5YHvms4qsR4TpH/ImLfhfARvbPaGGrrjTtwjH5hFFfHcgkv5SOZ9mbvxIgwGaZl+8ULGcJ8zOsJa9R1r9B2d8v2eGb1KNieqBhLNz8ekyAoV3VAX985+FvSXEenF8lf9lA7DUUxa0HUl/RTG1EfOUQmUwwCtggDewiHmc1R+Ir/MfKJz/f9tTwn31Nf7qVxlHLR6qXwg7cHXqU/p4hPdUB6Lp55TiXwDYTsrpG12dbdY5t0WLrCSRSVjIItG0dqIAG2jHwlPTmvQdsL3Ajjg3nAq3zIgdS98ZiGV0MJZeWVJs2WNWIJK5hcLh0osuqVTxIAdi6X3w/0LFGoa+AtFMzo5kflix0gQLBiLOZmAYro84RcfSc3NKpFAcliM9eYDdjZ7QO/1mRc+CTapqFX+4lO9TQEPoUpz//anQ5FQphXdizB1QXXk/moOl/JUC7aLMDpQSHj02PdxbG9xybM60u47UjZ4bq290Zm451ky3HSi6kxTKJ9fXHQVvZJm1XTjutYsozw53T1L+2ufBGPMTe/c30M/mD3uChW+c+6tQttthuBnbqMBLKGbydI54/eFQ3b5CWa/dGMl8xFJ0D/rvg1Pjdxil+2XK5b6ZWD15lyfnvYOxTBYs9TrY5NbuUENRUo5EGtGyVUNtBwBfDjA/IDtTkiNRsdYD8O+NcVN2KUfXo3UnukvA6Z3I+mWeY++NpNoAwDvAv1Uiss7oiNBmYD+XraoO0NvnPVnvrbUsA4CcYusPgajzY2/cvN+KtOFl/6w/IWrvdTV/Ktla92KhkNcOxpwPCqm/IgLbEvteW1m4E2/d8iY9AZOXQ/7WxKq6nxq9YNT5OLF6DmAfTHT13EL3XjTk2csXk4bqX2OXWiQ73Jz49tS4N5d/oxoHLr14EzPfAf1IIlS/2oznIx1omLURhL5Qa1oxFuC8EeHb8U6I88bXCwGbuZ61jb2Jgz1XYUHb0b0vEHNWmHE9lNsjWrcmnMhNhYDNnCkmNJSFHFdzte82M1b04HgC6HrYbAPw1pFdNOc4GE334wz9qkihRAdK/0HBub/E1MkhJBiq6V8gq7Htm05OjN2C/z/jCP1xbAlCwcnsAsbdkGHF/trPIcoNrtbjFRNmoama6EgZ42SimRG5FjLHWakNwWjmirLyZpLpKH7TysghZ00OUHNTxFmK2yDNQSKlx7u0Q0GQeLtQdy4rY5zMzqVb/ccoJ/OQMEmoPWW3988to4NY8DxYf6WMDCW6ktuRvFqxmqewgguhdLCcwsic0DMA8lE7kvrYyFhBw446X2B/nRNo739/YnX9azKUXYCg9CtlvdAUyywuEB1p4gh9AzbPZc0mF8Z+sINgn0MIwiVgKcAG6rGlT86AMdqw2n8ppR63o+mveQXCFAxzX2BWD0P6pcT+g3uNlmEDV3JX4iOh1xICdWU2gGXOMXN5HfRhK4IoPxlfXQfmKf+Ajh1I+MEeHMcKzqvoxoZsHsoOXgP+fEkxbw1e2JhB0h2q9tc4OL/fAVdsdd3jnyhklmRo8qGBQXchIvMMKPW7Pt85/SM66CNmDw1mh75cHu6JWZFZxNLNSJTPIM5PuJquKEt3o6zmqyJZH4LTC7CIfTonO5Jr/B2jxIq6jW3OZVYVX4edDSD6e1BAXqwgl/I2miKp+ZayOkT0CjaJww21/2bhznio7uoiL2dQB8HdhoV++ri4AdUdtgfw789mRHspzulXzyCcI1BMVQXgL5LodnP7zFfE+N9/9yOUyedxTn/SFHWWj0ifAY1ANHUleOJRlPqdCUmbO85J1jjxUfkUkgVCsg1/uGw0n/fvFm67LT2NLTLfi98Cke8dpMGl3r9QxVRnPuPrWzaIUmsAtgas0okd6ETh7AYt5d7+BeCbhfKVcQ6CtwgJjjoiP3fdgVbcbY57/otBnxidfndvo6/67BtxUf4kztJsbMg0CJaU9QxN2FskhePQBWr7La6wvzRFarTtyoBgB4hm5M//aAMT2+/Vlfzp81/vywLMWSBN1QAAAABJRU5ErkJggg==";_x000D_
var canvas = document.getElementById("theCanvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
var img = new Image;_x000D_
_x000D_
//wait for the image to load_x000D_
img.onload = function() {_x000D_
    //Draw the original image so that you can fetch the colour data_x000D_
    ctx.drawImage(img,0,0);_x000D_
    var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);_x000D_
    _x000D_
    /*_x000D_
    imgData.data is a one-dimensional array which contains _x000D_
    the respective RGBA values for every pixel _x000D_
    in the selected region of the context _x000D_
    (note i+=4 in the loop)_x000D_
    */_x000D_
    _x000D_
    for (var i = 0; i < imgData.data.length; i+=4) {_x000D_
   imgData.data[i] = 255; //Red, 0-255_x000D_
   imgData.data[i+1] = 255; //Green, 0-255_x000D_
   imgData.data[i+2] = 255; //Blue, 0-255_x000D_
   /* _x000D_
   imgData.data[i+3] contains the alpha value_x000D_
   which we are going to ignore and leave_x000D_
   alone with its original value_x000D_
   */_x000D_
    }_x000D_
    ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the original image_x000D_
    ctx.putImageData(imgData, 0, 0); //paint the new colorised image_x000D_
}_x000D_
_x000D_
//Load the image!_x000D_
img.src = src;
_x000D_
body {_x000D_
    background: green;_x000D_
}
_x000D_
<canvas id="theCanvas"></canvas>
_x000D_
_x000D_
_x000D_

How to avoid Sql Query Timeout

While I would be tempted to blame my issues - I'm getting the same error with my query, which is much, much bigger and involves a lot of loops - on the network, I think this is not the case.

Unfortunately it's not that simple. Query runs for 3+ hours before getting that error and apparently it crashes at the same time if it's just a query in SSMS and a job on SQL Server (did not look into details of that yet, so not sure if it's the same error; definitely same spot, though).

So just in case someone comes here with similar problem, this thread: https://www.sqlservercentral.com/Forums/569962/The-semaphore-timeout-period-has-expired

suggest that it may equally well be a hardware issue or actual timeout.

My loops aren't even (they depend on sales level in given month) in terms of time required for each, so good month takes about 20 mins to calculate (query looks at 4 years).

That way it's entirely possible I need to optimise my query. I would even say it's likely, as some changes I did included new tables, which are heaps... So another round of indexing my data before tearing into VM config and hardware tests.

Being aware that this is old question: I'm on SQL Server 2012 SE, SSMS is 2018 Beta and VM the SQL Server runs on has exclusive use of 132GB of RAM (30% total), 8 cores, and 2TB of SSD SAN.

python: how to check if a line is an empty line

I use the following code to test the empty line with or without white spaces.

if len(line.strip()) == 0 :
    # do something with empty line

Select current element in jQuery

Fortunately, jQuery selectors allow you much more freedom:

$("div a").click( function(event)
{
   var clicked = $(this); // jQuery wrapper for clicked element
   // ... click-specific code goes here ...
});

...will attach the specified callback to each <a> contained in a <div>.

npm install private github repositories by dependency in package.json

Here is a more detailed version of how to use the Github token without publishing in the package.json file.

  1. Create personal github access token
  2. Setup url rewrite in ~/.gitconfig
git config --global url."https://<TOKEN HERE>:[email protected]/".insteadOf https://[email protected]/
  1. Install private repository. Verbose log level for debugging access errors.
npm install --loglevel verbose --save git+https://[email protected]/<USERNAME HERE>/<REPOSITORY HERE>.git#v0.1.27

In case access to Github fails, try running the git ls-remote ... command that the npm install will print

How to enable CORS in flask

Here is what worked for me when I deployed to Heroku.

http://flask-cors.readthedocs.org/en/latest/
Install flask-cors by running - pip install -U flask-cors

from flask import Flask
from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

@app.route("/")
@cross_origin()
def helloWorld():
  return "Hello, cross-origin-world!"

How return error message in spring mvc @Controller

Evaluating the error response from another service invocated...

This was my solution for evaluating the error:

try {
        return authenticationFeign.signIn(userDto, dataRequest);
    }catch(FeignException ex){

        //ex.status();

        if(ex.status() == HttpStatus.UNAUTHORIZED.value()){
            System.out.println("is a error 401");
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
        return new ResponseEntity<>(HttpStatus.OK);

    }

Best way to convert strings to symbols in hash

ruby-1.9.2-p180 :001 > h = {'aaa' => 1, 'bbb' => 2}
 => {"aaa"=>1, "bbb"=>2} 
ruby-1.9.2-p180 :002 > Hash[h.map{|a| [a.first.to_sym, a.last]}]
 => {:aaa=>1, :bbb=>2}

Runtime vs. Compile time

IMHO you need to read many links , resources to make an idea about the difference between Runtime vs Compile time because it is a very complex subject . I have list below some of this pictures/links that I am recommend .

Apart from what it is said above I want to add that sometimes a picture worth 1000 words :

  1. the order of this two: first is compile time and then you run A compiled program can be opened and run by a user. When an application is running, it is called runtime : compile time and then runtime1 compile time and then runtime1 ;

CLR_diag compile time and then runtime2  CLR_diag compile time and then runtime2

 from Wiki  

https://en.wikipedia.org/wiki/Run_time https://en.wikipedia.org/wiki/Run_time_(program_lifecycle_phase)

Run time, run-time, or runtime may refer to:

Computing

Run time (program lifecycle phase), the period during which a computer program is executing

Runtime library, a program library designed to implement functions built into a programming language

Runtime system, software designed to support the execution of computer programs

Software execution, the process of performing instructions one by one during the run time phase

enter image description here enter image description here

enter image description here enter image description here enter image description here enter image description here enter image description here List of compilers enter image description here enter image description here https://en.wikipedia.org/wiki/List_of_compilers

  • search on google and compare runtime errors vs compile errors:

runtime errors

compile errors ;

  1. In my opinion a very important thing to know : 3.1 the difference between build vs compile and the Build Lifecycle https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html

3.2 the difference between this 3 things : compile vs build vs runtime

https://www.quora.com/What-is-the-difference-between-build-run-and-compile Fernando Padoan, A developer that's just a bit curious for language design Answered Feb 23 I’m going backwards in relation to other answers:

running is getting some binary executable (or a script, for interpreted languages) to be, well… executed as a new process on the computer; compiling is the process of parsing a program written in some high level language (higher if compared to machine code), checking it’s syntax, semantics, linking libraries, maybe doing some optimization, then creating a binary executable program as an output. This executable may be in the form of machine code, or some kind of byte code — that is, instructions targeting some kind of virtual machine; building usually involves checking and providing dependencies, inspecting code, compiling the code into binary, running automated tests and packaging the resulting binary[ies] and other assets (images, configuration files, libraries, etc.) into some specific format of deployable file. Note that most processes are optional and some depend on the targeted platform you are building for. As an example, packaging a Java application for Tomcat will output a .war file. Building a Win32 executable out of C++ code could just output the .exe program, or could also package it inside a .msi installer.

CSS "color" vs. "font-color"

I know this is an old post but as MisterZimbu stated, the color property is defining the values of other properties, as the border-color and, with CSS3, of currentColor.

currentColor is very handy if you want to use the font color for other elements (as the background or custom checkboxes and radios of inner elements for example).

Example:

_x000D_
_x000D_
.element {_x000D_
  color: green;_x000D_
  background: red;_x000D_
  display: block;_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
.innerElement1 {_x000D_
  border: solid 10px;_x000D_
  display: inline-block;_x000D_
  width: 60px;_x000D_
  height: 100px;_x000D_
  margin: 10px;_x000D_
}_x000D_
_x000D_
.innerElement2 {_x000D_
  background: currentColor;_x000D_
  display: inline-block;_x000D_
  width: 60px;_x000D_
  height: 100px;_x000D_
  margin: 10px;_x000D_
}
_x000D_
<div class="element">_x000D_
  <div class="innerElement1"></div>_x000D_
  <div class="innerElement2"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to add Active Directory user group as login in SQL Server

Here is my observation. I created a login (readonly) for a group windows(AD) user account but, its acting defiantly in different SQL servers. In the SQl servers that users can not see the databases I added view definition checked and also gave database execute permeation to the master database for avoiding error 229. I do not have this issue if I create a login for a user.

Android Studio: Unable to start the daemon process

Error:Unable to start the daemon process.

This problem might be caused by incorrect configuration of the daemon. For example, an unrecognized JVM option is used.

Please refer to the user guide chapter on the daemon at https://docs.gradle.org/3.3/userguide/gradle_daemon.html

Adding a JAR to an Eclipse Java library

In Eclipse Ganymede (3.4.0):

  1. Select the library and click "Edit" (left side of the window)
  2. Click "User Libraries"
  3. Select the library again and click "Add JARs"

How to trigger event in JavaScript?

Just to suggest an alternative that does not involve the need to manually invoke a listener event:

Whatever your event listener does, move it into a function and call that function from the event listener.

Then, you can also call that function anywhere else that you need to accomplish the same thing that the event does when it fires.

I find this less "code intensive" and easier to read.

Escape double quotes in parameter

As none of the answers above are straight forward:

Backslash escape \ is what you need:

myscript \"test\"

WPF TabItem Header Styling

While searching for a way to round tabs, I found Carlo's answer and it did help but I needed a bit more. Here is what I put together, based on his work. This was done with MS Visual Studio 2015.

The Code:

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MealNinja"
        mc:Ignorable="d"
        Title="Rounded Tabs Example" Height="550" Width="700" WindowStartupLocation="CenterScreen" FontFamily="DokChampa" FontSize="13.333" ResizeMode="CanMinimize" BorderThickness="0">
    <Window.Effect>
        <DropShadowEffect Opacity="0.5"/>
    </Window.Effect>
    <Grid Background="#FF423C3C">
        <TabControl x:Name="tabControl" TabStripPlacement="Left" Margin="6,10,10,10" BorderThickness="3">
            <TabControl.Resources>
                <Style TargetType="{x:Type TabItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type TabItem}">
                                <Grid>
                                    <Border Name="Border" Background="#FF6E6C67" Margin="2,2,-8,0" BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="10">
                                        <ContentPresenter x:Name="ContentSite" ContentSource="Header" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="2,2,12,2" RecognizesAccessKey="True"/>
                                    </Border>
                                    <Rectangle Height="100" Width="10" Margin="0,0,-10,0" Stroke="Black" VerticalAlignment="Bottom" HorizontalAlignment="Right" StrokeThickness="0" Fill="#FFD4D0C8"/>
                                </Grid>
                                <ControlTemplate.Triggers>
                                    <Trigger Property="IsSelected" Value="True">
                                        <Setter Property="FontWeight" Value="Bold" />
                                        <Setter TargetName="ContentSite" Property="Width" Value="30" />
                                        <Setter TargetName="Border" Property="Background" Value="#FFD4D0C8" />
                                    </Trigger>
                                    <Trigger Property="IsEnabled" Value="False">
                                        <Setter TargetName="Border" Property="Background" Value="#FF6E6C67" />
                                    </Trigger>
                                    <Trigger Property="IsMouseOver" Value="true">
                                        <Setter Property="FontWeight" Value="Bold" />
                                    </Trigger>
                                </ControlTemplate.Triggers>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="HeaderTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <ContentPresenter Content="{TemplateBinding Content}">
                                    <ContentPresenter.LayoutTransform>
                                        <RotateTransform Angle="270" />
                                    </ContentPresenter.LayoutTransform>
                                </ContentPresenter>
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="Background" Value="#FF6E6C67" />
                    <Setter Property="Height" Value="90" />
                    <Setter Property="Margin" Value="0" />
                    <Setter Property="Padding" Value="0" />
                    <Setter Property="FontFamily" Value="DokChampa" />
                    <Setter Property="FontSize" Value="16" />
                    <Setter Property="VerticalAlignment" Value="Top" />
                    <Setter Property="HorizontalAlignment" Value="Right" />
                    <Setter Property="UseLayoutRounding" Value="False" />
                </Style>
                <Style x:Key="tabGrids">
                    <Setter Property="Grid.Background" Value="#FFE5E5E5" />
                    <Setter Property="Grid.Margin" Value="6,10,10,10" />
                </Style>
            </TabControl.Resources>
            <TabItem Header="Planner">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section 2">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section III">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Section 04">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
            <TabItem Header="Tools">
                <Grid Style="{StaticResource tabGrids}"/>
            </TabItem>
        </TabControl>
    </Grid>
</Window>

Screenshot:

enter image description here

C++ String Concatenation operator<<

nametext = "Your name is" + name;

I think this should do

Docker compose, running containers in net:host

Maybe I am answering very late. But I was also having a problem configuring host network in docker compose. Then I read the documentation thoroughly and made the changes and it worked. Please note this configuration is for docker-compose version "3.7". Here einwohner_net and elk_net_net are my user-defined networks required for my application. I am using host net to get some system metrics.

Link To Documentation https://docs.docker.com/compose/compose-file/#host-or-none

version: '3.7'
services:
  app:
    image: ramansharma/einwohnertomcat:v0.0.1
    deploy:
      replicas: 1
      ports:
       - '8080:8080'
    volumes:
     - type: bind
       source: /proc
       target: /hostfs/proc
       read_only: true
     - type: bind
       source: /sys/fs/cgroup
       target: /hostfs/sys/fs/cgroup
       read_only: true
     - type: bind
       source: /
       target: /hostfs
       read_only: true
    networks:
     hostnet: {}
    networks:
     - einwohner_net
     - elk_elk_net
networks:
 einwohner_net:
 elk_elk_net:
   external: true
 hostnet:
   external: true
   name: host

PyCharm error: 'No Module' when trying to import own module (python script)

PyCharm Community/Professional 2018.2.1

I was having this problem just now and I was able to solve it in sort of a similar way that @Beatriz Fonseca and @Julie pointed out.

If you go to File -> Settings -> Project: YourProjectName -> Project Structure, you'll have a directory layout of the project you're currently working in. You'll have to go through your directories and label them as being either the Source directory for all your Source files, or as a Resource folder for files that are strictly for importing.

You'll also want to make sure that you place __init__.py files within your resource directories, or really anywhere that you want to import from, and it'll work perfectly fine.

I hope this answer helps someone, and hopefully JetBrains will fix this annoying bug.

Android textview usage as label and value

You should implement a Custom List View, such that you define a Layout once and draw it for every row in the list view.

Jenkins - Configure Jenkins to poll changes in SCM

I think your cron is not correct. According to what you described, you may need to change cron schedule to

*/5 * * * *

What you put in your schedule now mean it will poll the SCM at 5 past of every hour.

Place a button right aligned

If the button is the only element on the block:

_x000D_
_x000D_
.border {_x000D_
  border: 2px blue dashed;_x000D_
}_x000D_
_x000D_
.mr-0 {_x000D_
  margin-right: 0;_x000D_
}_x000D_
.ml-auto {_x000D_
  margin-left:auto;_x000D_
}_x000D_
.d-block {_x000D_
  display:block;_x000D_
}
_x000D_
<p class="border">_x000D_
  <input type="button" class="d-block mr-0 ml-auto" value="The Button">_x000D_
</p>
_x000D_
_x000D_
_x000D_

If there are other elements on the block:

_x000D_
_x000D_
.border {_x000D_
  border: 2px indigo dashed;_x000D_
}_x000D_
_x000D_
.d-table {_x000D_
  display:table;_x000D_
}_x000D_
_x000D_
.d-table-cell {_x000D_
  display:table-cell;_x000D_
}_x000D_
_x000D_
.w-100 {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.tar {_x000D_
  text-align: right;_x000D_
}
_x000D_
<div class="border d-table w-100">_x000D_
  <p class="d-table-cell">The paragraph.....lorem ipsum...etc.</p>_x000D_
  <div class="d-table-cell tar">_x000D_
    <button >The Button</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

With flex-box:

_x000D_
_x000D_
.flex-box {_x000D_
  display:flex;_x000D_
  justify-content:space-between;_x000D_
  outline: 2px dashed blue;_x000D_
}_x000D_
_x000D_
.flex-box-2 {_x000D_
  display:flex;_x000D_
  justify-content: flex-end;_x000D_
  outline: 2px deeppink dashed;_x000D_
}
_x000D_
<h1>Button with Text</h1>_x000D_
<div class="flex-box">_x000D_
<p>Once upon a time in a ...</p>_x000D_
<button>Read More...</button>_x000D_
</div>_x000D_
_x000D_
<h1>Only Button</h1>_x000D_
<div class="flex-box-2">_x000D_
  <button>The Button</button>_x000D_
</div>_x000D_
_x000D_
<h1>Multiple Buttons</h1>_x000D_
<div class="flex-box-2">_x000D_
  <button>Button 1</button>_x000D_
  <button>Button 2</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Good Luck...

How to get and set the current web page scroll position?

There are some inconsistencies in how browsers expose the current window scrolling coordinates. Google Chrome on Mac and iOS seems to always return 0 when using document.documentElement.scrollTop or jQuery's $(window).scrollTop().

However, it works consistently with:

// horizontal scrolling amount
window.pageXOffset

// vertical scrolling amount
window.pageYOffset

textarea character limit

I think that doing this might be easier than most people think!

Try this:

var yourTextArea = document.getElementById("usertext").value;
// In case you want to limit the number of characters in no less than, say, 10
// or no more than 400.        
    if (yourTextArea.length < 10 || yourTextArea.length > 400) {
        alert("The field must have no less than 10 and no more than 400 characters.");
        return false;
    }

Please let me know it this was useful. And if so, vote up! Thx!

Daniel

send Content-Type: application/json post with node.js

For some reason only this worked for me today. All other variants ended up in bad json error from API.

Besides, yet another variant for creating required POST request with JSON payload.

_x000D_
_x000D_
request.post({_x000D_
    uri: 'https://www.googleapis.com/urlshortener/v1/url',_x000D_
    headers: {'Content-Type': 'application/json'},_x000D_
    body: JSON.stringify({"longUrl": "http://www.google.com/"})_x000D_
});
_x000D_
_x000D_
_x000D_

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

I have a similar issue with a share Host. I was having 500 error. I just fixed by checking the Laravel version and PHP version. The error was because Laravel 5.6 doesn't run on PHP 7.0.x Once I know this I just reconfigure the project to Laravel 5.5 that is compatible with PHP 7.0.x now everything is right. Another reason I have issues sometimes is the FTP I get corrupted Files and have to upload the project more than once. Hope this help in the future I don't found so many information in this topic.

Float to String format specifier

Use ToString() with this format:

12345.678901.ToString("0.0000"); // outputs 12345.6789
12345.0.ToString("0.0000"); // outputs 12345.0000

Put as much zero as necessary at the end of the format.

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

@AlexK wrote a great answer. I just want to add my two cents. The code below is entirely based on @AlexK's answer, the difference is that you can specify the user and a time since the last batch was executed (note that the code uses sys.dm_exec_sessions instead of master..sysprocess):

DECLARE @kill varchar(8000);
set @kill =''
select @kill = @kill + 'kill ' +  CONVERT(varchar(5), session_id) + ';' from sys.dm_exec_sessions 
where login_name = 'usrDBTest'
and datediff(hh,login_time,getdate()) > 1
--and session_id in (311,266)    
exec(@kill)

In this example only the process of the user usrDBTest which the last batch was executed more than 1 hour ago will be killed.

How to convert a hex string to hex number

Try this:

hex_str = "0xAD4"
hex_int = int(hex_str, 16)
new_int = hex_int + 0x200
print hex(new_int)

If you don't like the 0x in the beginning, replace the last line with

print hex(new_int)[2:]

How to Completely Uninstall Xcode and Clear All Settings

This answer should be more of a comment against Dawn Song's comment earlier, but since I don't have enough reputation, I'm going to write it as an answer.

According to the forum page

https://forums.developer.apple.com/thread/11313

"In general, you should never just delete the CoreSimulator/Devices directory yourself. If you really absolutely must, you need to make sure that the service is not runnign while you do that. eg:"

# Quit Xcode.app, Simulator.app, etc
sudo killall -9 com.apple.CoreSimulator.CoreSimulatorService
rm -rf ~/Library/*/CoreSimulator

I definitely ran into this issue after deleting and reinstalling Xcode.

You might encounter a problem trying to connect the build to a simulator device. The thread also answers what to do in that case,

gem install snapshot
fastlane snapshot reset_simulators

How can I copy a file on Unix using C?

Copying files byte-by-byte does work, but is slow and wasteful on modern UNIXes. Modern UNIXes have “copy-on-write” support built-in to the filesystem: a system call makes a new directory entry pointing at the existing bytes on disk, and no file content bytes on disk are touched until one of the copies is modified, at which point only the changed blocks are written to disk. This allows near-instant file copies that use no additional file blocks, regardless of file size. For example, here are some details about how this works in xfs.

On linux, use the FICLONE ioctl as coreutils cp now does by default.

 #ifdef FICLONE
   return ioctl (dest_fd, FICLONE, src_fd);
 #else
   errno = ENOTSUP;
   return -1;
 #endif

On macOS, use clonefile(2) for instant copies on APFS volumes. This is what Apple’s cp -c uses. The docs are not completely clear but it is likely that copyfile(3) with COPYFILE_CLONE also uses this. Leave a comment if you’d like me to test that.

In case these copy-on-write operations are not supported—whether the OS is too old, the underlying file system does not support it, or because you are copying files between different filesystems—you do need to fall back to trying sendfile, or as a last resort, copying byte-by-byte. But to save everyone a lot of time and disk space, please give FICLONE and clonefile(2) a try first.

How to fix nginx throws 400 bad request headers on any header testing tools?

A cause can be invalid encoding in the URL request. Such as % being passed un-encoded.

How to convert CSV file to multiline JSON?

I took @SingleNegationElimination's response and simplified it into a three-liner that can be used in a pipeline:

import csv
import json
import sys

for row in csv.DictReader(sys.stdin):
    json.dump(row, sys.stdout)
    sys.stdout.write('\n')

How to delete files recursively from an S3 bucket

Just saw that Amazon added a "How to Empty a Bucket" option to the AWS console menu:

http://docs.aws.amazon.com/AmazonS3/latest/UG/DeletingaBucket.html

How do I find files that do not contain a given string pattern?

The following command gives me all the files that do not contain the pattern foo:

find .  -not  -ipath '.*svn*' -exec  grep  -H -E -o -c  "foo"  {} \; | grep 0

Upgrading Node.js to latest version

If there is an issue with sudo/root access we can do

npm install stable Or
npm install 10.15.0

Run an Ansible task only when the variable contains a specific string

This works for me in Ansible 2.9:

variable1 = www.example.com. 
variable2 = www.example.org. 

when: ".com" in variable1

and for not:

when: not ".com" in variable2

How to update npm

For Ubuntu 18.04

npm install latest-version

I hope its for you also

Bootstrap modal: close current, open new

This code, close modal opened, open the new modal but inmediatly, new modal is closed.

$(nameClose).modal('hide');
$(nameOpen).modal('show');

My solution for open new modal after close other is:

function swapModals(nameClose,nameOpen) {
    $(nameClose).modal('hide');
    $(nameClose).on('hidden.bs.modal', function () {
        console.log('Fired when hide event has finished!');
        $(nameOpen).modal('show');
    });
}

number several equations with only one number

First of all, you probably don't want the align environment if you have only one column of equations. In fact, your example is probably best with the cases environment. But to answer your question directly, used the aligned environment within equation - this way the outside environment gives the number:

\begin{equation}
  \begin{aligned}
  w^T x_i + b &\geq 1-\xi_i &\text{ if }& y_i=1,  \\
  w^T x_i + b &\leq -1+\xi_i & \text{ if } &y_i=-1,
  \end{aligned}
\end{equation}

The documentation of the amsmath package explains this and more.

Java 8: Difference between two LocalDateTime in multiple units

Joda-Time

Since many of the answers required API 26 support and my min API was 23, I solved it by below code :

import org.joda.time.Days

LocalDate startDate = Something
LocalDate endDate = Something
// The difference would be exclusive of both dates, 
// so in most of use cases we may need to increment it by 1
Days.daysBetween(startDate, endDate).days

How to extract or unpack an .ab file (Android Backup file)

As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.

( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -

Replace backup.ab with the path to your file.

How to Convert double to int in C?

This is the notorious floating point rounding issue. Just add a very small number, to correct the issue.

double a;
a=3669.0;
int b;
b=a+ 1e-9;

What's the difference between Instant and LocalDateTime?

Instant corresponds to time on the prime meridian (Greenwich).

Whereas LocalDateTime relative to OS time zone settings, and

cannot represent an instant without additional information such as an offset or time-zone.

How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

"Dino TW" has provided the link to the comment Hibernate Mapping Exception : Repeated column in mapping for entity which has the vital information.

The link hints to provide "inverse=true" in the set mapping, I tried it and it actually works. It is such a rare situation wherein a Set and Composite key come together. Make inverse=true, we leave the insert & update of the table with Composite key to be taken care by itself.

Below can be the required mapping,

<class name="com.example.CompanyEntity" table="COMPANY">
    <id name="id" column="COMPANY_ID"/>
    <set name="names" inverse="true" table="COMPANY_NAME" cascade="all-delete-orphan" fetch="join" batch-size="1" lazy="false">
        <key column="COMPANY_ID" not-null="true"/>
        <one-to-many entity-name="vendorName"/>
    </set>
</class>

Round button with text and icon in flutter

If you need a button like this:

You can use RaisedButton and use the child property to do this. You need to add a Row and inside row you can add a Text widget and an Icon Widget to achieve this. If you want to use png image, you can use similar widget to achieve this.

RaisedButton(
    onPressed: () {},
    color: Theme.of(context).accentColor,
    child: Padding(
      padding: EdgeInsets.fromLTRB(
          SizeConfig.safeBlockHorizontal * 5,
          0,
          SizeConfig.safeBlockHorizontal * 5,
          0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            'Continue',
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.w700,
              color: Colors.white,
            ),
          ),
          Icon(
            Icons.arrow_forward,
            color: Colors.white,
          )
        ],
      ),
    ),
  ),

Grep regex NOT containing string

grep matches, grep -v does the inverse. If you need to "match A but not B" you usually use pipes:

grep "${PATT}" file | grep -v "${NOTPATT}"

How to decrypt the password generated by wordpress

You will not be able to retrieve a plain text password from wordpress.

Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.

See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password

Java Date vs Calendar

I generally use Date if possible. Although it is mutable, the mutators are actually deprecated. In the end it basically wraps a long that would represent the date/time. Conversely, I would use Calendars if I have to manipulate the values.

You can think of it this way: you only use StringBuffer only when you need to have Strings that you can easily manipulate and then convert them into Strings using toString() method. In the same way, I only use Calendar if I need to manipulate temporal data.

For best practice, I tend to use immutable objects as much as possible outside of the domain model. It significantly reduces the chances of any side effects and it is done for you by the compiler, rather than a JUnit test. You use this technique by creating private final fields in your class.

And coming back to the StringBuffer analogy. Here is some code that shows you how to convert between Calendar and Date

String s = "someString"; // immutable string
StringBuffer buf = new StringBuffer(s); // mutable "string" via StringBuffer
buf.append("x");
assertEquals("someStringx", buf.toString()); // convert to immutable String

// immutable date with hard coded format.  If you are hard
// coding the format, best practice is to hard code the locale
// of the format string, otherwise people in some parts of Europe
// are going to be mad at you.
Date date =     new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2001-01-02");

// Convert Date to a Calendar
Calendar cal = Calendar.getInstance();
cal.setTime(date);

// mutate the value
cal.add(Calendar.YEAR, 1);

// convert back to Date
Date newDate = cal.getTime();

// 
assertEquals(new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2002-01-02"), newDate);

How to reduce a huge excel file

I have worked extensively in Excel and have found the following 3 points very useful

Find if there are cells which apparently do not hold any data but Excel considers them to have data

You can find this by using the following property on a sheet

ActiveSheet.UsedRange.Rows.Count
ActiveSheet.UsedRange.Columns.Count

If this range is more than the cells on which you have data, delete the rest of the rows/columns

You will be surprised to see the amount of space it can free

Convert files to .xlsb format

XLSM format is to make Excel compliant with Open XML, but there are very few instances when we actually use the XML format of Excel. This reduces size by almost 50% if not more

Optimum way of storing information

For example if you have to save the stock price for around 10 years, and you need to save Open, High, Low, Close for a stock, this would result in (252*10) * (4) cells being used

Instead, of using separate columns for Open,High,Low,Close save them in a single column with a field separator Open:High:Low:Close

You can easily write a function to extract info from the single column whenever you want to, but it will free up almost 2/3rd space that you are currently taking up

What's the difference between the Window.Loaded and Window.ContentRendered events

If you visit this link https://msdn.microsoft.com/library/ms748948%28v=vs.100%29.aspx#Window_Lifetime_Events and scroll down to Window Lifetime Events it will show you the event order.

Open:

  1. SourceInitiated
  2. Activated
  3. Loaded
  4. ContentRendered

Close:

  1. Closing
  2. Deactivated
  3. Closed

JavaScript, get date of the next day

You can use:

var tomorrow = new Date();
tomorrow.setDate(new Date().getDate()+1);

For example, since there are 30 days in April, the following code will output May 1:

var day = new Date('Apr 30, 2000');
console.log(day); // Apr 30 2000

var nextDay = new Date(day);
nextDay.setDate(day.getDate() + 1);
console.log(nextDay); // May 01 2000    

See fiddle.

Remove carriage return from string

For VB.net

vbcrlf = environment.newline...

Dim MyString As String = "This is a Test" & Environment.NewLine & " This is the second line!"

Dim MyNewString As String = MyString.Replace(Environment.NewLine,String.Empty)

Changing iframe src with Javascript

In this case, it's probably because you are using the wrong brackets here:

document.getElementById['calendar'].src = loc;

should be

document.getElementById('calendar').src = loc;

How can I rename a single column in a table at select?

select table1.price, table2.price as other_price .....

How do I initialize a byte array in Java?

Using a function converting an hexa string to byte[], you could do

byte[] CDRIVES = hexStringToByteArray("e04fd020ea3a6910a2d808002b30309d");

I'd suggest you use the function defined by Dave L in Convert a string representation of a hex dump to a byte array using Java?

I insert it here for maximum readability :

public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

If you let CDRIVES static and final, the performance drop is irrelevant.

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

Vava's answer is on the mark. If you use jQuery, then the $.each() function takes care of this, hence it is safer to use.

$.each(evtListeners, function(index, elem) {
    // your code
});