Programs & Examples On #Custom application

Entity Framework Provider type could not be loaded?

Make sure EntityFramework.dll, EntityFramework.SqlServer.dll and your provider's dll (for SQL Server Compact, that will EntityFramework.SqlServerCompact.dll) are in the deployed application folder. This is especially important for deployed application.

Android device chooser - My device seems offline

I had the same problem several times - just rebooting solves this.

Insert 2 million rows into SQL Server quickly

  1. I think its better you read data of text file in DataSet

  2. Try out SqlBulkCopy - Bulk Insert into SQL from C# App

    // connect to SQL
    using (SqlConnection connection = new SqlConnection(connString))
    {
        // make sure to enable triggers
        // more on triggers in next post
        SqlBulkCopy bulkCopy = new SqlBulkCopy(
            connection, 
            SqlBulkCopyOptions.TableLock | 
            SqlBulkCopyOptions.FireTriggers | 
            SqlBulkCopyOptions.UseInternalTransaction,
            null
            );
    
        // set the destination table name
        bulkCopy.DestinationTableName = this.tableName;
        connection.Open();
    
        // write the data in the "dataTable"
        bulkCopy.WriteToServer(dataTable);
        connection.Close();
    }
    // reset
    this.dataTable.Clear();
    

or

after doing step 1 at the top

  1. Create XML from DataSet
  2. Pass XML to database and do bulk insert

you can check this article for detail : Bulk Insertion of Data Using C# DataTable and SQL server OpenXML function

But its not tested with 2 million record, it will do but consume memory on machine as you have to load 2 million record and insert it.

checking for typeof error in JS

I asked the original question - @Trott's answer is surely the best.

However with JS being a dynamic language and with there being so many JS runtime environments, the instanceof operator can fail especially in front-end development when crossing boundaries such as iframes. See: https://github.com/mrdoob/three.js/issues/5886

If you are ok with duck typing, this should be good:

let isError = function(e){
 return e && e.stack && e.message;
}

I personally prefer statically typed languages, but if you are using a dynamic language, it's best to embrace a dynamic language for what it is, rather than force it to behave like a statically typed language.

if you wanted to get a little more precise, you could do this:

   let isError = function(e){
     return e && e.stack && e.message && typeof e.stack === 'string' 
            && typeof e.message === 'string';
    }

Force to open "Save As..." popup open at text link click for PDF in HTML

I found a very simple solution for Firefox (only works with a relative rather than a direct href): add type="application/octet-stream":

<a href="./file.pdf" id='example' type="application/octet-stream">Example</a>

How do I get which JRadioButton is selected from a ButtonGroup

You could use getSelectedObjects() of ItemSelectable (superinterface of ButtonModel) which returns the list of selected items. In case of a radio button group it can only be one or none at all.

How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

A filter converting any dates in various ISO-related formats (and who'd use anything else after reading the writings of the Mighty Kuhn?) on standard input to seconds-since-the-epoch time on standard output might serve to illustrate both parts:

martind@whitewater:~$ cat `which isoToEpoch`
#!/usr/bin/perl -w
use strict;
use Time::Piece;
# sudo apt-get install libtime-piece-perl
while (<>) {
  # date --iso=s:
  # 2007-02-15T18:25:42-0800
  # Other matched formats:
  # 2007-02-15 13:50:29 (UTC-0800)
  # 2007-02-15 13:50:29 (UTC-08:00)
  s/(\d{4}-\d{2}-\d{2}([T ])\d{2}:\d{2}:\d{2})(?:\.\d+)? ?(?:\(UTC)?([+\-]\d{2})?:?00\)?/Time::Piece->strptime ($1, "%Y-%m-%d$2%H:%M:%S")->epoch - (defined ($3) ? $3 * 3600 : 0)/eg;
  print;
}
martind@whitewater:~$ 

Method call if not null in C#

From C# 6 onwards, you can just use:

MyEvent?.Invoke();

or:

obj?.SomeMethod();

The ?. is the null-propagating operator, and will cause the .Invoke() to be short-circuited when the operand is null. The operand is only accessed once, so there is no risk of the "value changes between check and invoke" problem.

===

Prior to C# 6, no: there is no null-safe magic, with one exception; extension methods - for example:

public static void SafeInvoke(this Action action) {
    if(action != null) action();
}

now this is valid:

Action act = null;
act.SafeInvoke(); // does nothing
act = delegate {Console.WriteLine("hi");}
act.SafeInvoke(); // writes "hi"

In the case of events, this has the advantage of also removing the race-condition, i.e. you don't need a temporary variable. So normally you'd need:

var handler = SomeEvent;
if(handler != null) handler(this, EventArgs.Empty);

but with:

public static void SafeInvoke(this EventHandler handler, object sender) {
    if(handler != null) handler(sender, EventArgs.Empty);
}

we can use simply:

SomeEvent.SafeInvoke(this); // no race condition, no null risk

Submitting a multidimensional array via POST with php

you could submit all parameters with such naming:

params[0][topdiameter]
params[0][bottomdiameter]
params[1][topdiameter]
params[1][bottomdiameter]

then later you do something like this:

foreach ($_REQUEST['params'] as $item) {
    echo $item['topdiameter'];
    echo $item['bottomdiameter'];
}

Change GridView row color based on condition

protected void DrugGridView_RowDataBound(object sender, GridViewRowEventArgs e)

{
    // To check condition on integer value
    if (Convert.ToInt16(DataBinder.Eval(e.Row.DataItem, "Dosage")) == 50)
    {
      e.Row.BackColor = System.Drawing.Color.Cyan;
    }
}

Simple dynamic breadcrumb

Hmm, from the examples you gave it seems like "$_SERVER['REQUEST_URI']" and the explode() function could help you. You could use explode to break up the URL following the domain name into an array, separating it at each forward-slash.

As a very basic example, something like this could be implemented:

$crumbs = explode("/",$_SERVER["REQUEST_URI"]);
foreach($crumbs as $crumb){
    echo ucfirst(str_replace(array(".php","_"),array(""," "),$crumb) . ' ');
}

Manifest Merger failed with multiple errors in Android Studio

My case i have fixed it by

build.gradle(Module:app)

defaultConfig {
----------
multiDexEnabled true
}
dependencies {
    ...........
    implementation 'com.google.android.gms:play-services-gcm:11.0.2'
    implementation 'com.onesignal:OneSignal:3.+@aar'
    }

This answer releted to OnSignal push notification

How to delete a record by id in Flask-SQLAlchemy

Another possible solution specially if you want batch delete

deleted_objects = User.__table__.delete().where(User.id.in_([1, 2, 3]))
session.execute(deleted_objects)
session.commit()

Could not instantiate mail function. Why this error occurring

Had same problem. Just did a quick look up apache2 error.log file and it said exactly what was the problem:

> sh: /usr/sbin/sendmail: Permission denied

So, the solution was to give proper permissions for /usr/sbin/sendmail file (it wasn't accessible from php).

Command to do this would be:

> chmod 777 /usr/sbin/sendmail

be sure that it even exists!

JOptionPane Input to int

// sample code for addition using JOptionPane

import javax.swing.JOptionPane;

public class Addition {

    public static void main(String[] args) {

        String firstNumber = JOptionPane.showInputDialog("Input <First Integer>");

        String secondNumber = JOptionPane.showInputDialog("Input <Second Integer>");

        int num1 = Integer.parseInt(firstNumber);
        int num2 = Integer.parseInt(secondNumber);
        int sum = num1 + num2;
        JOptionPane.showMessageDialog(null, "Sum is" + sum, "Sum of two Integers", JOptionPane.PLAIN_MESSAGE);
    }
}

Why do we use web.xml?

It says all the requests to go through WicketFilter


Also, if you use wicket WicketApplication for application level settings. Like URL patterns and things that are true at app level


This is what you need really, http://wicket.apache.org/learn/examples/helloworld.html

Convert integer to hex and hex to integer

IIF(Fields!HIGHLIGHT_COLOUR.Value="","#FFFFFF","#" & hex(Fields!HIGHLIGHT_COLOUR.Value) & StrDup(6-LEN(hex(Fields!HIGHLIGHT_COLOUR.Value)),"0"))

Is working for me as an expression in font colour

Split string based on regex

You could use a lookahead:

re.split(r'[ ](?=[A-Z]+\b)', input)

This will split at every space that is followed by a string of upper-case letters which end in a word-boundary.

Note that the square brackets are only for readability and could as well be omitted.

If it is enough that the first letter of a word is upper case (so if you would want to split in front of Hello as well) it gets even easier:

re.split(r'[ ](?=[A-Z])', input)

Now this splits at every space followed by any upper-case letter.

Selecting specific rows and columns from NumPy array

USE:

 >>> a[[0,1,3]][:,[0,2]]
array([[ 0,  2],
   [ 4,  6],
   [12, 14]])

OR:

>>> a[[0,1,3],::2]
array([[ 0,  2],
   [ 4,  6],
   [12, 14]])

NameError: name 'self' is not defined

For cases where you also wish to have the option of setting 'b' to None:

def p(self, **kwargs):
    b = kwargs.get('b', self.a)
    print b

Remove HTML Tags in Javascript with Regex

you can use a powerful library for management String which is undrescore.string.js

_('a <a href="#">link</a>').stripTags()

=> 'a link'

_('a <a href="#">link</a><script>alert("hello world!")</script>').stripTags()

=> 'a linkalert("hello world!")'

Don't forget to import this lib as following :

        <script src="underscore.js" type="text/javascript"></script>
        <script src="underscore.string.js" type="text/javascript"></script>
        <script type="text/javascript"> _.mixin(_.str.exports())</script>

Compare two MySQL databases

There is a Schema Synchronization Tool in SQLyog (commercial) which generates SQL for synchronizing two databases.

enter image description here

How to do IF NOT EXISTS in SQLite

How about this?

INSERT OR IGNORE INTO EVENTTYPE (EventTypeName) VALUES 'ANI Received'

(Untested as I don't have SQLite... however this link is quite descriptive.)

Additionally, this should also work:

INSERT INTO EVENTTYPE (EventTypeName)
SELECT 'ANI Received'
WHERE NOT EXISTS (SELECT 1 FROM EVENTTYPE WHERE EventTypeName = 'ANI Received');

How to Convert Boolean to String

The other solutions here all have caveats (though they address the question at hand). If you are (1) looping over mixed-types or (2) want a generic solution that you can export as a function or include in your utilities, none of the other solutions here will work.

The simplest and most self-explanatory solution is:

// simplest, most-readable
if (is_bool($res) {
    $res = $res ? 'true' : 'false';
}

// same as above but written more tersely
$res = is_bool($res) ? ($res ? 'true' : 'false') : $res;

// Terser still, but completely unnecessary  function call and must be
// commented due to poor readability. What is var_export? What is its
// second arg? Why are we exporting stuff?
$res = is_bool($res) ? var_export($res, 1) : $res;

But most developers reading your code will require a trip to http://php.net/var_export to understand what the var_export does and what the second param is.

1. var_export

Works for boolean input but converts everything else to a string as well.

// OK
var_export(false, 1); // 'false'
// OK
var_export(true, 1);  // 'true'
// NOT OK
var_export('', 1);  // '\'\''
// NOT OK
var_export(1, 1);  // '1'

2. ($res) ? 'true' : 'false';

Works for boolean input but converts everything else (ints, strings) to true/false.

// OK
true ? 'true' : 'false' // 'true'
// OK
false ? 'true' : 'false' // 'false'
// NOT OK
'' ? 'true' : 'false' // 'false'
// NOT OK
0 ? 'true' : 'false' // 'false'

3. json_encode()

Same issues as var_export and probably worse since json_encode cannot know if the string true was intended a string or a boolean.

Datetime current year and month in Python

You can write the accepted answer as a one-liner using date.replace:

datem = datetime.today().replace(day=1)

Finish all previous activities

When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your application starts, clear all the other activities, then have the last remaining activity finish. Have the following code run when the user presses the exit button. In my case, LoginActivity is the first activity in my program to run.

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

The above code clears all the activities except for LoginActivity. Then put the following code inside the LoginActivity's onCreate(...), to listen for when LoginActivity is recreated and the 'EXIT' signal was passed:

if (getIntent().getBooleanExtra("EXIT", false)) {
    finish();  
}

Why is making an exit button in Android so hard?

Android tries hard to discourage you from having an "exit" button in your application, because they want the user to never care about whether or not the programs they use are running in the background or not.

The Android OS developers want your program to be able to survive an unexpected shutdown and power off of the phone, and when the user restarts the program, they pick up right where they left off. So the user can receive a phone call while they use your application, and open maps which requires your application to be freed for more resources.

When the user resumes your application, they pick up right where they left off with no interruption. This exit button is usurping power from the activity manager, potentially causing problems with the automatically managed android program life cycle.

Install a module using pip for specific python version

I had Python 2.7 installed via chocolatey on Windows and found pip2.7.exe in C:\tools\python2\Scripts.

Using this executable instead of the pip command installed the correct module for me (requests for Python 2.7).

SQL Server query - Selecting COUNT(*) with DISTINCT

try this:

SELECT
    COUNT(program_name) AS [Count],program_type AS [Type]
    FROM (SELECT DISTINCT program_name,program_type
              FROM cm_production 
              WHERE push_number=@push_number
         ) dt
    GROUP BY program_type

What is the => assignment in C# in a property signature

What you're looking at is an expression-bodied member not a lambda expression.

When the compiler encounters an expression-bodied property member, it essentially converts it to a getter like this:

public int MaxHealth
{
    get
    {
        return Memory[Address].IsValid ? Memory[Address].Read<int>(Offs.Life.MaxHp) : 0;
    }
}

(You can verify this for yourself by pumping the code into a tool called TryRoslyn.)

Expression-bodied members - like most C# 6 features - are just syntactic sugar. This means that they don’t provide functionality that couldn't otherwise be achieved through existing features. Instead, these new features allow a more expressive and succinct syntax to be used

As you can see, expression-bodied members have a handful of shortcuts that make property members more compact:

  • There is no need to use a return statement because the compiler can infer that you want to return the result of the expression
  • There is no need to create a statement block because the body is only one expression
  • There is no need to use the get keyword because it is implied by the use of the expression-bodied member syntax.

I have made the final point bold because it is relevant to your actual question, which I will answer now.

The difference between...

// expression-bodied member property
public int MaxHealth => x ? y:z;

And...

// field with field initializer
public int MaxHealth = x ? y:z;

Is the same as the difference between...

public int MaxHealth
{
    get
    {
        return x ? y:z;
    }
}

And...

public int MaxHealth = x ? y:z;

Which - if you understand properties - should be obvious.

Just to be clear, though: the first listing is a property with a getter under the hood that will be called each time you access it. The second listing is is a field with a field initializer, whose expression is only evaluated once, when the type is instantiated.

This difference in syntax is actually quite subtle and can lead to a "gotcha" which is described by Bill Wagner in a post entitled "A C# 6 gotcha: Initialization vs. Expression Bodied Members".

While expression-bodied members are lambda expression-like, they are not lambda expressions. The fundamental difference is that a lambda expression results in either a delegate instance or an expression tree. Expression-bodied members are just a directive to the compiler to generate a property behind the scenes. The similarity (more or less) starts and end with the arrow (=>).

I'll also add that expression-bodied members are not limited to property members. They work on all these members:

  • Properties
  • Indexers
  • Methods
  • Operators

Added in C# 7.0

However, they do not work on these members:

  • Nested Types
  • Events
  • Fields

How to comment multiple lines with space or indent

Pressing Ctrl+K+C or Ctrl+E+C After selecting the lines you want to comment will not give space after slashes. you can use multiline select to provide space as suggested by Habib

Perhaps, you can use /* before the lines you want to comment and after */ in that case you might not need to provide spaces.

/*
  First Line to Comment
  Second Line to Comment
  Third Line to Comment      
*/

How to center buttons in Twitter Bootstrap 3?

add to your style:

display: table; margin: 0 auto;

Simple way to create matrix of random numbers

x = np.int_(np.random.rand(10) * 10)

For random numbers out of 10. For out of 20 we have to multiply by 20.

resource error in android studio after update: No Resource Found

I noticed I didn't have sdk 23 installed. So I first installed it then re-built my project. And it worked fine. Also compilesdkVersion should be 23

Ruby max integer

Reading the friendly manual? Who'd want to do that?

start = Time.now
largest_known_fixnum = 1
smallest_known_bignum = nil

until smallest_known_bignum == largest_known_fixnum + 1
  if smallest_known_bignum.nil?
    next_number_to_try = largest_known_fixnum * 1000
  else
    next_number_to_try = (smallest_known_bignum + largest_known_fixnum) / 2 # Geometric mean would be more efficient, but more risky
  end

  if next_number_to_try <= largest_known_fixnum ||
       smallest_known_bignum && next_number_to_try >= smallest_known_bignum
    raise "Can't happen case" 
  end

  case next_number_to_try
    when Bignum then smallest_known_bignum = next_number_to_try
    when Fixnum then largest_known_fixnum = next_number_to_try
    else raise "Can't happen case"
  end
end

finish = Time.now
puts "The largest fixnum is #{largest_known_fixnum}"
puts "The smallest bignum is #{smallest_known_bignum}"
puts "Calculation took #{finish - start} seconds"

How to correctly get image from 'Resources' folder in NetBeans

Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image. In one of my tries i use

    String pathToImageSortBy = "resources/testDataIcons/filling.png";
    ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));

But correct way was use name of my project in path to resource

String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));

Find provisioning profile in Xcode 5

If it's sufficient to use the following criteria to locate the profile:

<key>Name</key>
<string>iOS Team Provisioning Profile: *</string>

you can scan the directory using awk. This one-liner will find the first file that contains the name starting with "iOS Team".

awk 'BEGIN{e=1;pat="<string>"tolower("iOS Team")}{cur=tolower($0);if(cur~pat &&prev~/<key>name<\/key>/){print FILENAME;e=0;exit};if($0!~/^\s*$/)prev=cur}END{exit e}' *

Here's a script that also returns the first match, but is easier to work with.

#!/bin/bash

if [ $# != 1 ] ; then
    echo Usage: $0 \<start of provisioning profile name\>
    exit 1
fi

read -d '' script << 'EOF'
BEGIN {
    e = 1
    pat = "<string>"tolower(prov)
}
{
    cur = tolower($0)
    if (cur ~ pat && prev ~ /<key>name<\\/key>/) {
        print FILENAME
        e = 0
        exit
    }
    if ($0 !~ /^\s*$/) {
        prev = cur
    }
}
END {
 exit e
}
EOF


awk -v "prov=$1" "$script" *

It can be called from within the profiles directory, $HOME/Library/MobileDevice/Provisioning Profiles:

~/findprov "iOS Team"

To use the script, save it to a suitable location and remember to set the executable mode; e.g., chmod ugo+x

Show/Hide Div on Scroll

Try this code

$('window').scrollDown(function(){$(#div).hide()});

$('window').scrollUp(function(){ $(#div).show() });

Angular 4 checkbox change value

This works for me, angular 9:

component.html file:

<mat-checkbox (change)="checkValue($event)">text</mat-checkbox>

component.ts file:

checkValue(e){console.log(e.target.checked)}

cannot convert data (type interface {}) to type string: need type assertion

According to the Go specification:

For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T.

A "type assertion" allows you to declare an interface value contains a certain concrete type or that its concrete type satisfies another interface.

In your example, you were asserting data (type interface{}) has the concrete type string. If you are wrong, the program will panic at runtime. You do not need to worry about efficiency, checking just requires comparing two pointer values.

If you were unsure if it was a string or not, you could test using the two return syntax.

str, ok := data.(string)

If data is not a string, ok will be false. It is then common to wrap such a statement into an if statement like so:

if str, ok := data.(string); ok {
    /* act on str */
} else {
    /* not string */
}

Iterating over and deleting from Hashtable in Java

You can use Enumeration:

Hashtable<Integer, String> table = ...

Enumeration<Integer> enumKey = table.keys();
while(enumKey.hasMoreElements()) {
    Integer key = enumKey.nextElement();
    String val = table.get(key);
    if(key==0 && val.equals("0"))
        table.remove(key);
}

How to set scope property with ng-init?

Just set ng-init as a function. You should not have to use watch.

<body ng-controller="MainCtrl" ng-init="init()">
  <div ng-init="init('Blah')">{{ testInput }}</div>
</body>

app.controller('MainCtrl', ['$scope', function ($scope) {
  $scope.testInput = null;
  $scope.init = function(value) {
    $scope.testInput= value;
  }
}]);

Here's an example.

Plunker

Pandas read_sql with parameters

The read_sql docs say this params argument can be a list, tuple or dict (see docs).

To pass the values in the sql query, there are different syntaxes possible: ?, :1, :name, %s, %(name)s (see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2 in your case I suppose).

In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2 documentation, they support the %(name)s style (and so not the :name I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:

df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
                     'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
                   db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
                   index_col=['Timestamp'])

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

May be the problem is with your python-opencv version. It's better to downgrade your version to 3.3.0.9 which does not include any GUI dependencies. Same question was found on GitHub here the link to the answer.

MySQL & Java - Get id of the last inserted value (JDBC)

Alternatively you can do:

Statement stmt = db.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
numero = stmt.executeUpdate();

ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
    risultato=rs.getString(1);
}

But use Sean Bright's answer instead for your scenario.

Automatically open Chrome developer tools when new tab/new window is opened

I came here looking for a similar solution. I really wanted to see the chrome output for the pageload from a new tab. (a form submission in my case) The solution I actually used was to modify the form target attribute so that the form submission would occur in the current tab. I was able to capture the network request. Problem Solved!

Using sed to split a string with a delimiter

Using \n in sed is non-portable. The portable way to do what you want with sed is:

sed 's/:/\
/g' ~/Desktop/myfile.txt

but in reality this isn't a job for sed anyway, it's the job tr was created to do:

tr ':' '
' < ~/Desktop/myfile.txt

method in class cannot be applied to given types

generateNumbers() expects a parameter and you aren't passing one in!

generateNumbers() also returns after it has set the first random number - seems to be some confusion about what it is trying to do.

Using an array as needles in strpos

The below code not only shows how to do it, but also puts it in an easy to use function moving forward. It was written by "jesda". (I found it online)

PHP Code:

<?php
/* strpos that takes an array of values to match against a string
 * note the stupid argument order (to match strpos)
 */
function strpos_arr($haystack, $needle) {
    if(!is_array($needle)) $needle = array($needle);
    foreach($needle as $what) {
        if(($pos = strpos($haystack, $what))!==false) return $pos;
    }
    return false;
}
?>

Usage:

$needle = array('something','nothing');
$haystack = "This is something";
echo strpos_arr($haystack, $needle); // Will echo True

$haystack = "This isn't anything";
echo strpos_arr($haystack, $needle); // Will echo False 

How can I find whitespace in a String?

You can use charAt() function to find out spaces in string.

 public class Test {
  public static void main(String args[]) {
   String fav="Hi Testing  12 3";
   int counter=0;
   for( int i=0; i<fav.length(); i++ ) {
    if(fav.charAt(i) == ' ' ) {
     counter++;
      }
     }
    System.out.println("Number of spaces "+ counter);
    //This will print Number of spaces 4
   }
  }

Converting string format to datetime in mm/dd/yyyy

You can change the format too by doing this

string fecha = DateTime.Now.ToString(format:"dd-MM-yyyy");

// this change the "/" for the "-"

Converting BigDecimal to Integer

TL;DR

Use one of these for universal conversion needs

//Java 7 or below
bigDecimal.setScale(0, RoundingMode.DOWN).intValueExact()
//Java 8    
bigDecimal.toBigInteger().intValueExact()

Reasoning

The answer depends on what the requirements are and how you answer these question.

  • Will the BigDecimal potentially have a non-zero fractional part?
  • Will the BigDecimal potentially not fit into the Integer range?
  • Would you like non-zero fractional parts rounded or truncated?
  • How would you like non-zero fractional parts rounded?

If you answered no to the first 2 questions, you could just use BigDecimal.intValueExact() as others have suggested and let it blow up when something unexpected happens.

If you are not absolutely 100% confident about question number 2, then intValue() is always the wrong answer.

Making it better

Let's use the following assumptions based on the other answers.

  • We are okay with losing precision and truncating the value because that's what intValueExact() and auto-boxing do
  • We want an exception thrown when the BigDecimal is larger than the Integer range because anything else would be crazy unless you have a very specific need for the wrap around that happens when you drop the high-order bits.

Given those params, intValueExact() throws an exception when we don't want it to if our fractional part is non-zero. On the other hand, intValue() doesn't throw an exception when it should if our BigDecimal is too large.

To get the best of both worlds, round off the BigDecimal first, then convert. This also has the benefit of giving you more control over the rounding process.

Spock Groovy Test

void 'test BigDecimal rounding'() {
    given:
    BigDecimal decimal = new BigDecimal(Integer.MAX_VALUE - 1.99)
    BigDecimal hugeDecimal = new BigDecimal(Integer.MAX_VALUE + 1.99)
    BigDecimal reallyHuge = new BigDecimal("10000000000000000000000000000000000000000000000")
    String decimalAsBigIntString = decimal.toBigInteger().toString()
    String hugeDecimalAsBigIntString = hugeDecimal.toBigInteger().toString()
    String reallyHugeAsBigIntString = reallyHuge.toBigInteger().toString()

    expect: 'decimals that can be truncated within Integer range to do so without exception'
    //GOOD: Truncates without exception
    '' + decimal.intValue() == decimalAsBigIntString
    //BAD: Throws ArithmeticException 'Non-zero decimal digits' because we lose information
    // decimal.intValueExact() == decimalAsBigIntString
    //GOOD: Truncates without exception
    '' + decimal.setScale(0, RoundingMode.DOWN).intValueExact() == decimalAsBigIntString

    and: 'truncated decimal that cannot be truncated within Integer range throw conversionOverflow exception'
    //BAD: hugeDecimal.intValue() is -2147483648 instead of 2147483648
    //'' + hugeDecimal.intValue() == hugeDecimalAsBigIntString
    //BAD: Throws ArithmeticException 'Non-zero decimal digits' because we lose information
    //'' + hugeDecimal.intValueExact() == hugeDecimalAsBigIntString
    //GOOD: Throws conversionOverflow ArithmeticException because to large
    //'' + hugeDecimal.setScale(0, RoundingMode.DOWN).intValueExact() == hugeDecimalAsBigIntString

    and: 'truncated decimal that cannot be truncated within Integer range throw conversionOverflow exception'
    //BAD: hugeDecimal.intValue() is 0
    //'' + reallyHuge.intValue() == reallyHugeAsBigIntString
    //GOOD: Throws conversionOverflow ArithmeticException because to large
    //'' + reallyHuge.intValueExact() == reallyHugeAsBigIntString
    //GOOD: Throws conversionOverflow ArithmeticException because to large
    //'' + reallyHuge.setScale(0, RoundingMode.DOWN).intValueExact() == reallyHugeAsBigIntString

    and: 'if using Java 8, BigInteger has intValueExact() just like BigDecimal'
    //decimal.toBigInteger().intValueExact() == decimal.setScale(0, RoundingMode.DOWN).intValueExact()
}

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

If its a maven project, add the below dependency in your pom file

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.3.4</version>
    </dependency>

How do I manage conflicts with git submodules?

I had this problem with git rebase -i origin/master to a branch. I wanted to take master's version of the submodule ref, so I simply did:

git reset master path/to/submodule

and then

git rebase --continue

That solved the problem for me.

How do you find out which version of GTK+ is installed on Ubuntu?

You can use this command:

$ dpkg -s libgtk2.0-0|grep '^Version'

Is it necessary to assign a string to a variable before comparing it to another?

Brian, also worth throwing in here - the others are of course correct that you don't need to declare a string variable. However, next time you want to declare a string you don't need to do the following:

NSString *myString = [[NSString alloc] initWithFormat:@"SomeText"];

Although the above does work, it provides a retained NSString variable which you will then need to explicitly release after you've finished using it.

Next time you want a string variable you can use the "@" symbol in a much more convenient way:

NSString *myString = @"SomeText";

This will be autoreleased when you've finished with it so you'll avoid memory leaks too...

Hope that helps!

What's the difference between git clone --mirror and git clone --bare

The difference is that when using --mirror, all refs are copied as-is. This means everything: remote-tracking branches, notes, refs/originals/* (backups from filter-branch). The cloned repo has it all. It's also set up so that a remote update will re-fetch everything from the origin (overwriting the copied refs). The idea is really to mirror the repository, to have a total copy, so that you could for example host your central repo in multiple places, or back it up. Think of just straight-up copying the repo, except in a much more elegant git way.

The new documentation pretty much says all this:

--mirror

Set up a mirror of the source repository. This implies --bare. Compared to --bare, --mirror not only maps local branches of the source to local branches of the target, it maps all refs (including remote branches, notes etc.) and sets up a refspec configuration such that all these refs are overwritten by a git remote update in the target repository.

My original answer also noted the differences between a bare clone and a normal (non-bare) clone - the non-bare clone sets up remote tracking branches, only creating a local branch for HEAD, while the bare clone copies the branches directly.

Suppose origin has a few branches (master (HEAD), next, pu, and maint), some tags (v1, v2, v3), some remote branches (devA/master, devB/master), and some other refs (refs/foo/bar, refs/foo/baz, which might be notes, stashes, other devs' namespaces, who knows).

  • git clone origin-url (non-bare): You will get all of the tags copied, a local branch master (HEAD) tracking a remote branch origin/master, and remote branches origin/next, origin/pu, and origin/maint. The tracking branches are set up so that if you do something like git fetch origin, they'll be fetched as you expect. Any remote branches (in the cloned remote) and other refs are completely ignored.

  • git clone --bare origin-url: You will get all of the tags copied, local branches master (HEAD), next, pu, and maint, no remote tracking branches. That is, all branches are copied as is, and it's set up completely independent, with no expectation of fetching again. Any remote branches (in the cloned remote) and other refs are completely ignored.

  • git clone --mirror origin-url: Every last one of those refs will be copied as-is. You'll get all the tags, local branches master (HEAD), next, pu, and maint, remote branches devA/master and devB/master, other refs refs/foo/bar and refs/foo/baz. Everything is exactly as it was in the cloned remote. Remote tracking is set up so that if you run git remote update all refs will be overwritten from origin, as if you'd just deleted the mirror and recloned it. As the docs originally said, it's a mirror. It's supposed to be a functionally identical copy, interchangeable with the original.

Shell - How to find directory of some command?

The Korn shell, ksh, offers the whence built-in, which identifies other shell built-ins, macros, etc. The which command is more portable, however.

Checking that a List is not empty in Hamcrest

Well there's always

assertThat(list.isEmpty(), is(false));

... but I'm guessing that's not quite what you meant :)

Alternatively:

assertThat((Collection)list, is(not(empty())));

empty() is a static in the Matchers class. Note the need to cast the list to Collection, thanks to Hamcrest 1.2's wonky generics.

The following imports can be used with hamcrest 1.3

import static org.hamcrest.Matchers.empty;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.*;

passing JSON data to a Spring MVC controller

  1. Html

    $('#save').click(function(event) {        
        var jenis = $('#jenis').val();
        var model = $('#model').val();
        var harga = $('#harga').val();
        var json = { "jenis" : jenis, "model" : model, "harga": harga};
        $.ajax({
            url: 'phone/save',
            data: JSON.stringify(json),
            type: "POST",           
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },
            success: function(data){ 
                alert(data);
            }
        });
    
        event.preventDefault();
    });
    
    1. Controller

      @Controller
      @RequestMapping(value="/phone")
      public class phoneController {
      
          phoneDao pd=new phoneDao();
      
          @RequestMapping(value="/save",method=RequestMethod.POST)
          public @ResponseBody
          int save(@RequestBody Smartphones phone)
          {
              return pd.save(phone);
          }
      
    2. Dao

      public Integer save(Smartphones i) {
          int id = 0;
          Session session=HibernateUtil.getSessionFactory().openSession();
          Transaction trans=session.beginTransaction();
          try {
              session.save(i);   
              id=i.getId();
              trans.commit();
          }
          catch(HibernateException he){}
          return id;
      }
      

Regular Expression with wildcards to match any character

Without knowing the exact regex implementation you're making use of, I can only give general advice. (The syntax I will be perl as that's what I know, some languages will require tweaking)

Looking at ABC: (z) jan 02 1999 \n

  • The first thing to match is ABC: So using our regex is /ABC:/

  • You say ABC is always at the start of the string so /^ABC/ will ensure that ABC is at the start of the string.

  • You can match spaces with the \s (note the case) directive. With all directives you can match one or more with + (or 0 or more with *)

  • You need to escape the usage of ( and ) as it's a reserved character. so \(\)

  • You can match any non space or newline character with .

  • You can match anything at all with .* but you need to be careful you're not too greedy and capture everything.

So in order to capture what you've asked. I would use /^ABC:\s*\(.+?\)\s*(.+)$/

Which I read as:

Begins with ABC:

May have some spaces

has (

has some characters

has )

may have some spaces

then capture everything until the end of the line (which is $).

I highly recommend keeping a copy of the following laying about http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

How to use private Github repo as npm dependency

If someone is looking for another option for Git Lab and the options above do not work, then we have another option. For a local installation of Git Lab server, we have found that the approach, below, allows us to include the package dependency. We generated and use an access token to do so.

$ npm install --save-dev https://git.yourdomain.com/userOrGroup/gitLabProjectName/repository/archive.tar.gz?private_token=InsertYourAccessTokenHere

Of course, if one is using an access key this way, it should have a limited set of permissions.

Good luck!

How to create a file in a directory in java?

When you write to the file via file output stream, the file will be created automatically. but make sure all necessary directories ( folders) are created.

    String absolutePath = ...
    try{
       File file = new File(absolutePath);
       file.mkdirs() ;
       //all parent folders are created
       //now the file will be created when you start writing to it via FileOutputStream.
      }catch (Exception e){
        System.out.println("Error : "+ e.getmessage());
       }

UILabel - Wordwrap text

If you set numberOfLines to 0 (and the label to word wrap), the label will automatically wrap and use as many of lines as needed.

If you're editing a UILabel in IB, you can enter multiple lines of text by pressing option+return to get a line break - return alone will finish editing.

Convert HashBytes to VarChar

SELECT CONVERT(NVARCHAR(32),HashBytes('MD5', 'Hello World'),2)

Django set field value after a form is initialized

Something like Nigel Cohen's would work if you were adding data to a copy of the collected set of form data:

form = FormType(request.POST)
if request.method == "POST":
    formcopy = form(request.POST.copy())
    formcopy.data['Email'] = GetEmailString()

Compare dates with javascript

The best way is,

var first = '2012-11-21';
var second = '2012-11-03';

if (new Date(first) > new Date(second) {
    .....
}

How do you show animated GIFs on a Windows Form (c#)

If you put it in a PictureBox control, it should just work

Check if XML Element exists

 string name = "some node name";
    var xDoc = XDocument.Load("yourFile");
    var docRoot = xDoc.Element("your docs root name");

     var aNode = docRoot.Elements().Where(x => x.Name == name).FirstOrDefault();
                if (aNode == null)
                {
                    return $"file has no {name}";
                }

How to validate numeric values which may contain dots or commas?

If you want to be very permissive, required only two final digits with comma or dot:

^([,.\d]+)([,.]\d{2})$

Value of type 'T' cannot be converted to

If you're checking for explicit types, why are you declaring those variables as T's?

T HowToCast<T>(T t)
{
    if (typeof(T) == typeof(string))
    {
        var newT1 = "some text";
        var newT2 = t;  //this builds but I'm not sure what it does under the hood.
        var newT3 = t.ToString();  //for sure the string you want.
    }

    return t;
}

bash export command

change from bash to sh scripting, make my script work.

!/bin/sh

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

I first tried Mohammed Emad's answer - no joy. Then I tried

git clean -x -d -f

which brought me to a new "Roslyn" error which I was able to fix by manually editing my .csproj.

Interestingly, after I'd read down a bit further down the page on the Roslyn question, I found another suggestion with even more votes (Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r). Thinking I'd rather implement that than manually edit .csproj, I backed out my .csproj changes, only to find my solution was still working.

So after all that, I'm wondering if Mohammed's answer (on this page) would have done the trick, had I simply done the git clean first.

RuntimeError: module compiled against API version a but this version of numpy is 9

You may also want to check your $PYTHONPATH. I had changed mine in ~/.bashrc in order to get another package to work.

To check your path:

    echo $PYTHONPATH

To change your path (I use nano but you could edit another way)

    nano ~/.bashrc

Look for the line with export PYTHONPATH ...

After making changes, don't forget to

   source ~/.bashrc

How to convert View Model into JSON object in ASP.NET MVC?

In mvc3 with razor @Html.Raw(Json.Encode(object)) seems to do the trick.

How to enable CORS in flask

If you want to enable CORS for all routes, then just install flask_cors extension (pip3 install -U flask_cors) and wrap app like this: CORS(app).

That is enough to do it (I tested this with a POST request to upload an image, and it worked for me):

from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # This will enable CORS for all routes

Important note: if there is an error in your route, let us say you try to print a variable that does not exist, you will get a CORS error related message which, in fact, has nothing to do with CORS.

How to find lines containing a string in linux

/tmp/myfile

first line text
wanted text
other text

the command

$ grep -n "wanted text" /tmp/myfile | awk -F  ":" '{print $1}'
2

What is the purpose of the "role" attribute in HTML?

Is this role attribute necessary?

Answer: Yes.

  • The role attribute is necessary to support Accessible Rich Internet Applications (WAI-ARIA) to define roles in XML-based languages, when the languages do not define their own role attribute.
  • Although this is the reason the role attribute is published by the Protocols and Formats Working Group, the attribute has more general use cases as well.

It provides you:

  • Accessibility
  • Device adaptation
  • Server-side processing
  • Complex data description,...etc.

Javascript Uncaught Reference error Function is not defined

If you are using Angular.js then functions imbedded into HTML, such as onclick="function()" or onchange="function()". They will not register. You need to make the change events in the javascript. Such as:

$('#exampleBtn').click(function() {
  function();
});

ngOnInit not being called when Injectable class is Instantiated

I had to call a function once my dataService was initialized, instead, I called it inside the constructor, that worked for me.

How to check task status in Celery?

Try:

task.AsyncResult(task.request.id).state

this will provide the Celery Task status. If Celery Task is already is under FAILURE state it will throw an Exception:

raised unexpected: KeyError('exc_type',)

How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()

I am using Chrome version 75.

add the muted property to video tag

<video id="myvid" muted>

then play it using javascript and set muted to false

var myvideo = document.getElementById("myvid");
myvideo.play();
myvideo.muted = false;

edit: need user interaction (at least click anywhere in the page to work)

multiple classes on single element html

It's a good practice if you need them. It's also a good practice is they make sense, so future coders can understand what you're doing.

But generally, no it's not a good practice to attach 10 class names to an object because most likely whatever you're using them for, you could accomplish the same thing with far fewer classes. Probably just 1 or 2.

To qualify that statement, javascript plugins and scripts may append far more classnames to do whatever it is they're going to do. Modernizr for example appends anywhere from 5 - 25 classes to your body tag, and there's a very good reason for it. jQuery UI appends lots of classnames when you use one of the widgets in that library.

How to clear the text of all textBoxes in the form?

And this for clearing all controls in form like textbox, checkbox, radioButton

you can add different types you want..

private void ClearTextBoxes(Control control)
    {
        foreach (Control c in control.Controls)
        {
            if (c is TextBox)
            {
                ((TextBox)c).Clear();
            }

            if (c.HasChildren)
            {
                ClearTextBoxes(c);
            }


            if (c is CheckBox)
            {

                ((CheckBox)c).Checked = false;
            }

            if (c is RadioButton)
            {
                ((RadioButton)c).Checked = false;
            }
        }
    }

Best practices for copying files with Maven

For a simple copy-tasks I can recommend copy-rename-maven-plugin. It's straight forward and simple to use:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>com.coderplus.maven.plugins</groupId>
        <artifactId>copy-rename-maven-plugin</artifactId>
        <version>1.0</version>
        <executions>
          <execution>
            <id>copy-file</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>copy</goal>
            </goals>
            <configuration>
              <sourceFile>src/someDirectory/test.environment.properties</sourceFile>
              <destinationFile>target/someDir/environment.properties</destinationFile>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

If you would like to copy more than one file, replace the <sourceFile>...</destinationFile> part with

<fileSets>
  <fileSet>
    <sourceFile>src/someDirectory/test.environment.properties</sourceFile>
    <destinationFile>target/someDir/environment.properties</destinationFile>
  </fileSet>
  <fileSet>
    <sourceFile>src/someDirectory/test.logback.xml</sourceFile>
    <destinationFile>target/someDir/logback.xml</destinationFile>
  </fileSet>                
</fileSets>

Furthermore you can specify multiple executions in multiple phases if needed, the second goal is "rename", which simply does what it says while the rest of the configuration stays the same. For more usage examples refer to the Usage-Page.

Note: This plugin can only copy files, not directories. (Thanks to @james.garriss for finding this limitation.)

Convert comma separated string of ints to int array

import java.util.*;
import java.io.*;
public class problem
{
public static void main(String args[])enter code here
{
  String line;
  String[] lineVector;
  int n,m,i,j;
  Scanner sc = new Scanner(System.in);
  line = sc.nextLine();
  lineVector = line.split(",");
  //enter the size of the array
  n=Integer.parseInt(lineVector[0]);
  m=Integer.parseInt(lineVector[1]);
  int arr[][]= new int[n][m];
  //enter the array here
  System.out.println("Enter the array:");
  for(i=0;i<n;i++)
  {
  line = sc.nextLine();
  lineVector = line.split(",");
  for(j=0;j<m;j++)
  {
  arr[i][j] = Integer.parseInt(lineVector[j]);
  }
  }
  sc.close();
}
}

On the first line enter the size of the array separated by a comma. Then enter the values in the array separated by a comma.The result is stored in the array arr. e.g input: 2,3 1,2,3 2,4,6 will store values as arr = {{1,2,3},{2,4,6}};

Uncaught TypeError: Cannot read property 'length' of undefined

"ProjectID" JSON data format problem Remove "ProjectID": This value collection objeckt key value

 { * * "ProjectID" * * : {
            "name": "ProjectID",
            "value": "16,36,8,7",
            "group": "Genel",
            "editor": {
                "type": "combobox",
                "options": {
                    "url": "..\/jsonEntityVarServices\/?id=6&task=7",
                    "valueField": "value",
                    "textField": "text",
                    "multiple": "true"
                }
            },
            "id": "14",
            "entityVarID": "16",
            "EVarMemID": "47"
        }
    }

Scrollview vertical and horizontal in android

I use it and works fine:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView android:id="@+id/ScrollView02" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            xmlns:android="http://schemas.android.com/apk/res/android">
<HorizontalScrollView android:id="@+id/HorizontalScrollView01" 
                      android:layout_width="wrap_content" 
                      android:layout_height="wrap_content">
<ImageView android:id="@+id/ImageView01"
           android:src="@drawable/pic" 
           android:isScrollContainer="true" 
           android:layout_height="fill_parent" 
           android:layout_width="fill_parent" 
           android:adjustViewBounds="true">
</ImageView>
</HorizontalScrollView>
</ScrollView>

The source link is here: Android-spa

get unique machine id

There are two ways possible to this that I know:

  1. Get the Processor id of the system:

    public string getCPUId()
    {
        string cpuInfo = string.Empty;
        ManagementClass mc = new ManagementClass("win32_processor");
        ManagementObjectCollection moc = mc.GetInstances();
    
        foreach (ManagementObject mo in moc)
        {
            if (cpuInfo == "")
            {
                //Get only the first CPU's ID
                cpuInfo = mo.Properties["processorID"].Value.ToString();
                break;
            }
        }
        return cpuInfo;
    }
    
  2. Get UUID of the system:

    public string getUUID()
    {
            Process process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            startInfo.FileName = "CMD.exe";
            startInfo.Arguments = "/C wmic csproduct get UUID";
            process.StartInfo = startInfo;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();
            process.WaitForExit();
            string output = process.StandardOutput.ReadToEnd();
            return output;
    }
    

How do I create sql query for searching partial matches?

This may work as well.

SELECT * 
FROM myTable
WHERE CHARINDEX('mall', name) > 0
  OR CHARINDEX('mall', description) > 0

Scale the contents of a div by a percentage?

This cross-browser lib seems safer - just zoom and moz-transform won't cover as many browsers as jquery.transform2d's scale().

http://louisremi.github.io/jquery.transform.js/

For example

$('#div').css({ transform: 'scale(.5)' });

Update

OK - I see people are voting this down without an explanation. The other answer here won't work in old Safari (people running Tiger), and it won't work consistently in some older browsers - that is, it does scale things but it does so in a way that's either very pixellated or shifts the position of the element in a way that doesn't match other browsers.

http://www.browsersupport.net/CSS/zoom

Or just look at this question, which this one is likely just a dupe of:

complete styles for cross browser CSS zoom

OS X cp command in Terminal - No such file or directory

In my case, I had accidentally named a folder 'samples '. I couldn't see the space when I did 'ls -la'.

Eventually I realized this when I tried tabbing to autocomplete and saw 'samples\ /'.

To fix this I ran

mv samples\  samples

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

The SETX command does not modify the current environment.

If you run the following batch file:

setx AAA aaa
echo AAA=%AAA%

It will print

AAA=

So your batch file is wrong. You have to use set:

set AAA=aaa

See What is the difference between SETX and SET in environment variables in Windows.

Multiple "order by" in LINQ

Using non-lambda, query-syntax LINQ, you can do this:

var movies = from row in _db.Movies 
             orderby row.Category, row.Name
             select row;

[EDIT to address comment] To control the sort order, use the keywords ascending (which is the default and therefore not particularly useful) or descending, like so:

var movies = from row in _db.Movies 
             orderby row.Category descending, row.Name
             select row;

Saving and loading objects and using pickle

You can use anycache to do the job for you. Assuming you have a function myfunc which creates the instance:

from anycache import anycache

class Fruits:pass

@anycache(cachedir='/path/to/your/cache')    
def myfunc()
    banana = Fruits()
    banana.color = 'yellow'
    banana.value = 30
return banana

Anycache calls myfunc at the first time and pickles the result to a file in cachedir using an unique identifier (depending on the the function name and the arguments) as filename. On any consecutive run, the pickled object is loaded.

If the cachedir is preserved between python runs, the pickled object is taken from the previous python run.

The function arguments are also taken into account. A refactored implementation works likewise:

from anycache import anycache

class Fruits:pass

@anycache(cachedir='/path/to/your/cache')    
def myfunc(color, value)
    fruit = Fruits()
    fruit.color = color
    fruit.value = value
return fruit

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

You have quite a few options for this:

1 - If you can find an SVG file for the map you want, you can use something like RaphaelJS or SnapSVG to add click listeners for your states/regions, this solution is the most customizable...

2 - You can use dedicated tools such as clickablemapbuilder (free) or makeaclickablemap (i think free also).

[disclaimer] Im the author of clickablemapbuilder.com :)

Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string

We recently ran into a similar issue and was unable to find anything obvious as the cause. There turned out to be a control character in our string but when we outputted that string to the browser that character was not visible unless we copied the text into an IDE.

We managed to solve our problem thanks to this post and this:

preg_replace('/[\x00-\x1F\x7F]/', '', $input);

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

Since your content-type is application/x-www-form-urlencoded you'll need to encode the POST body, especially if it contains characters like & which have special meaning in a form.

Try passing your string through HttpUtility.UrlEncode before writing it to the request stream.

Here are a couple links for reference.

How to style SVG with external CSS?

What works for me: style tag with @import rule

<defs>
    <style type="text/css">
        @import url("svg-common.css");
    </style>
</defs>

Regex date validation for yyyy-mm-dd

You can use this regex to get the yyyy-MM-dd format:

((?:19|20)\\d\\d)-(0?[1-9]|1[012])-([12][0-9]|3[01]|0?[1-9])

You can find example for date validation: How to validate date with regular expression.

Windows error 2 occured while loading the Java VM

Try adding C:\path\to\java\jre\bin to your system environment variable PATH and run again. That worked for me!

SQL Server date format yyyymmdd

try this....

SELECT FORMAT(CAST(DOB AS DATE),'yyyyMMdd') FROM Employees;

Pandas: convert dtype 'object' to int

Follow these steps:

1.clean your file -> open your datafile in csv format and see that there is "?" in place of empty places and delete all of them.

2.drop the rows containing missing values e.g.:

df.dropna(subset=["normalized-losses"], axis = 0 , inplace= True)

3.use astype now for conversion

df["normalized-losses"]=df["normalized-losses"].astype(int)

Note: If still finding erros in your program then again inspect your csv file, open it in excel to find whether is there an "?" in your required column, then delete it and save file and go back and run your program.

comment success! if it works. :)

List(of String) or Array or ArrayList

Neither collection will let you add items that way.

You can make an extension to make for examle List(Of String) have an Add method that can do that:

Imports System.Runtime.CompilerServices
Module StringExtensions

  <Extension()>
  Public Sub Add(ByVal list As List(Of String), ParamArray values As String())
    For Each s As String In values
      list.Add(s)
    Next
  End Sub

End Module

Now you can add multiple value in one call:

Dim lstOfStrings as New List(Of String)
lstOfStrings.Add(String1, String2, String3, String4)

Unable to open debugger port in IntelliJ IDEA

For me, IntelliJ Event Log (right bottom corner) had below logs:

Error running EntitmentTooling-Debug: Cannot run program "/path-to/apache-tomcat-8.5.15/bin/catalina.sh" (in directory "path-to/apache-tomcat-8.5.15/bin"): error=13, Permission denied

Error running EntitmentTooling-Debug: Unable to open debugger port (127.0.0.1:58804): java.net.SocketException "Socket closed"

The command

$ chmod a+x /path-to/apache-tomcat-8.5.15/bin/catalina.sh

to sufficiently change privileges worked for me.

How to make a copy of an object in C#

You can use MemberwiseClone

obj myobj2 = (obj)myobj.MemberwiseClone();

The copy is a shallow copy which means the reference properties in the clone are pointing to the same values as the original object but that shouldn't be an issue in your case as the properties in obj are of value types.

If you own the source code, you can also implement ICloneable

Difference between HashSet and HashMap?

A HashMap is to add, get, remove, ... objects indexed by a custom key of any type.
A HashSet is to add elements, remove elements and check if elements are present by comparing their hashes.

So a HashMap contains the elements and a HashSet remembers their hashes.

React proptype array with shape

There's a ES6 shorthand import, you can reference. More readable and easy to type.

import React, { Component } from 'react';
import { arrayOf, shape, number } from 'prop-types';

class ExampleComponent extends Component {
  static propTypes = {
    annotationRanges: arrayOf(shape({
      start: number,
      end: number,
    })).isRequired,
  }

  static defaultProps = {
     annotationRanges: [],
  }
}

Loop through all the files with a specific extension

as @chepner says in his comment you are comparing $i to a fixed string.

To expand and rectify the situation you should use [[ ]] with the regex operator =~

eg:

for i in $(ls);do
    if [[ $i =~ .*\.java$ ]];then
        echo "I want to do something with the file $i"
    fi
done

the regex to the right of =~ is tested against the value of the left hand operator and should not be quoted, ( quoted will not error but will compare against a fixed string and so will most likely fail"

but @chepner 's answer above using glob is a much more efficient mechanism.

Restart pods when configmap updates in Kubernetes?

Had this problem where the Deployment was in a sub-chart and the values controlling it were in the parent chart's values file. This is what we used to trigger restart:

spec:
  template:
    metadata:
      annotations:
        checksum/config: {{ tpl (toYaml .Values) . | sha256sum }}

Obviously this will trigger restart on any value change but it works for our situation. What was originally in the child chart would only work if the config.yaml in the child chart itself changed:

    checksum/config: {{ include (print $.Template.BasePath "/config.yaml") . | sha256sum }}

Access files stored on Amazon S3 through web browser

You can use a bucket policy to give anonymous users full read access to your objects. Depending on whether you need them to LIST or just perform a GET, you'll want to tweak this. (I.e. permissions for listing the contents of a bucket have the action set to "s3:ListBucket").

http://docs.aws.amazon.com/AmazonS3/latest/dev/AccessPolicyLanguage_UseCases_s3_a.html

Your policy will look something like the following. You can use the S3 console at http://aws.amazon.com/console to upload it.

 {
  "Version":"2008-10-17",
  "Statement":[{
    "Sid":"AddPerm",
      "Effect":"Allow",
      "Principal": {
            "AWS": "*"
         },
      "Action":["s3:GetObject"],
      "Resource":["arn:aws:s3:::bucket/*"
      ]
    }
  ]
}

If you're truly opening up your objects to the world, you'll want to look into setting up CloudWatch rules on your billing so you can shut off permissions to your objects if they become too popular.

Set value for particular cell in pandas DataFrame with iloc

Another way is to get the row index and then use df.loc or df.at.

# get row index 'label' from row number 'irow'
label = df.index.values[irow] 
df.at[label, 'COL_NAME'] = x

Prevent form submission on Enter key press

A react js solution

 handleChange: function(e) {
    if (e.key == 'Enter') {
      console.log('test');
    }


 <div>
    <Input type="text"
       ref = "input"
       placeholder="hiya"
       onKeyPress={this.handleChange}
    />
 </div>

scroll image with continuous scrolling using marquee tag

Marquee (<marquee>) is a deprecated and not a valid HTML tag. You can use many jQuery plugins to do. One of it, is jQuery News Ticker. There are many more!

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

PostgreSQL function for last inserted ID

You can use RETURNING id after insert query.

INSERT INTO distributors (id, name) VALUES (DEFAULT, 'ALI') RETURNING id;

and result:

 id 
----
  1

In the above example id is auto-increment filed.

MySQL Removing Some Foreign keys

The foreign keys are there to ensure data integrity, so you can't drop a column as long as it's part of a foreign key. You need to drop the key first.

I would think the following query would do it:

ALTER TABLE assignmentStuff DROP FOREIGN KEY assignmentIDX;

Double free or corruption after queue::push

The problem is that your class contains a managed RAW pointer but does not implement the rule of three (five in C++11). As a result you are getting (expectedly) a double delete because of copying.

If you are learning you should learn how to implement the rule of three (five). But that is not the correct solution to this problem. You should be using standard container objects rather than try to manage your own internal container. The exact container will depend on what you are trying to do but std::vector is a good default (and you can change afterwords if it is not opimal).

#include <queue>
#include <vector>

class Test{
    std::vector<int> myArray;

    public:
    Test(): myArray(10){
    }    
};

int main(){
    queue<Test> q
    Test t;
    q.push(t);
}

The reason you should use a standard container is the separation of concerns. Your class should be concerned with either business logic or resource management (not both). Assuming Test is some class you are using to maintain some state about your program then it is business logic and it should not be doing resource management. If on the other hand Test is supposed to manage an array then you probably need to learn more about what is available inside the standard library.

How to trace the path in a Breadth-First Search?

Very easy code. You keep appending the path each time you discover a node.

graph = {
         'A': set(['B', 'C']),
         'B': set(['A', 'D', 'E']),
         'C': set(['A', 'F']),
         'D': set(['B']),
         'E': set(['B', 'F']),
         'F': set(['C', 'E'])
         }
def retunShortestPath(graph, start, end):

    queue = [(start,[start])]
    visited = set()

    while queue:
        vertex, path = queue.pop(0)
        visited.add(vertex)
        for node in graph[vertex]:
            if node == end:
                return path + [end]
            else:
                if node not in visited:
                    visited.add(node)
                    queue.append((node, path + [node]))

How add unique key to existing table (with non uniques rows)

Either create an auto-increment id or a UNIQUE id and add it to the natural key you are talking about with the 4 fields. this will make every row in the table unique...

Oracle 11g Express Edition for Windows 64bit?

This is a very useful question. It has 5 different helpful answers that say quite different but complementary things (surprising, eh?). This answer combines those answers into a more useful form as well as adding two more solutions.

There is no Oracle Express Edition for 64 bit Windows. See this official [but unanswered] forum thread. Therefore, these are the classes of solutions:

  • Pay. The paid versions of Oracle (Standard/Enterprise) support 64-bit Windows.
  • Hack. Many people have successfully installed the 32 bit Oracle XE software on 64 bit Windows. This blog post seems to be the one most often cited as helpful. This is unsupported, of course, and session trace is known to fail. But for many folks this is a good solution.
  • VM. If your goal is simply to run Oracle on a 64 bit Windows machine, then running Oracle in a Virtual Machine may be a good solution. VirtualBox is a natural choice because it's free and Oracle provides pre-configured VMs with Oracle DB installed. VMWare or other virtualization systems work equally well.
  • Develop only. Many users want Oracle XE just to learn Oracle or to test an application with Oracle. If that's your requirement, then Oracle Enterprise Edition (including support for 64-bit Windows) is free "only for the purpose of developing, testing, prototyping and demonstrating your application".

Accessing dict keys like an attribute?

Here's a short example of immutable records using built-in collections.namedtuple:

def record(name, d):
    return namedtuple(name, d.keys())(**d)

and a usage example:

rec = record('Model', {
    'train_op': train_op,
    'loss': loss,
})

print rec.loss(..)

Recommended way to insert elements into map

  1. insert is not a recommended way - it is one of the ways to insert into map. The difference with operator[] is that the insert can tell whether the element is inserted into the map. Also, if your class has no default constructor, you are forced to use insert.
  2. operator[] needs the default constructor because the map checks if the element exists. If it doesn't then it creates one using default constructor and returns a reference (or const reference to it).

Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.

Check if a string is a valid date using DateTime.TryParse

Basically, I want to check if a particular string contains AT LEAST day(1 through 31 or 01 through 31),month(1 through 12 or 01 through 12) and year(yyyy or yy) in any order, with any date separator , what will be the solution? So, if the value includes any parts of time, it should return true too. I could NOT be able to define a array of format.

When I was in a similar situation, here is what I did:

  1. Gather all the formats my system is expected to support.
  2. Looked at what is common or can be generalize.
  3. Learned to create REGEX (It is an investment of time initially but pays off once you create one or two on your own). Also do not try to build REGEX for all formats in one go, follow incremental process.
  4. I created REGEX to cover as many format as possible.
  5. For few cases, not to make REGEX extra complex, I covered it through DateTime.Parse() method.
  6. With the combination of both Parse as well as REGEX i was able to validate the input is correct/as expected.

This http://www.codeproject.com/Articles/13255/Validation-with-Regular-Expressions-Made-Simple was really helpful both for understanding as well as validation the syntax for each format.

My 2 cents if it helps....

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

I have used in my many projects and never got any single issue :)

for your reference, Code are in snippet

_x000D_
_x000D_
* {_x000D_
 margin: 0;_x000D_
}_x000D_
html, body {_x000D_
 height: 100%;_x000D_
}_x000D_
.wrapper {_x000D_
 min-height: 100%;_x000D_
 height: auto !important; /* This line and the next line are not necessary unless you need IE6 support */_x000D_
 height: 100%;_x000D_
 margin: 0 auto -50px; /* the bottom margin is the negative value of the footer's height */_x000D_
  background:green;_x000D_
}_x000D_
.footer, .push {_x000D_
 height: 50px; /* .push must be the same height as .footer */_x000D_
}_x000D_
_x000D_
.footer{_x000D_
  background:gold;_x000D_
  }
_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Untitled Document</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class="wrapper">_x000D_
    Content Area_x000D_
    </div>_x000D_
  _x000D_
  <div class="push">_x000D_
    </div>_x000D_
  _x000D_
  <div class="footer">_x000D_
    Footer Area_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Android, How can I Convert String to Date?

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date d = dateFormat.parse(datestring)

How to make an embedded Youtube video automatically start playing?

Add &autoplay=1 to your syntax, like this

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI&amp;autoplay=1" frameborder="0" allowfullscreen></iframe>

How to start a Process as administrator mode in C#

This works when I try it. I double-checked with two sample programs:

using System;
using System.Diagnostics;

namespace ConsoleApplication1 {
  class Program {
    static void Main(string[] args) {
      Process.Start("ConsoleApplication2.exe");
    }
  }
}

using System;
using System.IO;

namespace ConsoleApplication2 {
  class Program {
    static void Main(string[] args) {
      try {
        File.WriteAllText(@"c:\program files\test.txt", "hello world");
      }
      catch (Exception ex) {
        Console.WriteLine(ex.ToString());
        Console.ReadLine();
      }
    }
  }
}

First verified that I get the UAC bomb:

System.UnauthorizedAccessException: Access to the path 'c:\program files\test.txt' is denied.
// etc..

Then added a manifest to ConsoleApplication1 with the phrase:

    <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

No bomb. And a file I can't easily delete :) This is consistent with several previous tests on various machines running Vista and Win7. The started program inherits the security token from the starter program. If the starter has acquired admin privileges, the started program has them as well.

HTML/CSS font color vs span style

1st preference external style sheet.

<span class="myClass">test</span>

css

.myClass
{
color:red;
}

2nd preference inline style

<span style="color:red">test</span>

<font> as mentioned is deprecated.

How to programmatically send SMS on the iPhone?

Follow this procedures

1 .Add MessageUI.Framework to projectenter image description here

2 . Import #import <MessageUI/MessageUI.h> in .h file.

3 . Copy this code for sending message

 if ([MFMessageComposeViewController canSendText]) {
    MFMessageComposeViewController *messageComposer =
    [[MFMessageComposeViewController alloc] init];
    NSString *message = @"Message!!!";
    [messageComposer setBody:message];
    messageComposer.messageComposeDelegate = self;
    [self presentViewController:messageComposer animated:YES completion:nil];
}

4 . Implement delegate method if you want to.

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result{


   ///your stuff here 

    [self dismissViewControllerAnimated:YES completion:nil];
}

Run And GO!

String "true" and "false" to boolean

You can use wannabe_bool gem. https://github.com/prodis/wannabe_bool

This gem implements a #to_b method for String, Integer, Symbol and NilClass classes.

params[:internal].to_b

Select first 10 distinct rows in mysql

SELECT * 
FROM people 
WHERE names ='SMITH'
ORDER BY names asc
limit 10

If you need add group by clause. If you search Smith you would have to sort on something else.

SQL Server: how to select records with specific date from datetime column

For Perfect DateTime Match in SQL Server

SELECT ID FROM [Table Name] WHERE (DateLog between '2017-02-16 **00:00:00.000**' and '2017-12-16 **23:59:00.999**') ORDER BY DateLog DESC

How to add calendar events in Android?

Just in case if someone needs this for Xamarin in c#:

        Intent intent = new Intent(Intent.ActionInsert);
        intent.SetData(Android.Provider.CalendarContract.Events.ContentUri);
        intent.PutExtra(Android.Provider.CalendarContract.ExtraEventBeginTime, Utils.Tools.CurrentTimeMillis(game.Date));
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.AllDay, false);
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.EventLocation, "Location");
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.Description, "Description");
        intent.PutExtra(Android.Provider.CalendarContract.ExtraEventEndTime, Utils.Tools.CurrentTimeMillis(game.Date.AddHours(2)));
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.Title, "Title");
        StartActivity(intent);

Helper Functions:

    private static readonly DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    public static long CurrentTimeMillis(DateTime date)
    {
        return (long)(date.ToUniversalTime() - Jan1st1970).TotalMilliseconds;
    }

Vagrant ssh authentication failure

Between all of the responses here, there are lots of good things to try. For completeness, if you

ssh vagrant@localhost -p 2222

as @Bizmate suggests, and it fails, be sure you have

AllowUsers vagrant

in the /etc/ssh/sshd_config of your guest/vagrant machine.

Styling mat-select in Angular Material

Working solution is by using in-build: panelClass attribute and set styles in global style.css (with !important):

https://material.angular.io/components/select/api

_x000D_
_x000D_
/* style.css */
.matRole .mat-option-text {
  height: 4em !important;
}
_x000D_
<mat-select panelClass="matRole">...
_x000D_
_x000D_
_x000D_

Why do we need middleware for async flow in Redux?

You don't.

But... you should use redux-saga :)

Dan Abramov's answer is right about redux-thunk but I will talk a bit more about redux-saga that is quite similar but more powerful.

Imperative VS declarative

  • DOM: jQuery is imperative / React is declarative
  • Monads: IO is imperative / Free is declarative
  • Redux effects: redux-thunk is imperative / redux-saga is declarative

When you have a thunk in your hands, like an IO monad or a promise, you can't easily know what it will do once you execute. The only way to test a thunk is to execute it, and mock the dispatcher (or the whole outside world if it interacts with more stuff...).

If you are using mocks, then you are not doing functional programming.

Seen through the lens of side-effects, mocks are a flag that your code is impure, and in the functional programmer's eye, proof that something is wrong. Instead of downloading a library to help us check the iceberg is intact, we should be sailing around it. A hardcore TDD/Java guy once asked me how you do mocking in Clojure. The answer is, we usually don't. We usually see it as a sign we need to refactor our code.

Source

The sagas (as they got implemented in redux-saga) are declarative and like the Free monad or React components, they are much easier to test without any mock.

See also this article:

in modern FP, we shouldn’t write programs — we should write descriptions of programs, which we can then introspect, transform, and interpret at will.

(Actually, Redux-saga is like a hybrid: the flow is imperative but the effects are declarative)

Confusion: actions/events/commands...

There is a lot of confusion in the frontend world on how some backend concepts like CQRS / EventSourcing and Flux / Redux may be related, mostly because in Flux we use the term "action" which can sometimes represent both imperative code (LOAD_USER) and events (USER_LOADED). I believe that like event-sourcing, you should only dispatch events.

Using sagas in practice

Imagine an app with a link to a user profile. The idiomatic way to handle this with each middleware would be:

redux-thunk

<div onClick={e => dispatch(actions.loadUserProfile(123)}>Robert</div>

function loadUserProfile(userId) {
  return dispatch => fetch(`http://data.com/${userId}`)
    .then(res => res.json())
    .then(
      data => dispatch({ type: 'USER_PROFILE_LOADED', data }),
      err => dispatch({ type: 'USER_PROFILE_LOAD_FAILED', err })
    );
}

redux-saga

<div onClick={e => dispatch({ type: 'USER_NAME_CLICKED', payload: 123 })}>Robert</div>


function* loadUserProfileOnNameClick() {
  yield* takeLatest("USER_NAME_CLICKED", fetchUser);
}

function* fetchUser(action) {
  try {
    const userProfile = yield fetch(`http://data.com/${action.payload.userId }`)
    yield put({ type: 'USER_PROFILE_LOADED', userProfile })
  } 
  catch(err) {
    yield put({ type: 'USER_PROFILE_LOAD_FAILED', err })
  }
}

This saga translates to:

every time a username gets clicked, fetch the user profile and then dispatch an event with the loaded profile.

As you can see, there are some advantages of redux-saga.

The usage of takeLatest permits to express that you are only interested to get the data of the last username clicked (handle concurrency problems in case the user click very fast on a lot of usernames). This kind of stuff is hard with thunks. You could have used takeEvery if you don't want this behavior.

You keep action creators pure. Note it's still useful to keep actionCreators (in sagas put and components dispatch), as it might help you to add action validation (assertions/flow/typescript) in the future.

Your code becomes much more testable as the effects are declarative

You don't need anymore to trigger rpc-like calls like actions.loadUser(). Your UI just needs to dispatch what HAS HAPPENED. We only fire events (always in the past tense!) and not actions anymore. This means that you can create decoupled "ducks" or Bounded Contexts and that the saga can act as the coupling point between these modular components.

This means that your views are more easy to manage because they don't need anymore to contain that translation layer between what has happened and what should happen as an effect

For example imagine an infinite scroll view. CONTAINER_SCROLLED can lead to NEXT_PAGE_LOADED, but is it really the responsibility of the scrollable container to decide whether or not we should load another page? Then he has to be aware of more complicated stuff like whether or not the last page was loaded successfully or if there is already a page that tries to load, or if there is no more items left to load? I don't think so: for maximum reusability the scrollable container should just describe that it has been scrolled. The loading of a page is a "business effect" of that scroll

Some might argue that generators can inherently hide state outside of redux store with local variables, but if you start to orchestrate complex things inside thunks by starting timers etc you would have the same problem anyway. And there's a select effect that now permits to get some state from your Redux store.

Sagas can be time-traveled and also enables complex flow logging and dev-tools that are currently being worked on. Here is some simple async flow logging that is already implemented:

saga flow logging

Decoupling

Sagas are not only replacing redux thunks. They come from backend / distributed systems / event-sourcing.

It is a very common misconception that sagas are just here to replace your redux thunks with better testability. Actually this is just an implementation detail of redux-saga. Using declarative effects is better than thunks for testability, but the saga pattern can be implemented on top of imperative or declarative code.

In the first place, the saga is a piece of software that permits to coordinate long running transactions (eventual consistency), and transactions across different bounded contexts (domain driven design jargon).

To simplify this for frontend world, imagine there is widget1 and widget2. When some button on widget1 is clicked, then it should have an effect on widget2. Instead of coupling the 2 widgets together (ie widget1 dispatch an action that targets widget2), widget1 only dispatch that its button was clicked. Then the saga listen for this button click and then update widget2 by dispaching a new event that widget2 is aware of.

This adds a level of indirection that is unnecessary for simple apps, but make it more easy to scale complex applications. You can now publish widget1 and widget2 to different npm repositories so that they never have to know about each others, without having them to share a global registry of actions. The 2 widgets are now bounded contexts that can live separately. They do not need each others to be consistent and can be reused in other apps as well. The saga is the coupling point between the two widgets that coordinate them in a meaningful way for your business.

Some nice articles on how to structure your Redux app, on which you can use Redux-saga for decoupling reasons:

A concrete usecase: notification system

I want my components to be able to trigger the display of in-app notifications. But I don't want my components to be highly coupled to the notification system that has its own business rules (max 3 notifications displayed at the same time, notification queueing, 4 seconds display-time etc...).

I don't want my JSX components to decide when a notification will show/hide. I just give it the ability to request a notification, and leave the complex rules inside the saga. This kind of stuff is quite hard to implement with thunks or promises.

notifications

I've described here how this can be done with saga

Why is it called a Saga?

The term saga comes from the backend world. I initially introduced Yassine (the author of Redux-saga) to that term in a long discussion.

Initially, that term was introduced with a paper, the saga pattern was supposed to be used to handle eventual consistency in distributed transactions, but its usage has been extended to a broader definition by backend developers so that it now also covers the "process manager" pattern (somehow the original saga pattern is a specialized form of process manager).

Today, the term "saga" is confusing as it can describe 2 different things. As it is used in redux-saga, it does not describe a way to handle distributed transactions but rather a way to coordinate actions in your app. redux-saga could also have been called redux-process-manager.

See also:

Alternatives

If you don't like the idea of using generators but you are interested by the saga pattern and its decoupling properties, you can also achieve the same with redux-observable which uses the name epic to describe the exact same pattern, but with RxJS. If you're already familiar with Rx, you'll feel right at home.

const loadUserProfileOnNameClickEpic = action$ =>
  action$.ofType('USER_NAME_CLICKED')
    .switchMap(action =>
      Observable.ajax(`http://data.com/${action.payload.userId}`)
        .map(userProfile => ({
          type: 'USER_PROFILE_LOADED',
          userProfile
        }))
        .catch(err => Observable.of({
          type: 'USER_PROFILE_LOAD_FAILED',
          err
        }))
    );

Some redux-saga useful resources

2017 advises

  • Don't overuse Redux-saga just for the sake of using it. Testable API calls only are not worth it.
  • Don't remove thunks from your project for most simple cases.
  • Don't hesitate to dispatch thunks in yield put(someActionThunk) if it makes sense.

If you are frightened of using Redux-saga (or Redux-observable) but just need the decoupling pattern, check redux-dispatch-subscribe: it permits to listen to dispatches and trigger new dispatches in listener.

const unsubscribe = store.addDispatchListener(action => {
  if (action.type === 'ping') {
    store.dispatch({ type: 'pong' });
  }
});

Cannot declare instance members in a static class in C#

As John Weldon said all members must be static in a static class. Try

public static class employee
{
     static NameValueCollection appSetting = ConfigurationManager.AppSettings;    

}

How to select an element with 2 classes

You can chain class selectors without a space between them:

.a.b {
     color: #666;
}

Note that, if it matters to you, IE6 treats .a.b as .b, so in that browser both div.a.b and div.b will have gray text. See this answer for a comparison between proper browsers and IE6.

Find records with a date field in the last 24 hours

To get records from the last 24 hours:

SELECT * from [table_name] WHERE date > (NOW() - INTERVAL 24 HOUR)

Why can't I push to this bare repository?

I use SourceTree git client, and I see that their initial commit/push command is:

git -c diff.mnemonicprefix=false -c core.quotepath=false push -v --tags --set-upstream origin master:master

How to increase Bootstrap Modal Width?

In my case,

  1. Giving a static width to the modal hurts the responsiveness.
  2. The modal-lg class was not wide enough.

so the solution was

@media (min-width: 1200px) {
   .modal-xlg {
      width: 90%; 
   }
}

and use the above class instead of modal-lg class

Notepad++ cached files location

I lost somehow my temporary notepad++ files, they weren't showing in tabs. So I did some search in appdata folder, and I found all my temporary files there. It seems that they are stored there for a long time.

C:\Users\USER\AppData\Roaming\Notepad++\backup

or

%AppData%\Notepad++\backup

Rails: Get Client IP address

I found request.env['HTTP_X_FORWARDED_FOR'] very useful too in cases when request.remote_ip returns 127.0.0.1

Vertical line using XML drawable

Instead of a shape, you could try a View:

<View
    android:layout_width="1dp"
    android:layout_height="match_parent"
    android:background="#FF0000FF" />

I have only used this for horizontal lines, but I would think it would work for vertical lines as well.

Use:

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="#FF0000FF" />

for a horizontal line.

Selecting distinct values from a JSON

Underscore.js is great for this kind of thing. You can use _.countBy() to get the counts per name:

data = [{"id":11,"name":"ajax","subject":"OR","mark":63},
        {"id":12,"name":"javascript","subject":"OR","mark":63},
        {"id":13,"name":"jquery","subject":"OR","mark":63},
        {"id":14,"name":"ajax","subject":"OR","mark":63},
        {"id":15,"name":"jquery","subject":"OR","mark":63},
        {"id":16,"name":"ajax","subject":"OR","mark":63},
        {"id":20,"name":"ajax","subject":"OR","mark":63}]

_.countBy(data, function(data) { return data.name; });

Gives:

{ajax: 4, javascript: 1, jquery: 2} 

For an array of the keys just use _.keys()

_.keys(_.countBy(data, function(data) { return data.name; }));

Gives:

["ajax", "javascript", "jquery"]

How do files get into the External Dependencies in Visual Studio C++?

The External Dependencies folder is populated by IntelliSense: the contents of the folder do not affect the build at all (you can in fact disable the folder in the UI).

You need to actually include the header (using a #include directive) to use it. Depending on what that header is, you may also need to add its containing folder to the "Additional Include Directories" property and you may need to add additional libraries and library folders to the linker options; you can set all of these in the project properties (right click the project, select Properties). You should compare the properties with those of the project that does build to determine what you need to add.

Squash my last X commits together using Git

If you are on a remote branch(called feature-branch) cloned from a Golden Repository(golden_repo_name), then here's the technique to squash your commits into one:

  1. Checkout the golden repo

    git checkout golden_repo_name
    
  2. Create a new branch from it(golden repo) as follows

    git checkout -b dev-branch
    
  3. Squash merge with your local branch that you have already

    git merge --squash feature-branch
    
  4. Commit your changes (this will be the only commit that goes in dev-branch)

    git commit -m "My feature complete"
    
  5. Push the branch to your local repository

    git push origin dev-branch
    

Why do I always get the same sequence of random numbers with rand()?

Rand does not get you a random number. It gives you the next number in a sequence generated by a pseudorandom number generator. To get a different sequence every time you start your program, you have to seed the algorithm by calling srand.

A (very bad) way to do it is by passing it the current time:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    srand(time(NULL));
    int i, j = 0;
    for(i = 0; i <= 10; i++) {
        j = rand();
        printf("j = %d\n", j);
    }
    return 0;
}

Why this is a bad way? Because a pseudorandom number generator is as good as its seed, and the seed must be unpredictable. That is why you may need a better source of entropy, like reading from /dev/urandom.

When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

After wrestling with this problem today my opinion is this: BEGIN...END brackets code just like {....} does in C languages, e.g. code blocks for if...else and loops

GO is (must be) used when succeeding statements rely on an object defined by a previous statement. USE database is a good example above, but the following will also bite you:

alter table foo add bar varchar(8);
-- if you don't put GO here then the following line will error as it doesn't know what bar is.
update foo set bar = 'bacon';
-- need a GO here to tell the interpreter to execute this statement, otherwise the Parser will lump it together with all successive statements.

It seems to me the problem is this: the SQL Server SQL Parser, unlike the Oracle one, is unable to realise that you're defining a new symbol on the first line and that it's ok to reference in the following lines. It doesn't "see" the symbol until it encounters a GO token which tells it to execute the preceding SQL since the last GO, at which point the symbol is applied to the database and becomes visible to the parser.

Why it doesn't just treat the semi-colon as a semantic break and apply statements individually I don't know and wish it would. Only bonus I can see is that you can put a print() statement just before the GO and if any of the statements fail the print won't execute. Lot of trouble for a minor gain though.

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

Sounds like you're calling sp_executesql with a VARCHAR statement, when it needs to be NVARCHAR.

e.g. This will give the error because @SQL needs to be NVARCHAR

DECLARE @SQL VARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

So:

DECLARE @SQL NVARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

Re-ordering columns in pandas dataframe based on column name

print df.sort_index(by='Frequency',ascending=False)

where by is the name of the column,if you want to sort the dataset based on column

How do I implement onchange of <input type="text"> with jQuery?

You can use .change()

$('input[name=myInput]').change(function() { ... });

However, this event will only fire when the selector has lost focus, so you will need to click somewhere else to have this work.

If that's not quite right for you, you could use some of the other jQuery events like keyup, keydown or keypress - depending on the exact effect you want.

How to set ObjectId as a data type in mongoose

I was looking for a different answer for the question title, so maybe other people will be too.

To set type as an ObjectId (so you may reference author as the author of book, for example), you may do like:

const Book = mongoose.model('Book', {
  author: {
    type: mongoose.Schema.Types.ObjectId, // here you set the author ID
                                          // from the Author colection, 
                                          // so you can reference it
    required: true
  },
  title: {
    type: String,
    required: true
  }
});

How to enable file upload on React's Material UI simple input?

Just the same as what should be but change the button component to be label like so

<form id='uploadForm'
      action='http://localhost:8000/upload'
      method='post'
      encType="multipart/form-data">
    <input type="file" id="sampleFile" style="display: none;" />
    <Button htmlFor="sampleFile" component="label" type={'submit'}>Upload</Button> 
</form>

JavaScript: get code to run every minute

Using setInterval:

setInterval(function() {
    // your code goes here...
}, 60 * 1000); // 60 * 1000 milsec

The function returns an id you can clear your interval with clearInterval:

var timerID = setInterval(function() {
    // your code goes here...
}, 60 * 1000); 

clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.

A "sister" function is setTimeout/clearTimeout look them up.


If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:

function fn60sec() {
    // runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);

How to right-align form input boxes?

Use some tag, to aligning the input element. So

<form>
   <div>
     <input>
     <br />
     <input>
    </div>
</form>

    .mydiv
     {
        width: 500px;
        height: 250px;
        display: table;
        text-align: right;
     }

How to create a shared library with cmake?

I'm trying to learn how to do this myself, and it seems you can install the library like this:

cmake_minimum_required(VERSION 2.4.0)

project(mycustomlib)

# Find source files
file(GLOB SOURCES src/*.cpp)

# Include header files
include_directories(include)

# Create shared library
add_library(${PROJECT_NAME} SHARED ${SOURCES})

# Install library
install(TARGETS ${PROJECT_NAME} DESTINATION lib/${PROJECT_NAME})

# Install library headers
file(GLOB HEADERS include/*.h)
install(FILES ${HEADERS} DESTINATION include/${PROJECT_NAME})

How to import existing Git repository into another?

This function will clone remote repo into local repo dir, after merging all commits will be saved, git log will be show the original commits and proper paths:

function git-add-repo
{
    repo="$1"
    dir="$(echo "$2" | sed 's/\/$//')"
    path="$(pwd)"

    tmp="$(mktemp -d)"
    remote="$(echo "$tmp" | sed 's/\///g'| sed 's/\./_/g')"

    git clone "$repo" "$tmp"
    cd "$tmp"

    git filter-branch --index-filter '
        git ls-files -s |
        sed "s,\t,&'"$dir"'/," |
        GIT_INDEX_FILE="$GIT_INDEX_FILE.new" git update-index --index-info &&
        mv "$GIT_INDEX_FILE.new" "$GIT_INDEX_FILE"
    ' HEAD

    cd "$path"
    git remote add -f "$remote" "file://$tmp/.git"
    git pull "$remote/master"
    git merge --allow-unrelated-histories -m "Merge repo $repo into master" --edit "$remote/master"
    git remote remove "$remote"
    rm -rf "$tmp"
}

How to use:

cd current/package
git-add-repo https://github.com/example/example dir/to/save

If make a little changes you can even move files/dirs of merged repo into different paths, for example:

repo="https://github.com/example/example"
path="$(pwd)"

tmp="$(mktemp -d)"
remote="$(echo "$tmp" | sed 's/\///g' | sed 's/\./_/g')"

git clone "$repo" "$tmp"
cd "$tmp"

GIT_ADD_STORED=""

function git-mv-store
{
    from="$(echo "$1" | sed 's/\./\\./')"
    to="$(echo "$2" | sed 's/\./\\./')"

    GIT_ADD_STORED+='s,\t'"$from"',\t'"$to"',;'
}

# NOTICE! This paths used for example! Use yours instead!
git-mv-store 'public/index.php' 'public/admin.php'
git-mv-store 'public/data' 'public/x/_data'
git-mv-store 'public/.htaccess' '.htaccess'
git-mv-store 'core/config' 'config/config'
git-mv-store 'core/defines.php' 'defines/defines.php'
git-mv-store 'README.md' 'doc/README.md'
git-mv-store '.gitignore' 'unneeded/.gitignore'

git filter-branch --index-filter '
    git ls-files -s |
    sed "'"$GIT_ADD_STORED"'" |
    GIT_INDEX_FILE="$GIT_INDEX_FILE.new" git update-index --index-info &&
    mv "$GIT_INDEX_FILE.new" "$GIT_INDEX_FILE"
' HEAD

GIT_ADD_STORED=""

cd "$path"
git remote add -f "$remote" "file://$tmp/.git"
git pull "$remote/master"
git merge --allow-unrelated-histories -m "Merge repo $repo into master" --edit "$remote/master"
git remote remove "$remote"
rm -rf "$tmp"

Notices
Paths replaces via sed, so make sure it moved in proper paths after merging.
The --allow-unrelated-histories parameter only exists since git >= 2.9.

How to check if an object is a certain type

Some more details in relation with the response from Cody Gray. As it took me some time to digest it I though it might be usefull to others.

First, some definitions:

  1. There are TypeNames, which are string representations of the type of an object, interface, etc. For example, Bar is a TypeName in Public Class Bar, or in Dim Foo as Bar. TypeNames could be seen as "labels" used in the code to tell the compiler which type definition to look for in a dictionary where all available types would be described.
  2. There are System.Type objects which contain a value. This value indicates a type; just like a String would take some text or an Int would take a number, except we are storing types instead of text or numbers. Type objects contain the type definitions, as well as its corresponding TypeName.

Second, the theory:

  1. Foo.GetType() returns a Type object which contains the type for the variable Foo. In other words, it tells you what Foo is an instance of.
  2. GetType(Bar) returns a Type object which contains the type for the TypeName Bar.
  3. In some instances, the type an object has been Cast to is different from the type an object was first instantiated from. In the following example, MyObj is an Integer cast into an Object:

    Dim MyVal As Integer = 42 Dim MyObj As Object = CType(MyVal, Object)

So, is MyObj of type Object or of type Integer? MyObj.GetType() will tell you it is an Integer.

  1. But here comes the Type Of Foo Is Bar feature, which allows you to ascertain a variable Foo is compatible with a TypeName Bar. Type Of MyObj Is Integer and Type Of MyObj Is Object will both return True. For most cases, TypeOf will indicate a variable is compatible with a TypeName if the variable is of that Type or a Type that derives from it. More info here: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/typeof-operator#remarks

The test below illustrate quite well the behaviour and usage of each of the mentionned keywords and properties.

Public Sub TestMethod1()

    Dim MyValInt As Integer = 42
    Dim MyValDble As Double = CType(MyValInt, Double)
    Dim MyObj As Object = CType(MyValDble, Object)

    Debug.Print(MyValInt.GetType.ToString) 'Returns System.Int32
    Debug.Print(MyValDble.GetType.ToString) 'Returns System.Double
    Debug.Print(MyObj.GetType.ToString) 'Returns System.Double

    Debug.Print(MyValInt.GetType.GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(MyValDble.GetType.GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(MyObj.GetType.GetType.ToString) 'Returns System.RuntimeType

    Debug.Print(GetType(Integer).GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(GetType(Double).GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(GetType(Object).GetType.ToString) 'Returns System.RuntimeType

    Debug.Print(MyValInt.GetType = GetType(Integer)) '# Returns True
    Debug.Print(MyValInt.GetType = GetType(Double)) 'Returns False
    Debug.Print(MyValInt.GetType = GetType(Object)) 'Returns False

    Debug.Print(MyValDble.GetType = GetType(Integer)) 'Returns False
    Debug.Print(MyValDble.GetType = GetType(Double)) '# Returns True
    Debug.Print(MyValDble.GetType = GetType(Object)) 'Returns False

    Debug.Print(MyObj.GetType = GetType(Integer)) 'Returns False
    Debug.Print(MyObj.GetType = GetType(Double)) '# Returns True
    Debug.Print(MyObj.GetType = GetType(Object)) 'Returns False

    Debug.Print(TypeOf MyObj Is Integer) 'Returns False
    Debug.Print(TypeOf MyObj Is Double) '# Returns True
    Debug.Print(TypeOf MyObj Is Object) '# Returns True


End Sub

EDIT

You can also use Information.TypeName(Object) to get the TypeName of a given object. For example,

Dim Foo as Bar
Dim Result as String
Result = TypeName(Foo)
Debug.Print(Result) 'Will display "Bar"

AssertionError: View function mapping is overwriting an existing endpoint function: main

There is a fix for Flask issue #570 introduced recenty (flask 0.10) that causes this exception to be raised.

See https://github.com/mitsuhiko/flask/issues/796

So if you go to flask/app.py and comment out the 4 lines 948..951, this may help until the issue is resovled fully in a new version.

The diff of that change is here: http://github.com/mitsuhiko/flask/commit/661ee54bc2bc1ea0763ac9c226f8e14bb0beb5b1

What are advantages of Artificial Neural Networks over Support Vector Machines?

We should also consider that the SVM system can be applied directly to non-metric spaces, such as the set of labeled graphs or strings. In fact, the internal kernel function can be generalized properly to virtually any kind of input, provided that the positive definiteness requirement of the kernel is satisfied. On the other hand, to be able to use an ANN on a set of labeled graphs, explicit embedding procedures must be considered.

Programmatically change the src of an img tag

<img src="../template/edit.png" name="edit-save" onclick="this.src = '../template/save.png'" />

" app-release.apk" how to change this default generated apk name

Add the following code in build.gradle(Module:app)

android {
    ......
    ......
    ......
    buildTypes {
        release {
            ......
            ......
            ......
            /*The is the code fot the template of release name*/
            applicationVariants.all { variant ->
                variant.outputs.each { output ->
                    def formattedDate = new Date().format('yyyy-MM-dd HH-mm')
                    def newName = "Your App Name " + formattedDate
                    output.outputFile = new File(output.outputFile.parent, newName)
                }
            }
        }
    }
}

And the release build name will be Your App Name 2018-03-31 12-34

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

In .Net 1.1 and earlier, Application.Exit was not a wise choice and the MSDN docs specifically recommended against it because all message processing stopped immediately.

In later versions however, calling Application.Exit will result in Form.Close being called on all open forms in the application, thus giving you a chance to clean up after yourself, or even cancel the operation all together.

Delete all data in SQL Server database

It is usually much faster to script out all the objects in the database, and create an empty one, that to delete from or truncate tables.

What's the difference between git reset --mixed, --soft, and --hard?

Here is a basic explanation for TortoiseGit users:

git reset --soft and --mixed leave your files untouched.

git reset --hard actually change your files to match the commit you reset to.

In TortoiseGit, The concept of the index is very hidden by the GUI. When you modify a file, you don't have to run git add to add the change to the staging area/index. When simply dealing with modifications to existing files that are not changing file names, git reset --soft and --mixed are the same! You will only notice a difference if you added new files or renamed files. In this case, if you run git reset --mixed, you will have to re-add your file(s) from the Not Versioned Files list.

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

You have to change MySQL settings. Edit my.cnf file and put this setting in mysqld section:

[mysqld]
default_authentication_plugin= mysql_native_password

Then run following command:

FLUSH PRIVILEGES;

Above command will bring into effect the changes of default authentication mechanism.

How to use org.apache.commons package?

Download commons-net binary from here. Extract the files and reference the commons-net-x.x.jar file.

Conditional formatting, entire row based

Use the "indirect" function on conditional formatting.

  1. Select Conditional Formatting
  2. Select New Rule
  3. Select "Use a Formula to determine which cells to format"
  4. Enter the Formula, =INDIRECT("g"&ROW())="X"
  5. Enter the Format you want (text color, fill color, etc).
  6. Select OK to save the new format
  7. Open "Manage Rules" in Conditional Formatting
  8. Select "This Worksheet" if you can't see your new rule.
  9. In the "Applies to" box of your new rule, enter =$A$1:$Z$1500 (or however wide/long you want the conditional formatting to extend depending on your worksheet)

For every row in the G column that has an X, it will now turn to the format you specified. If there isn't an X in the column, the row won't be formatted.

You can repeat this to do multiple row formatting depending on a column value. Just change either the g column or x specific text in the formula and set different formats.

For example, if you add a new rule with the formula, =INDIRECT("h"&ROW())="CAR", then it will format every row that has CAR in the H Column as the format you specified.

Gradient text color

The way this effect works is very simple. The element is given a background which is the gradient. It goes from one color to another depending on the colors and color-stop percentages given for it.

For example, in rainbow text sample (note that I've converted the gradient into the standard syntax):

  • The gradient starts at color #f22 at 0% (that is the left edge of the element). First color is always assumed to start at 0% even though the percentage is not mentioned explicitly.
  • Between 0% to 14.25%, the color changes from #f22 to #f2f gradually. The percenatge is set at 14.25 because there are seven color changes and we are looking for equal splits.
  • At 14.25% (of the container's size), the color will exactly be #f2f as per the gradient specified.
  • Similarly the colors change from one to another depending on the bands specified by color stop percentages. Each band should be a step of 14.25%.

So, we end up getting a gradient like in the below snippet. Now this alone would mean the background applies to the entire element and not just the text.

_x000D_
_x000D_
.rainbow {_x000D_
  background-image: linear-gradient(to right, #f22, #f2f 14.25%, #22f 28.5%, #2ff 42.75%, #2f2 57%, #2f2 71.25%, #ff2 85.5%, #f22);_x000D_
  color: transparent;_x000D_
}
_x000D_
<span class="rainbow">Rainbow text</span>
_x000D_
_x000D_
_x000D_

Since, the gradient needs to be applied only to the text and not to the element on the whole, we need to instruct the browser to clip the background from the areas outside the text. This is done by setting background-clip: text.

(Note that the background-clip: text is an experimental property and is not supported widely.)


Now if you want the text to have a simple 3 color gradient (that is, say from red - orange - brown), we just need to change the linear-gradient specification as follows:

  • First parameter is the direction of the gradient. If the color should be red at left side and brown at the right side then use the direction as to right. If it should be red at right and brown at left then give the direction as to left.
  • Next step is to define the colors of the gradient. Since our gradient should start as red on the left side, just specify red as the first color (percentage is assumed to be 0%).
  • Now, since we have two color changes (red - orange and orange - brown), the percentages must be set as 100 / 2 for equal splits. If equal splits are not required, we can assign the percentages as we wish.
  • So at 50% the color should be orange and then the final color would be brown. The position of the final color is always assumed to be at 100%.

Thus the gradient's specification should read as follows:

background-image: linear-gradient(to right, red, orange 50%, brown).

If we form the gradients using the above mentioned method and apply them to the element, we can get the required effect.

_x000D_
_x000D_
.red-orange-brown {_x000D_
  background-image: linear-gradient(to right, red, orange 50%, brown);_x000D_
  color: transparent;_x000D_
  -webkit-background-clip: text;_x000D_
  background-clip: text;_x000D_
}_x000D_
.green-yellowgreen-yellow-gold {_x000D_
  background-image: linear-gradient(to right, green, yellowgreen 33%, yellow 66%, gold);_x000D_
  color: transparent;_x000D_
  -webkit-background-clip: text;_x000D_
  background-clip: text;_x000D_
}
_x000D_
<span class="red-orange-brown">Red to Orange to Brown</span>_x000D_
_x000D_
<br>_x000D_
_x000D_
<span class="green-yellowgreen-yellow-gold">Green to Yellow-green to Yellow to Gold</span>
_x000D_
_x000D_
_x000D_

MySQL: How to reset or change the MySQL root password?

You can try these some steps to reset mysql 5.7 root password :

Stop Mysql Service 1st

sudo /etc/init.d/mysql stop 

Login as root without password sudo mysqld_safe --skip-grant-tables &

After login mysql terminal you should need execute commands more:

use mysql;




UPDATE mysql.user SET authentication_string=PASSWORD('solutionclub3@*^G'), plugin='mysql_native_password' WHERE User='root';


flush privileges;


sudo mysqladmin -S /var/run/mysqld/mysqld.sock shutdown

After you restart your mysql server If you still facing error you must visit : Reset MySQL 5.7 root password Ubuntu 16.04

Mask for an Input to allow phone numbers?

It can be done using a directive. Below is the plunker of the input mask I built.

https://plnkr.co/edit/hRsmd0EKci6rjGmnYFRr?p=preview

Code:

import {Directive, Attribute, ElementRef, OnInit, OnChanges, Input, SimpleChange } from 'angular2/core';
import {NgControl, DefaultValueAccessor} from 'angular2/common';

@Directive({
selector: '[mask-input]',
host: {
    //'(keyup)': 'onInputChange()',
    '(click)': 'setInitialCaretPosition()'
}, 
inputs: ['modify'],
providers: [DefaultValueAccessor]
})
export class MaskDirective implements OnChanges {
maskPattern: string;
placeHolderCounts: any;
dividers: string[];
modelValue: string;
viewValue: string;
intialCaretPos: any;
numOfChar: any;
@Input() modify: any; 

constructor(public model: NgControl, public ele: ElementRef, @Attribute("mask-input") maskPattern: string) {
    this.dividers = maskPattern.replace(/\*/g, "").split("");
    this.dividers.push("_");
    this.generatePattern(maskPattern);   
    this.numOfChar = 0;
}

ngOnChanges(changes: { [propertyName: string]: SimpleChange }) {
    this.onInputChange(changes);
}

onInputChange(changes: { [propertyName: string]: SimpleChange }) {             
    this.modelValue = this.getModelValue();
    var caretPosition = this.ele.nativeElement.selectionStart;
    if (this.viewValue != null) {
      this.numOfChar = this.getNumberOfChar(caretPosition);
    }
    var stringToFormat = this.modelValue;        

    if (stringToFormat.length < 10) {
        stringToFormat = this.padString(stringToFormat);
    }

    this.viewValue = this.format(stringToFormat);

    if (this.viewValue != null) {
        caretPosition = this.setCaretPosition(this.numOfChar);
    }

    this.model.viewToModelUpdate(this.modelValue);
    this.model.valueAccessor.writeValue(this.viewValue);
    this.ele.nativeElement.selectionStart = caretPosition;
    this.ele.nativeElement.selectionEnd = caretPosition;
}

generatePattern(patternString) {
    this.placeHolderCounts = (patternString.match(/\*/g) || []).length;
    for (var i = 0; i < this.placeHolderCounts; i++) {
        patternString = patternString.replace('*', "{" + i + "}");
    }
    this.maskPattern = patternString;
}

format(s) {
    var formattedString = this.maskPattern;
    for (var i = 0; i < this.placeHolderCounts; i++) {
        formattedString = formattedString.replace("{" + i + "}", s.charAt(i));
    }
    return formattedString;
}

padString(s) {
    var pad = "__________";
    return (s + pad).substring(0, pad.length);
}

getModelValue() {
    var modelValue = this.model.value;
    if (modelValue == null) {
        return "";
    }
    for (var i = 0; i < this.dividers.length; i++) {
        while (modelValue.indexOf(this.dividers[i]) > -1) {
            modelValue = modelValue.replace(this.dividers[i], "");
        }
    }
    return modelValue;
}

setInitialCaretPosition() {
    var caretPosition = this.setCaretPosition(this.modelValue.length);

    this.ele.nativeElement.selectionStart = caretPosition;
    this.ele.nativeElement.selectionEnd = caretPosition;

}

setCaretPosition(num) {
    var notDivider = true;
    var caretPos = 1;
    for (; num > 0; caretPos++) {
      var ch = this.viewValue.charAt(caretPos);
      if (!this.isDivider(ch)) {
        num--;
      }
    }
    return caretPos;
}

isDivider(ch) {
    for (var i = 0; i < this.dividers.length; i++) {
          if (ch == this.dividers[i]) {
              return true;
          }
    }
}

getNumberOfChar(pos) {
  var num = 0;
  var containDividers = false;
  for (var i = 0; i < pos; i++) {
    var ch = this.modify.charAt(i);

    if (!this.isDivider(ch)) {
      num++;
    }
    else {
      containDividers = true;
    }
  }
  if (containDividers) {
    return num;
  }
  else {
    return this.numOfChar;
  }
}

}

Note: there are still a few bugs.

Plotting dates on the x-axis with Python's matplotlib

As @KyssTao has been saying, help(dates.num2date) says that the x has to be a float giving the number of days since 0001-01-01 plus one. Hence, 19910102 is not 2/Jan/1991, because if you counted 19910101 days from 0001-01-01 you'd get something in the year 54513 or similar (divide by 365.25, number of days in a year).

Use datestr2num instead (see help(dates.datestr2num)):

new_x = dates.datestr2num(date) # where date is '01/02/1991'

Create an empty object in JavaScript with {} or new Object()?

Objects

There is no benefit to using new Object(); - whereas {}; can make your code more compact, and more readable.

For defining empty objects they're technically the same. The {} syntax is shorter, neater (less Java-ish), and allows you to instantly populate the object inline - like so:

var myObject = {
        title:  'Frog',
        url:    '/img/picture.jpg',
        width:  300,
        height: 200
      };

Arrays

For arrays, there's similarly almost no benefit to ever using new Array(); over []; - with one minor exception:

var emptyArray = new Array(100);

creates a 100 item long array with all slots containing undefined - which may be nice/useful in certain situations (such as (new Array(9)).join('Na-Na ') + 'Batman!').

My recommendation

  1. Never use new Object(); - it's clunkier than {}; and looks silly.
  2. Always use []; - except when you need to quickly create an "empty" array with a predefined length.

Static link of shared library function in gcc

Yeah, I know this is an 8 year-old question, but I was told that it was possible to statically link against a shared-object library and this was literally the top hit when I searched for more information about it.

To actually demonstrate that statically linking a shared-object library is not possible with ld (gcc's linker) -- as opposed to just a bunch of people insisting that it's not possible -- use the following gcc command:

gcc -o executablename objectname.o -Wl,-Bstatic -l:libnamespec.so

(Of course you'll have to compile objectname.o from sourcename.c, and you should probably make up your own shared-object library as well. If you do, use -Wl,--library-path,. so that ld can find your library in the local directory.)

The actual error you receive is:

/usr/bin/ld: attempted static link of dynamic object `libnamespec.so'
collect2: error: ld returned 1 exit status

Hope that helps.

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

This solution sort by Col1 and group by Col2. Then extract value of Col2 and display it in a mbox.

var grouped = from DataRow dr in dt.Rows orderby dr["Col1"] group dr by dr["Col2"];
string x = "";
foreach (var k in grouped) x += (string)(k.ElementAt(0)["Col2"]) + Environment.NewLine;
MessageBox.Show(x);

Play audio with Python

It is possible to play audio in OS X without any 3rd party libraries using an analogue of the following code. The raw audio data can be input with wave_wave.writeframes. This code extracts 4 seconds of audio from the input file.

import wave
import io
from AppKit import NSSound


wave_output = io.BytesIO()
wave_shell = wave.open(wave_output, mode="wb")
file_path = 'SINE.WAV'
input_audio = wave.open(file_path)
input_audio_frames = input_audio.readframes(input_audio.getnframes())

wave_shell.setnchannels(input_audio.getnchannels())
wave_shell.setsampwidth(input_audio.getsampwidth())
wave_shell.setframerate(input_audio.getframerate())

seconds_multiplier = input_audio.getnchannels() * input_audio.getsampwidth() * input_audio.getframerate()

wave_shell.writeframes(input_audio_frames[second_multiplier:second_multiplier*5])

wave_shell.close()

wave_output.seek(0)
wave_data = wave_output.read()
audio_stream = NSSound.alloc()
audio_stream.initWithData_(wave_data)
audio_stream.play()

How to list all users in a Linux group?

In UNIX (as opposed to GNU/Linux), there's the listusers command. See the Solaris man page for listusers.

Note that this command is part of the open-source Heirloom Project. I assume that it's missing from GNU/Linux because RMS doesn't believe in groups and permissions. :-)

String contains - ignore case

An optimized Imran Tariq's version

Pattern.compile(strptrn, Pattern.CASE_INSENSITIVE + Pattern.LITERAL).matcher(str1).find();

Pattern.quote(strptrn) always returns "\Q" + s + "\E" even if there is nothing to quote, concatination spoils performance.

How to negate code in "if" statement block in JavaScript -JQuery like 'if not then..'

Try negation operator ! before $(this):

if (!$(this).parent().next().is('ul')){

React - How to pass HTML tags in props?

We can do the same thing in such a way.

const Child = () => {
  return (
     write your whole HTML here.
  )
}

now you want to send this HTML inside another component which name is Parent component.

Calling :-

<Parent child={<child/>} >
</Parent> 

Use Of Child:-

 const Parent = (props) => {
   const { child } = props; 
   return (
       {child}
    )
}

this work perfect for me.

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

Bootstrap Element 100% Width

The container class is intentionally not 100% width. It is different fixed widths depending on the width of the viewport.

If you want to work with the full width of the screen, use .container-fluid:

Bootstrap 3:

<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-lg-6"></div>
      <div class="col-lg-6"></div>
    </div>
    <div class="row">
      <div class="col-lg-8"></div>
      <div class="col-lg-4"></div>
    </div>
    <div class="row">
      <div class="col-lg-12"></div>
    </div>
  </div>
</body>

Bootstrap 2:

<body>
  <div class="row">
    <div class="span6"></div>
    <div class="span6"></div>
  </div>
  <div class="row">
    <div class="span8"></div>
    <div class="span4"></div>
  </div>
  <div class="row">
    <div class="span12"></div>
  </div>
</body>

how to use Blob datatype in Postgres

I think this is the most comprehensive answer on the PostgreSQL wiki itself: https://wiki.postgresql.org/wiki/BinaryFilesInDB

Read the part with the title 'What is the best way to store the files in the Database?'

Request exceeded the limit of 10 internal redirects due to probable configuration error

This error occurred to me when I was debugging the PHP header() function:

header('Location: /aaa/bbb/ccc'); // error

If I use a relative path it works:

header('Location: aaa/bbb/ccc'); // success, but not what I wanted

However when I use an absolute path like /aaa/bbb/ccc, it gives the exact error:

Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

It appears the header function redirects internally without going HTTP at all which is weird. After some tests and trials, I found the solution of adding exit after header():

header('Location: /aaa/bbb/ccc');
exit;

And it works properly.

Align DIV to bottom of the page

Simple 2020 no-tricks method:

body {
    display: flex;
    flex-direction: column;
}

#footer {
    margin-top: auto;
}

How to dynamically create columns in datatable and assign values to it?

If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :

  • Create Data table object.
  • Add columns into that data table object.
  • Add Rows with values into the object.

For eg.

Dim dt As New DataTable

dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))

dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")

How to change the font and font size of an HTML input tag?

<input type ="text" id="txtComputer">

css

input[type="text"]
{
    font-size:24px;
}

Exception.Message vs Exception.ToString()

In terms of the XML format for log4net, you need not worry about ex.ToString() for the logs. Simply pass the exception object itself and log4net does the rest do give you all of the details in its pre-configured XML format. The only thing I run into on occasion is new line formatting, but that's when I'm reading the files raw. Otherwise parsing the XML works great.

Powershell 2 copy-item which creates a folder if doesn't exist

I have stumbled here twice, and this last time was a unique situation and even though I ditch using copy-item I wanted to post the solution I used.

Had a list of nothing but files with the full path and in majority of the case the files have no extensions. the -Recurse -Force option would not work for me so I ditched copy-item function and fell back to something like below using xcopy as I still wanted to keep it a one liner. Initially I tied with Robocopy but it is apparently looking for a file extension and since many of mine had no extension it considered it a directory.

$filelist = @("C:\Somepath\test\location\here\file","C:\Somepath\test\location\here2\file2")

$filelist | % { echo f | xcopy $_  $($_.Replace("somepath", "somepath_NEW")) }

Hope it helps someone.

Right way to reverse a pandas DataFrame?

data.reindex(index=data.index[::-1])

or simply:

data.iloc[::-1]

will reverse your data frame, if you want to have a for loop which goes from down to up you may do:

for idx in reversed(data.index):
    print(idx, data.loc[idx, 'Even'], data.loc[idx, 'Odd'])

or

for idx in reversed(data.index):
    print(idx, data.Even[idx], data.Odd[idx])

You are getting an error because reversed first calls data.__len__() which returns 6. Then it tries to call data[j - 1] for j in range(6, 0, -1), and the first call would be data[5]; but in pandas dataframe data[5] means column 5, and there is no column 5 so it will throw an exception. ( see docs )

How to remove leading and trailing spaces from a string

String.Trim

Removes all leading and trailing white-space characters from the current String object.

Usage:

txt = txt.Trim();

If this isn't working then it highly likely that the "spaces" aren't spaces but some other non printing or white space character, possibly tabs. In this case you need to use the String.Trim method which takes an array of characters:

  char[] charsToTrim = { ' ', '\t' };
  string result = txt.Trim(charsToTrim);

Source

You can add to this list as and when you come across more space like characters that are in your input data. Storing this list of characters in your database or configuration file would also mean that you don't have to rebuild your application each time you come across a new character to check for.

NOTE

As of .NET 4 .Trim() removes any character that Char.IsWhiteSpace returns true for so it should work for most cases you come across. Given this, it's probably not a good idea to replace this call with the one that takes a list of characters you have to maintain.

It would be better to call the default .Trim() and then call the method with your list of characters.

SQL Server - NOT IN

It's because of the way NOT IN works.

To avoid these headaches (and for a faster query in many cases), I always prefer NOT EXISTS:

SELECT  *  
FROM Table1 t1 
WHERE NOT EXISTS (
    SELECT * 
    FROM Table2 t2 
    WHERE t1.MAKE = t2.MAKE
    AND   t1.MODEL = t2.MODEL
    AND   t1.[Serial Number] = t2.[serial number]);

How to know user has clicked "X" or the "Close" button?

I always use a Form Close method in my applications that catches alt + x from my exit Button, alt + f4 or another form closing event was initiated. All my classes have the class name defined as Private string mstrClsTitle = "grmRexcel" in this case, an Exit method that calls the Form Closing Method and a Form Closing Method. I also have a statement for the Form Closing Method - this.FormClosing = My Form Closing Form Closing method name.

The code for this:

namespace Rexcel_II
{
    public partial class frmRexcel : Form
    {
        private string mstrClsTitle = "frmRexcel";

        public frmRexcel()
        {
            InitializeComponent();

            this.FormClosing += frmRexcel_FormClosing;
        }

        /// <summary>
        /// Handles the Button Exit Event executed by the Exit Button Click
        /// or Alt + x
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {            
            this.Close();        
        }


        /// <summary>
        /// Handles the Form Closing event
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmRexcel_FormClosing(object sender, FormClosingEventArgs e)
        {

            // ---- If windows is shutting down, 
            // ---- I don't want to hold up the process
            if (e.CloseReason == CloseReason.WindowsShutDown) return;
            {

                // ---- Ok, Windows is not shutting down so
                // ---- either btnExit or Alt + x or Alt + f4 has been clicked or
                // ---- another form closing event was intiated
                //      *)  Confirm user wants to close the application
                switch (MessageBox.Show(this, 
                                    "Are you sure you want to close the Application?",
                                    mstrClsTitle + ".frmRexcel_FormClosing",
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {

                    // ---- *)  if No keep the application alive 
                    //----  *)  else close the application
                    case DialogResult.No:
                        e.Cancel = true;
                        break;
                    default:
                        break;
                }
            }
        }
    }
}

What is the current choice for doing RPC in Python?

You missed out omniORB. This is a pretty full CORBA implementation, so you can also use it to talk to other languages that have CORBA support.

How do I loop through rows with a data reader in C#?

Suppose your DataTable has the following columns try this code:

DataTable dt =new DataTable();
txtTGrossWt.Text = dt.Compute("sum(fldGrossWeight)", "").ToString() == "" ? "0" : dt.Compute("sum(fldGrossWeight)", "").ToString();
txtTOtherWt.Text = dt.Compute("sum(fldOtherWeight)", "").ToString() == "" ? "0" : dt.Compute("sum(fldOtherWeight)", "").ToString();
txtTNetWt.Text = dt.Compute("sum(fldNetWeight)", "").ToString() == "" ? "0" : dt.Compute("sum(fldNetWeight)", "").ToString();
txtFinalValue.Text = dt.Compute("sum(fldValue)", "").ToString() == "" ? "0" : dt.Compute("sum(fldValue)", "").ToString();