Programs & Examples On #Tdataset

tdataset is the base class for all dataset components. Defined in the DB.pas unit, it represents data in rows and columns.

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

Just put the

Response.End();

within a finally block instead of within the try block.

This has worked for me!!!.

I had the following problematic (with the Exception) code structure

...
Response.Clear();
...
...
try{
 if (something){
   Reponse.Write(...);
   Response.End();

   return;

 } 

 some_more_code...

 Reponse.Write(...);
 Response.End();

}
catch(Exception){
}
finally{}

and it throws the exception. I suspect the Exception is thrown where there is code / work to execute after response.End(); . In my case the extra code was just the return itself.

When I just moved the response.End(); to the finally block (and left the return in its place - which causes skipping the rest of code in the try block and jumping to the finally block (not just exiting the containing function) ) the Exception ceased to take place.

The following works OK:

...
Response.Clear();
...
...
try{
 if (something){
   Reponse.Write(...);

   return;

 } 

 some_more_code...

 Reponse.Write(...);

}
catch(Exception){
}
finally{
    Response.End();
}

Direct method from SQL command text to DataSet

Just finish it up.

string sqlCommand = "SELECT * FROM TABLE";
string connectionString = "blahblah";

DataSet ds = GetDataSet(sqlCommand, connectionString);
DataSet GetDataSet(string sqlCommand, string connectionString)
{
    DataSet ds = new DataSet();
    using (SqlCommand cmd = new SqlCommand(
        sqlCommand, new SqlConnection(connectionString)))
    {
        cmd.Connection.Open();
        DataTable table = new DataTable();
        table.Load(cmd.ExecuteReader());
        ds.Tables.Add(table);
    }
    return ds;
}

Exception of type 'System.OutOfMemoryException' was thrown. Why?

It runs successfully the first time, but if I run it again, I keep getting a System.OutOfMemoryException. What are some reasons this could be happening?

Regardless of what the others have said, the error has nothing to do with forgetting to dispose your DBCommand or DBConnection, and you will not fix your error by disposing of either of them.

The error has everything to do with your dataset which contains nearly 600,000 rows of data. Apparently your dataset consumes more than 50% of the available memory on your machine. Clearly, you'll run out of memory when you return another dataset of the same size before the first one has been garbage collected. Simple as that.

You can remedy this problem in a few ways:

  • Consider returning fewer records. I personally can't imagine a time when returning 600K records has ever been useful to a user. To minimize the records returned, try:

    • Limiting your query to the first 1000 records. If there are more than 1000 results returned from the query, inform the user to narrow their search results.

    • If your users really insist on seeing that much data at once, try paging the data. Remember: Google never shows you all 22 bajillion results of a search at once, it shows you 20 or so records at a time. Google probably doesn't hold all 22 bajillion results in memory at once, it probably finds its more memory efficient to requery its database to generate a new page.

  • If you just need to iterate through the data and you don't need random access, try returning a datareader instead. A datareader only loads one record into memory at a time.

If none of those are an option, then you need to force .NET to free up the memory used by the dataset before calling your method using one of these methods:

  • Remove all references to your old dataset. Anything holding on to a refenence of your dataset will prevent it from being reclaimed by memory.

  • If you can't null all the references to your dataset, clear all of the rows from the dataset and any objects bound to those rows instead. This removes references to the datarows and allows them to be eaten by the garbage collector.

I don't believe you'll need to call GC.Collect() to force a gen cycle. Not only is it generally a bad idea to call GC.Collect(), because sufficient memory pressure will cause .NET invoke the garbage collector on its own.

Note: calling Dispose on your dataset does not free any memory, nor does it invoke the garbage collector, nor does it remove a reference to your dataset. Dispose is used to clean up unmanaged resources, but the DataSet does not have any unmanaged resources. It only implements IDispoable because it inherents from MarshalByValueComponent, so the Dispose method on the dataset is pretty much useless.

Can I get the name of the current controller in the view?

Use controller.controller_name

In the Rails Guides, it says:

The params hash will always contain the :controller and :action keys, but you should use the methods controller_name and action_name instead to access these values

ActionController Parameters

So let's say you have a CSS class active , that should be inserted in any link whose page is currently open (maybe so that you can style differently) . If you have a static_pages controller with an about action, you can then highlight the link like so in your view:

<li>
  <a class='button <% if controller.controller_name == "static_pages" && controller.action_name == "about" %>active<%end%>' href="/about">
      About Us
  </a>
</li>

How do I remove all null and empty string values from an object?

function removeAllBlankOrNull(JsonObj) {
    $.each(JsonObj, function(key, value) {
        if (value === "" || value === null) {
            delete JsonObj[key];
        } else if (typeof(value) === "object") {
            JsonObj[key] = removeAllBlankOrNull(value);
        }
    });
    return JsonObj;
}

Deletes all empty strings and null values recursively. Fiddle

What's the syntax to import a class in a default package in Java?

The only way to access classes in the default package is from another class in the default package. In that case, don't bother to import it, just refer to it directly.

How to uninstall an older PHP version from centOS7

Subscribing to the IUS Community Project Repository

cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh

Run the script:

sudo bash setup-ius.sh

Upgrading mod_php with Apache

This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.

Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.

sudo yum remove php-cli mod_php php-common

Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.

sudo yum install mod_php70u php70u-cli php70u-mysqlnd

Finally, restart Apache to load the new version of mod_php:

sudo apachectl restart

You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:

systemctl status httpd

Saving Excel workbook to constant path with filename from two fields

try

Sub save()
ActiveWorkbook.SaveAS Filename:="C:\-docs\cmat\Desktop\New folder\" & Range("C5").Text & chr(32) & Range("C8").Text &".xls", FileFormat:= _
  xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
 , CreateBackup:=False
End Sub

If you want to save the workbook with the macros use the below code

Sub save()
ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
    "\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xlsm", FileFormat:= _
    xlOpenXMLWorkbookMacroEnabled, Password:=vbNullString, WriteResPassword:=vbNullString, _
    ReadOnlyRecommended:=False, CreateBackup:=False
End Sub

if you want to save workbook with no macros and no pop-up use this

Sub save()
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
    "\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xls", _
    FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    Application.DisplayAlerts = True
End Sub

How to properly exit a C# application?

This will work from anywhere, inside Form(), Form_Load(), or any event handler. I posted before, but I don't see it now?!?

public void exit(int exitCode)
{
    if (System.Windows.Forms.Application.MessageLoop)
    {
       // Use this since we are in a running Form
       System.Windows.Forms.Application.Exit();
       System.Environment.Exit(exitCode);
    }
    else
    {
       // Form ended or never .Run
       System.Environment.Exit(exitCode);
    }
} //* end exit()

Java Compare Two List's object values?

ArrayList already have support for this, with the equals method. Quoting the docs

... In other words, two lists are defined to be equal if they contain the same elements in the same order.

It does require you to properly implement equals in your MyData class.

Edit

You have updated the question stating that the lists could have different orders. In that case, sort your list first, and then apply equals.

Git push results in "Authentication Failed"

Problem Statement: "git fatal authentication failed". I am using bitbucket.

Solution: I simply deleted the user from using access management of bitbucket and then added the same user. The .gitconfig file is simple

[user]
    name = BlaBla
    email = [email protected]

[push]
    default = simple

Run bash command on jenkins pipeline

If you want to change your default shell to bash for all projects on Jenkins, you can do so in the Jenkins config through the web portal:

Manage Jenkins > Configure System (Skip this clicking if you want by just going to https://{YOUR_JENKINS_URL}/configure.)

Fill in the field marked 'Shell executable' with the value /bin/bash and click 'Save'.

Hibernate, @SequenceGenerator and allocationSize

I would check the DDL for the sequence in the schema. JPA Implementation is responsible only creation of the sequence with the correct allocation size. Therefore, if the allocation size is 50 then your sequence must have the increment of 50 in its DDL.

This case may typically occur with the creation of a sequence with allocation size 1 then later configured to allocation size 50 (or default) but the sequence DDL is not updated.

How to get file extension from string in C++

Actually, the easiest way is

char* ext;
ext = strrchr(filename,'.') 

One thing to remember: if '.' doesn't exist in filename, ext will be NULL.

Iterate through <select> options

You can try like this too.

Your HTML Code

<select id="mySelectionBox">
    <option value="hello">Foo</option>
    <option value="hello1">Foo1</option>
    <option value="hello2">Foo2</option>
    <option value="hello3">Foo3</option>
</select>

You JQuery Code

$("#mySelectionBox option").each(function() {
    alert(this.text + ' ' + this.value);
});

OR

var select =  $('#mySelectionBox')[0];

  for (var i = 0; i < select.length; i++){
    var option = select.options[i];
    alert (option.text + ' ' + option.value);
  }

How to initialize std::vector from C-style array?

Don't forget that you can treat pointers as iterators:

w_.assign(w, w + len);

Npm install failed with "cannot run in wd"

!~~ For Docker ~~!

@Alexander Mills answer - just to make it easier to find:

RUN npm set unsafe-perm true

How do I make XAML DataGridColumns fill the entire DataGrid?

For those looking for a C# workaround:

If you need for some reason to have the "AutoGeneratedColumns" enabled, one thing you can do is to specify all the columns's width except the ones you want to be auto resized (it will not take the remaining space, but it will resize to the cell's content).

Example (dgShopppingCart is my DataGrid):

dgShoppingCart.Columns[0].Visibility = Visibility.Hidden; 
dgShoppingCart.Columns[1].Header = "Qty";
dgShoppingCart.Columns[1].Width = 100;
dgShoppingCart.Columns[2].Header = "Product Name"; /*This will be resized to cell content*/
dgShoppingCart.Columns[3].Header = "Price";
dgShoppingCart.Columns[3].Width = 100;
dgShoppingCart.Columns[4].Visibility = Visibility.Hidden; 

For me it works as a workaround because I needed to have the DataGrid resized when the user maximize the Window.

My Routes are Returning a 404, How can I Fix Them?

you must be using Laravel 5 the command

  class User_Controller extends Controller {
  public $restful = true;
  public function get_index(){
  return View('user.index');
  }
  }

and in routes.php

  Route::get('/', function()
  {
  return view('home.index');
  });

  Route::get('user', function()
  {
  return view('user.index');
  });

Laravel 5 command changes for view and controller see the documentation i was having same error before

Compare cell contents against string in Excel

If a case-insensitive comparison is acceptable, just use =:

=IF(A1="ENG",1,0)

How to work with progress indicator in flutter?

This is my solution with stack

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';

final themeColor = new Color(0xfff5a623);
final primaryColor = new Color(0xff203152);
final greyColor = new Color(0xffaeaeae);
final greyColor2 = new Color(0xffE8E8E8);

class LoadindScreen extends StatefulWidget {
  LoadindScreen({Key key, this.title}) : super(key: key);
  final String title;
  @override
  LoginScreenState createState() => new LoginScreenState();
}

class LoginScreenState extends State<LoadindScreen> {
  SharedPreferences prefs;

  bool isLoading = false;

  Future<Null> handleSignIn() async {
    setState(() {
      isLoading = true;
    });
    prefs = await SharedPreferences.getInstance();
    var isLoadingFuture = Future.delayed(const Duration(seconds: 3), () {
      return false;
    });
    isLoadingFuture.then((response) {
      setState(() {
        isLoading = response;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            widget.title,
            style: TextStyle(color: primaryColor, fontWeight: FontWeight.bold),
          ),
          centerTitle: true,
        ),
        body: Stack(
          children: <Widget>[
            Center(
              child: FlatButton(
                  onPressed: handleSignIn,
                  child: Text(
                    'SIGN IN WITH GOOGLE',
                    style: TextStyle(fontSize: 16.0),
                  ),
                  color: Color(0xffdd4b39),
                  highlightColor: Color(0xffff7f7f),
                  splashColor: Colors.transparent,
                  textColor: Colors.white,
                  padding: EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0)),
            ),

            // Loading
            Positioned(
              child: isLoading
                  ? Container(
                      child: Center(
                        child: CircularProgressIndicator(
                          valueColor: AlwaysStoppedAnimation<Color>(themeColor),
                        ),
                      ),
                      color: Colors.white.withOpacity(0.8),
                    )
                  : Container(),
            ),
          ],
        ));
  }
}

Python 3 Building an array of bytes

Here is a solution to getting an array (list) of bytes:

I found that you needed to convert the Int to a byte first, before passing it to the bytes():

bytes(int('0xA2', 16).to_bytes(1, "big"))

Then create a list from the bytes:

list(frame)

So your code should look like:

frame = b""
frame += bytes(int('0xA2', 16).to_bytes(1, "big"))
frame += bytes(int('0x01', 16).to_bytes(1, "big"))
frame += bytes(int('0x02', 16).to_bytes(1, "big"))
frame += bytes(int('0x03', 16).to_bytes(1, "big"))
frame += bytes(int('0x04', 16).to_bytes(1, "big"))
bytesList = list(frame)

The question was for an array (list) of bytes. You accepted an answer that doesn't tell how to get a list so I'm not sure if this is actually what you needed.

rails generate model

The error shows you either didn't create the rails project yet or you're not in the rails project directory.

Suppose if you're working on myapp project. You've to move to that project directory on your command line and then generate the model. Here are some steps you can refer.

Example: Assuming you didn't create the Rails app yet:

$> rails new myapp
$> cd myapp

Now generate the model from your commandline.

$> rails generate model your_model_name 

Import SQL file into mysql

In Windows OS the following commands works for me.

mysql>Use <DatabaseName>
mysql>SOURCE C:/data/ScriptFile.sql;

No single quotes or double quotes around file name. Path would contain '/' instead of '\'.

How to keep form values after post

If you are looking to just repopulate the fields with the values that were posted in them, then just echo the post value back into the field, like so:

<input type="text" name="myField1" value="<?php echo isset($_POST['myField1']) ? $_POST['myField1'] : '' ?>" />

How do I set the rounded corner radius of a color drawable using xml?

Try below code

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
    android:bottomLeftRadius="30dp"
    android:bottomRightRadius="30dp"
    android:topLeftRadius="30dp"
    android:topRightRadius="30dp" />
<solid android:color="#1271BB" />

<stroke
    android:width="5dp"
    android:color="#1271BB" />

<padding
    android:bottom="1dp"
    android:left="1dp"
    android:right="1dp"
    android:top="1dp" /></shape>

How to add many functions in ONE ng-click?

A lot of people use (click) option so I will share this too.

<button (click)="function1()" (click)="function2()">Button</button>

XSLT equivalent for JSON

For a working doodle/proof of concept of an approach to utilize pure JavaScript along with the familiar and declarative pattern behind XSLT's matching expressions and recursive templates, see https://gist.github.com/brettz9/0e661b3093764f496e36

(A similar approach might be taken for JSON.)

Note that the demo also relies on JavaScript 1.8 expression closures for convenience in expressing templates in Firefox (at least until the ES6 short form for methods may be implemented).

Disclaimer: This is my own code.

Python: Total sum of a list of numbers with the for loop

l = [1,2,3,4,5]
sum = 0
for x in l:
    sum = sum + x

And you can change l for any list you want.

Statically rotate font-awesome icons

If you use Less you can directly use the following mixin:

.@{fa-css-prefix}-rotate-90  { .fa-icon-rotate(90deg, 1);  }

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

How do I assign ls to an array in Linux Bash?

Whenever possible, you should avoid parsing the output of ls (see Greg's wiki on the subject). Basically, the output of ls will be ambiguous if there are funny characters in any of the filenames. It's also usually a waste of time. In this case, when you execute ls -d */, what happens is that the shell expands */ to a list of subdirectories (which is already exactly what you want), passes that list as arguments to ls -d, which looks at each one, says "yep, that's a directory all right" and prints it (in an inconsistent and sometimes ambiguous format). The ls command isn't doing anything useful!

Well, ok, it is doing one thing that's useful: if there are no subdirectories, */ will get left as is, ls will look for a subdirectory named "*", not find it, print an error message that it doesn't exist (to stderr), and not print the "*/" (to stdout).

The cleaner way to make an array of subdirectory names is to use the glob (*/) without passing it to ls. But in order to avoid putting "*/" in the array if there are no actual subdirectories, you should set nullglob first (again, see Greg's wiki):

shopt -s nullglob
array=(*/)
shopt -u nullglob # Turn off nullglob to make sure it doesn't interfere with anything later
echo "${array[@]}"  # Note double-quotes to avoid extra parsing of funny characters in filenames

If you want to print an error message if there are no subdirectories, you're better off doing it yourself:

if (( ${#array[@]} == 0 )); then
    echo "No subdirectories found" >&2
fi

How to show progress bar while loading, using ajax

I did it like this

CSS

html {
    -webkit-transition: background-color 1s;
    transition: background-color 1s;
}
html, body {
    /* For the loading indicator to be vertically centered ensure */
    /* the html and body elements take up the full viewport */
    min-height: 100%;
}
html.loading {
    /* Replace #333 with the background-color of your choice */
    /* Replace loading.gif with the loading image of your choice */
    background: #333 url('/Images/loading.gif') no-repeat 50% 50%;

    /* Ensures that the transition only runs in one direction */
    -webkit-transition: background-color 0;
    transition: background-color 0;
}
body {
    -webkit-transition: opacity 1s ease-in;
    transition: opacity 1s ease-in;
}
html.loading body {
    /* Make the contents of the body opaque during loading */
    opacity: 0;

    /* Ensures that the transition only runs in one direction */
    -webkit-transition: opacity 0;
    transition: opacity 0;
}

JS

$(document).ready(function () {
   $(document).ajaxStart(function () {     
       $("html").addClass("loading");
    });
    $(document).ajaxStop(function () {        
        $("html").removeClass("loading");
    });
    $(document).ajaxError(function () {       
        $("html").removeClass("loading");
    }); 
});

Best way to test exceptions with Assert to ensure they will be thrown

Mark the test with the ExpectedExceptionAttribute (this is the term in NUnit or MSTest; users of other unit testing frameworks may need to translate).

Using Javascript in CSS

IE and Firefox both contain ways to execute JavaScript from CSS. As Paolo mentions, one way in IE is the expression technique, but there's also the more obscure HTC behavior, in which a seperate XML that contains your script is loaded via CSS. A similar technique for Firefox exists, using XBL. These techniques don't exectue JavaScript from CSS directly, but the effect is the same.

HTC with IE

Use a CSS rule like so:

body {
  behavior:url(script.htc);
}

and within that script.htc file have something like:

<PUBLIC:COMPONENT TAGNAME="xss">
   <PUBLIC:ATTACH EVENT="ondocumentready" ONEVENT="main()" LITERALCONTENT="false"/>
</PUBLIC:COMPONENT>
<SCRIPT>
   function main() 
   {
     alert("HTC script executed.");
   }
</SCRIPT>

The HTC file executes the main() function on the event ondocumentready (referring to the HTC document's readiness.)

XBL with Firefox

Firefox supports a similar XML-script-executing hack, using XBL.

Use a CSS rule like so:

body {
  -moz-binding: url(script.xml#mycode);
}

and within your script.xml:

<?xml version="1.0"?>
<bindings xmlns="http://www.mozilla.org/xbl" xmlns:html="http://www.w3.org/1999/xhtml">

<binding id="mycode">
  <implementation>
    <constructor>
      alert("XBL script executed.");
    </constructor>
  </implementation>
</binding>

</bindings>

All of the code within the constructor tag will be executed (a good idea to wrap code in a CDATA section.)

In both techniques, the code doesn't execute unless the CSS selector matches an element within the document. By using something like body, it will execute immediately on page load.

Are there such things as variables within an Excel formula?

Not related to variables, your example will also be solved by MOD:

=Mod(VLOOKUP(A1, B:B, 1, 0);10)

How to iterate through a String

Using Guava (r07) you can do this:

for(char c : Lists.charactersOf(someString)) { ... }

This has the convenience of using foreach while not copying the string to a new array. Lists.charactersOf returns a view of the string as a List.

How to calculate the running time of my program?

The general approach to this is to:

  1. Get the time at the start of your benchmark, say at the start of main().
  2. Run your code.
  3. Get the time at the end of your benchmark, say at the end of main().
  4. Subtract the start time from the end time and convert into appropriate units.

A hint: look at System.nanoTime() or System.currentTimeMillis().

REST API Authentication

Here's a guided approach.

Your authentication service issues a JWT token that is signed using a secret that is also available in your API service. The reason they need to be there too is that you will need to verify the tokens received to make sure you created them. The nice thing about JWTs is that their payload can hold claims as to what the user is authorised to access should different users have different access control levels.

That architecture renders authentication stateless: No need to store any tokens in a database unless you would like to handle token blacklisting (think banning users). Being stateless is crucial if you ever need to scale. That also frees up your API service from having to call the authentication server at all as the information they need for both authentication and authorisation are in the issued token.

Flow (no refresh tokens):

  1. User authenticates with the authentication server (eg: POST /auth/login) and receives a JWT token generated and signed by the auth server.
  2. User uses that token to talk to your API and assuming user is authorised), gets and posts the necessary resources.

There are a couple of issues here. Namely, that auth token in the wrong hands provides unlimited access to a malicious user to pretend they are the affected user and call your APIs indefinitely. To handle that, tokens have an expiry date and clients are forced to request new tokens whenever expiry happens. That expiry is part of the token's payload. But if tokens are short-lived, do we require users to authenticate with their usernames and password every time? No. We do not want to ask a user for their password every 30min to an hour, and we do not want to persist that password anywhere in the client. To get around that issue, we introduce the concept of refresh tokens. They are longer lived tokens that serve one purpose: act as a user's password, authenticate them to get a new token. Downside is that with this architecture your authentication server needs to persist these refresh token in a database.

New flow (with refresh tokens):

  1. User authenticates with the authentication server (eg: POST /auth/login) and receives a JWT token generated and signed by the auth server, alongside a long lived (eg: 6 months) refresh token that they store securely
  2. Whenever the user needs to make an API request, the token's expiry is checked. Assuming it has not yet expired, user uses that token to talk to your API and assuming user is authorised), gets and posts the necessary resources.
  3. If the token has indeed expired, there is a need to refresh your token, user calls authentication server (EG: POST / auth/token) and passes the securely stored refresh token. Response is a new access token issued.
  4. Use that new token to talk to your API image servers.

OPTIONAL (banning users)

How do we ban users? Using that model there is no easy way to do so. Enhancement: Every persisted refresh token includes a blacklisted field and only issue new tokens if the refresh token isn't black listed.

Things to consider:

  • You may want to rotate refresh token. To do so, blacklist the refresh token each time your user needs a new access token. That way refresh tokens can only be used once. Downside you will end up with a lot more refresh tokens but that can easily be solved with a job that clears blacklisted refresh tokens (eg: once a day)
  • You may want to consider setting a maximum number of allowed refresh tokens issued per user (say 10 or 20) as you issue a new one every time they login (with username and password). This number depends on your flow, how many clients a user may use (web, mobile, etc) and other factors.
  • Logout endpoint in your authentication service may or may not blacklist refresh tokens. Something to think about.

What is polymorphism, what is it for, and how is it used?

What is polymorphism?

Polymorphism is the ability to:

  • Invoke an operation on an instance of a specialized type by only knowing its generalized type while calling the method of the specialized type and not that of the generalized type: it is dynamic polymorphism.

  • Define several methods having the save name but having differents parameters: it is static polymorphism.

The first if the historical definition and the most important.

What is polymorphism used for?

It allows to create strongly-typed consistency of the class hierarchy and to do some magical things like managing lists of objects of differents types without knowing their types but only one of their parent type, as well as data bindings.

Strong and weak typing

Sample

Here are some Shapes like Point, Line, Rectangle and Circle having the operation Draw() taking either nothing or either a parameter to set a timeout to erase it.

public class Shape
{
 public virtual void Draw()
 {
   DoNothing();
 }
 public virtual void Draw(int timeout)
 {
   DoNothing();
 }
}

public class Point : Shape
{
 int X, Y;
 public override void Draw()
 {
   DrawThePoint();
 }
}

public class Line : Point
{
 int Xend, Yend;
 public override Draw()
 {
   DrawTheLine();
 }
}

public class Rectangle : Line
{
 public override Draw()
 {
   DrawTheRectangle();
 }
}

var shapes = new List<Shape> { new Point(0,0), new Line(0,0,10,10), new rectangle(50,50,100,100) };

foreach ( var shape in shapes )
  shape.Draw();

Here the Shape class and the Shape.Draw() methods should be marked as abstract.

They are not for to make understand.

Explaination

Without polymorphism, using abstract-virtual-override, while parsing the shapes, it is only the Spahe.Draw() method that is called as the CLR don't know what method to call. So it call the method of the type we act on, and here the type is Shape because of the list declaration. So the code do nothing at all.

With polymorphism, the CLR is able to infer the real type of the object we act on using what is called a virtual table. So it call the good method, and here calling Shape.Draw() if Shape is Point calls the Point.Draw(). So the code draws the shapes.

More readings

C# - Polymorphism (Level 1)

Polymorphism in Java (Level 2)

Polymorphism (C# Programming Guide)

Virtual method table

How to send JSON instead of a query string with $.ajax?

You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    contentType: "application/json",
    complete: callback
});

Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.

How to set the environmental variable LD_LIBRARY_PATH in linux

Keep the previous path, don't overwrite it:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/your/custom/path/

You can add it to your ~/.bashrc:

echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/your/custom/path/' >> ~/.bashrc

How to automatically close cmd window after batch file execution?

This works for me

cd "C:\Program Files\SmartBear\SoapUI-5.6.0\bin"

start SoapUI-5.6.0.exe -w "C:\DATA\SoapUi\Workspaces\Production-workspace.xml"

exit

How can I start PostgreSQL server on Mac OS X?

There is some edge case that maybe will be helpful for someone:

There is an option that you will have postgres.pid filled with some PID. If you restart your machine, and before PostgreSQL will be back again, some other process will take that PID.

If that will happen, both the pg_ctl status and brew service are asked about the PostgreSQL status, will tell you that it is up.

Just do ps aux | grep <yourPID> and check if it is really PostgreSQL.

How can I convert a string to upper- or lower-case with XSLT?

For ANSI character encoding:

 translate(//variable, 'ABCDEFGHIJKLMNOPQRSTUVWXYZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞŸŽŠŒ', 'abcdefghijklmnopqrstuvwxyzàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿžšœ')

Authentication issue when debugging in VS2013 - iis express

I had just upgraded to VS 2013 from VS 2012 and the current user identity (HttpContext.User.Identity) was coming through as anonymous.

I tried changing the IIS express applicationhost.config, no difference.

The solution was to look at the properties of the web project, hit F4 to get the project properties when you have the top level of the project selected. Do not right click on the project and select properties, this is something entirely different.

Change Anonymous Authentication to be Disabled and Windows Authentication to be Enabled.

Works like gravy :)

What does the KEY keyword mean?

KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.

column_definition:
      data_type [NOT NULL | NULL] [DEFAULT default_value]
      [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
      ...

Ref: http://dev.mysql.com/doc/refman/5.1/en/create-table.html

Performance of Arrays vs. Lists

In some brief tests I have found a combination of the two to be better in what I would call reasonably intensive Math:

Type: List<double[]>

Time: 00:00:05.1861300

Type: List<List<double>>

Time: 00:00:05.7941351

Type: double[rows * columns]

Time: 00:00:06.0547118

Running the Code:

int rows = 10000;
int columns = 10000;

IMatrix Matrix = new IMatrix(rows, columns);

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();


for (int r = 0; r < Matrix.Rows; r++)
    for (int c = 0; c < Matrix.Columns; c++)
        Matrix[r, c] = Math.E;

for (int r = 0; r < Matrix.Rows; r++)
    for (int c = 0; c < Matrix.Columns; c++)
        Matrix[r, c] *= -Math.Log(Math.E);


stopwatch.Stop();
TimeSpan ts = stopwatch.Elapsed;

Console.WriteLine(ts.ToString());

I do wish we had some top notch Hardware Accelerated Matrix Classes like the .NET Team have done with the System.Numerics.Vectors Class!

C# could be the best ML Language with a bit more work in this area!

How to check if a number is a power of 2

bool isPow2 = ((x & ~(x-1))==x)? !!x : 0;

Setting a property by reflection with a string value

You can use a type converter (no error checking):

Ship ship = new Ship();
string value = "5.5";
var property = ship.GetType().GetProperty("Latitude");
var convertedValue = property.Converter.ConvertFrom(value);
property.SetValue(self, convertedValue);

In terms of organizing the code, you could create a kind-of mixin that would result in code like this:

Ship ship = new Ship();
ship.SetPropertyAsString("Latitude", "5.5");

This would be achieved with this code:

public interface MPropertyAsStringSettable { }
public static class PropertyAsStringSettable {
  public static void SetPropertyAsString(
    this MPropertyAsStringSettable self, string propertyName, string value) {
    var property = TypeDescriptor.GetProperties(self)[propertyName];
    var convertedValue = property.Converter.ConvertFrom(value);
    property.SetValue(self, convertedValue);
  }
}

public class Ship : MPropertyAsStringSettable {
  public double Latitude { get; set; }
  // ...
}

MPropertyAsStringSettable can be reused for many different classes.

You can also create your own custom type converters to attach to your properties or classes:

public class Ship : MPropertyAsStringSettable {
  public Latitude Latitude { get; set; }
  // ...
}

[TypeConverter(typeof(LatitudeConverter))]
public class Latitude { ... }

AngularJS: Insert HTML from a string

you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"'),if you want to know more detail, please refer to $sce

Adding HTML entities using CSS content

Use the hex code for a non-breaking space. Something like this:

.breadcrumbs a:before {
    content: '>\00a0';
}

Get the name of a pandas DataFrame

You can name the dataframe with the following, and then call the name wherever you like:

import pandas as pd
df = pd.DataFrame( data=np.ones([4,4]) )
df.name = 'Ones'

print df.name
>>>
Ones

Hope that helps.

get current date with 'yyyy-MM-dd' format in Angular 4

In Controller ,

 var DateObj = new Date();

 $scope.YourParam = DateObj.getFullYear() + '-' + ('0' + (DateObj.getMonth() + 1)).slice(-2) + '-' + ('0' + DateObj.getDate()).slice(-2);

How to replace case-insensitive literal substrings in Java

String target = "FOOBar";
target = target.replaceAll("(?i)foo", "");
System.out.println(target);

Output:

Bar

It's worth mentioning that replaceAll treats the first argument as a regex pattern, which can cause unexpected results. To solve this, also use Pattern.quote as suggested in the comments.

hardcoded string "row three", should use @string resource

You can go to Design mode and select "Fix" at the bottom of the warning. Then a pop up will appear (seems like it's going to register the new string) and voila, the error is fixed.

PHP function to generate v4 UUID

If you use CakePHP you can use their method CakeText::uuid(); from the CakeText class to generate a RFC4122 uuid.

Is it possible to have placeholders in strings.xml for runtime values?

In your string file use this

<string name="redeem_point"> You currently have %s points(%s points = 1 %s)</string>

And in your code use as accordingly

coinsTextTV.setText(String.format(getContext().getString(R.string.redeem_point), rewardPoints.getReward_points()
                        , rewardPoints.getConversion_rate(), getString(R.string.rs)));

What causes HttpHostConnectException?

In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.

how to prevent css inherit

While this isn't currently available, this fascinating article discusses the use of the Shadow DOM, which is a technique used by browsers to limit how far cascading style sheets cascade, so to speak. He doesn't provide any APIs, as it seems that there are no current libraries able to provide access to this part of the DOM, but it's worth a look. There are links to mailing lists at the bottom of the article if this intrigues you.

Hyper-V: Create shared folder between host and guest with internal network

  • Open Hyper-V Manager
  • Create a new internal virtual switch (e.g. "Internal Network Connection")
  • Go to your Virtual Machine and create a new Network Adapter -> choose "Internal Network Connection" as virtual switch
  • Start the VM
  • Assign both your host as well as guest an IP address as well as a Subnet mask (IP4, e.g. 192.168.1.1 (host) / 192.168.1.2 (guest) and 255.255.255.0)
  • Open cmd both on host and guest and check via "ping" if host and guest can reach each other (if this does not work disable/enable the network adapter via the network settings in the control panel, restart...)
  • If successfull create a folder in the VM (e.g. "VMShare"), right-click on it -> Properties -> Sharing -> Advanced Sharing -> checkmark "Share this folder" -> Permissions -> Allow "Full Control" -> Apply
  • Now you should be able to reach the folder via the host -> to do so: open Windows Explorer -> enter the path to the guest (\192.168.1.xx...) in the address line -> enter the credentials of the guest (Choose "Other User" - it can be necessary to change the domain therefore enter ".\"[username] and [password])

There is also an easy way for copying via the clipboard:

  • If you start your VM and go to "View" you can enable "Enhanced Session". If you do it is not possible to drag and drop but to copy and paste.

Enhanced Session

How do I start my app on startup?

Another approach is to use android.intent.action.USER_PRESENT instead of android.intent.action.BOOT_COMPLETED to avoid slow downs during the boot process. But this is only true if the user has enabled the lock Screen - otherwise this intent is never broadcasted.

Reference blog - The Problem With Android’s ACTION_USER_PRESENT Intent

How do I start an activity from within a Fragment?

Use the Base Context of the Activity in which your fragment resides to start an Intent.

Intent j = new Intent(fBaseCtx, NewactivityName.class);         
startActivity(j);

where fBaseCtx is BaseContext of your current activity. You can get it as fBaseCtx = getBaseContext();

Change priorityQueue to max priorityqueue

You can try pushing elements with reverse sign. Eg: To add a=2 & b=5 and then poll b=5.

PriorityQueue<Integer>  pq = new PriorityQueue<>();
pq.add(-a);
pq.add(-b);
System.out.print(-pq.poll());

Once you poll the head of the queue, reverse the sign for your usage. This will print 5 (larger element). Can be used in naive implementations. Definitely not a reliable fix. I don't recommend it.

error: This is probably not a problem with npm. There is likely additional logging output above

Finally, I found a solution to this problem without reinstalling npm and I'm posting it because in future it will help someone, Most of the time this error occurs javascript heap went out of the memory. As the error says itself this is not a problem with npm. Only we have to do is

instead of,

npm  run build -prod

extend the javascript memory by following,

node --max_old_space_size=4096 node_modules/@angular/cli/bin/ng build --prod

How to install MinGW-w64 and MSYS2?

Unfortunately, the MinGW-w64 installer you used sometimes has this issue. I myself am not sure about why this happens (I think it has something to do with Sourceforge URL redirection or whatever that the installer currently can't handle properly enough).

Anyways, if you're already planning on using MSYS2, there's no need for that installer.

  1. Download MSYS2 from this page (choose 32 or 64-bit according to what version of Windows you are going to use it on, not what kind of executables you want to build, both versions can build both 32 and 64-bit binaries).

  2. After the install completes, click on the newly created "MSYS2 Shell" option under either MSYS2 64-bit or MSYS2 32-bit in the Start menu. Update MSYS2 according to the wiki (although I just do a pacman -Syu, ignore all errors and close the window and open a new one, this is not recommended and you should do what the wiki page says).

  3. Install a toolchain

    a) for 32-bit:

    pacman -S mingw-w64-i686-gcc
    

    b) for 64-bit:

    pacman -S mingw-w64-x86_64-gcc
    
  4. install any libraries/tools you may need. You can search the repositories by doing

    pacman -Ss name_of_something_i_want_to_install
    

    e.g.

    pacman -Ss gsl
    

    and install using

    pacman -S package_name_of_something_i_want_to_install
    

    e.g.

    pacman -S mingw-w64-x86_64-gsl
    

    and from then on the GSL library is automatically found by your MinGW-w64 64-bit compiler!

  5. Open a MinGW-w64 shell:

    a) To build 32-bit things, open the "MinGW-w64 32-bit Shell"

    b) To build 64-bit things, open the "MinGW-w64 64-bit Shell"

  6. Verify that the compiler is working by doing

    gcc -v
    

If you want to use the toolchains (with installed libraries) outside of the MSYS2 environment, all you need to do is add <MSYS2 root>/mingw32/bin or <MSYS2 root>/mingw64/bin to your PATH.

Sending emails with Javascript

The problem with the very idea is that the user has to have an email client, which is not the case if he rely on webmails, which is the case for many users. (at least there was no turn-around to redirect to this webmail when I investigated the issue a dozen years ago).

That's why the normal solution is to rely on php mail() for sending emails (server-side, then).

But if nowadays "email client" is always set, automatically, potentially to a webmail client, I'll be happy to know.

path.join vs path.resolve with __dirname

From the doc for path.resolve:

The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.

But path.join keeps trailing slashes

So

__dirname = '/';
path.resolve(__dirname, 'foo/'); // '/foo'
path.join(__dirname, 'foo/'); // '/foo/'

numpy: most efficient frequency counts for unique values in an array

I was also interested in this, so I did a little performance comparison (using perfplot, a pet project of mine). Result:

y = np.bincount(a)
ii = np.nonzero(y)[0]
out = np.vstack((ii, y[ii])).T

is by far the fastest. (Note the log-scaling.)

enter image description here


Code to generate the plot:

import numpy as np
import pandas as pd
import perfplot
from scipy.stats import itemfreq


def bincount(a):
    y = np.bincount(a)
    ii = np.nonzero(y)[0]
    return np.vstack((ii, y[ii])).T


def unique(a):
    unique, counts = np.unique(a, return_counts=True)
    return np.asarray((unique, counts)).T


def unique_count(a):
    unique, inverse = np.unique(a, return_inverse=True)
    count = np.zeros(len(unique), np.int)
    np.add.at(count, inverse, 1)
    return np.vstack((unique, count)).T


def pandas_value_counts(a):
    out = pd.value_counts(pd.Series(a))
    out.sort_index(inplace=True)
    out = np.stack([out.keys().values, out.values]).T
    return out


perfplot.show(
    setup=lambda n: np.random.randint(0, 1000, n),
    kernels=[bincount, unique, itemfreq, unique_count, pandas_value_counts],
    n_range=[2 ** k for k in range(26)],
    logx=True,
    logy=True,
    xlabel="len(a)",
)

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

Example query: SELECT TO_CHAR(TO_DATE('2017-08-23','YYYY-MM-DD'), 'MM/DD/YYYY') FROM dual;

Getting text from td cells with jQuery

I would give your tds a specific class, e.g. data-cell, and then use something like this:

$("td.data-cell").each(function () {
    // 'this' is now the raw td DOM element
    var txt = $(this).html();
});

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

The idea is that for speed and cache considerations, operands should be read from addresses aligned to their natural size. To make this happen, the compiler pads structure members so the following member or following struct will be aligned.

struct pixel {
    unsigned char red;   // 0
    unsigned char green; // 1
    unsigned int alpha;  // 4 (gotta skip to an aligned offset)
    unsigned char blue;  // 8 (then skip 9 10 11)
};

// next offset: 12

The x86 architecture has always been able to fetch misaligned addresses. However, it's slower and when the misalignment overlaps two different cache lines, then it evicts two cache lines when an aligned access would only evict one.

Some architectures actually have to trap on misaligned reads and writes, and early versions of the ARM architecture (the one that evolved into all of today's mobile CPUs) ... well, they actually just returned bad data on for those. (They ignored the low-order bits.)

Finally, note that cache lines can be arbitrarily large, and the compiler doesn't attempt to guess at those or make a space-vs-speed tradeoff. Instead, the alignment decisions are part of the ABI and represent the minimum alignment that will eventually evenly fill up a cache line.

TL;DR: alignment is important.

Insert multiple values using INSERT INTO (SQL Server 2005)

You can also use the following syntax:-

INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO

From here

How to sort a HashMap in Java

Sorting HashMap by value in Java:

public class HashMapSortByValue {
    public static void main(String[] args) {

        HashMap<Long,String> unsortMap = new HashMap<Long,String>();
            unsortMap.put(5l,"B");
            unsortMap.put(8l,"A");
            unsortMap.put(2l, "D");
            unsortMap.put(7l,"C" );

            System.out.println("Before sorting......");
            System.out.println(unsortMap);

            HashMap<Long,String> sortedMapAsc = sortByComparator(unsortMap);
            System.out.println("After sorting......");
            System.out.println(sortedMapAsc);

    }

    public static HashMap<Long,String> sortByComparator(
            HashMap<Long,String> unsortMap) {

            List<Map.Entry<Long,String>> list = new LinkedList<Map.Entry<Long,String>>(
                unsortMap.entrySet());

            Collections.sort(list, new Comparator<Map.Entry<Long,String>> () {
                public int compare(Map.Entry<Long,String> o1, Map.Entry<Long,String> o2) {
                    return o1.getValue().compareTo(o2.getValue());
                }
            });

            HashMap<Long,String> sortedMap = new LinkedHashMap<Long,String>();
            for (Entry<Long,String> entry : list) {
              sortedMap.put(entry.getKey(), entry.getValue());
            }
            return sortedMap;
          }

}

How can I get input radio elements to horizontally align?

This also works like a charm

_x000D_
_x000D_
<form>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio" checked>Option 1_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 2_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 3_x000D_
    </label>_x000D_
  </form>
_x000D_
_x000D_
_x000D_

Assigning strings to arrays of characters

Note that you can still do:

s[0] = 'h';
s[1] = 'e';
s[2] = 'l';
s[3] = 'l';
s[4] = 'o';
s[5] = '\0';

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

Give:

keytool -list -keystore ~/.android/debug.keystore

Also in your line there is a space in keystore. Please check it.

How do I get column datatype in Oracle with PL-SQL with low privileges?

Quick and dirty way (e.g. to see how data is stored in oracle)

SQL> select dump(dummy) dump_dummy, dummy
     , dump(10) dump_ten
from dual

DUMP_DUMMY       DUMMY DUMP_TEN            
---------------- ----- --------------------
Typ=1 Len=1: 88  X     Typ=2 Len=2: 193,11 
1 row selected.

will show that dummy column in table sys.dual has typ=1 (varchar2), while 10 is Typ=2 (number).

Android Use Done button on Keyboard to click button

Try this for Xamarin.Android (Cross Platform)

edittext.EditorAction += (object sender, TextView.EditorActionEventArgs e) {
       if (e.ActionId.Equals (global::Android.Views.InputMethods.ImeAction.Done)) {
           //TODO Something
       }
};

How to convert xml into array in php?

$array = json_decode(json_encode((array)simplexml_load_string($xml)),true);

Want custom title / image / description in facebook share link from a flash app

2016 Update

Use the Sharing Debugger to figure out what your problems are.

Make sure you're following the Facebook Sharing Best Practices.

Make sure you're using the Open Graph Markup correctly.

Original Answer

I agree with what has already been said here, but per documentation on the Facebook developer site, you might want to use the following meta tags.

<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />

If you are not able to accomplish your goal with meta tags and you need a URL embedded version, see @Lelis718's answer below.

How to get images in Bootstrap's card to be the same height/width?

I dont believe you can without cropping them, I mean you could make the divs the same height by using jquery however this will not make the images the same size.

You could take a look at using Masonry which will make this look decent.

http://masonry.desandro.com/

Get the string value from List<String> through loop for display

pst = con.createStatement(); ResultSet resultSet= pst.executeQuery(query);

     String str1 = "<table>";
     int i = 1;
    while(resultSet.next()) {
             str1+= "</tr><td>"+i+"</td>"+
             "<td>"+resultSet.getString("first_name")+"</td>"+
             "<td>"+resultSet.getString("last_name")+"</td>"+
             "<td>"+resultSet.getString("email_id")+"</td>"+
             "<td>"+resultSet.getString("dob") +"</td>"+

             "</tr>";
        i++;

    }
        str1 =str1+"<table>";

    model.addAttribute("list",str1);

    return "userlist";  //Sending to views .jsp 

LINQ query to select top five

var list = (from t in ctn.Items
           where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
           orderby t.Delivery.SubmissionDate
           select t).Take(5);

Difference between Dictionary and Hashtable

Dictionary is typed (so valuetypes don't need boxing), a Hashtable isn't (so valuetypes need boxing). Hashtable has a nicer way of obtaining a value than dictionary IMHO, because it always knows the value is an object. Though if you're using .NET 3.5, it's easy to write an extension method for dictionary to get similar behavior.

If you need multiple values per key, check out my sourcecode of MultiValueDictionary here: multimap in .NET

How to apply CSS page-break to print a table with lots of rows?

Wherever you want to apply a break, either a table or tr, you needs to give a class for ex. page-break with CSS as mentioned below:

/* class works for table row */
table tr.page-break{
  page-break-after:always
} 

<tr class="page-break">

/* class works for table */
table.page-break{
  page-break-after:always
}

<table class="page-break">

and it will work as you required

Alternatively, you can also have div structure for same:

CSS:

@media all {
 .page-break  { display: none; }
}

@media print {
 .page-break  { display: block; page-break-before: always; }
}

Div:

<div class="page-break"></div>

Using moment.js to convert date to string "MM/dd/yyyy"

Try this:

var momentObj = $("#start_ts").datepicker("getDate");

var yourDate = momentObj.format('L');

Setting unique Constraint with fluent API?

Unfortunately this is not supported in Entity Framework. It was on the roadmap for EF 6, but it got pushed back: Workitem 299: Unique Constraints (Unique Indexes)

Counting how many times a certain char appears in a string before any other char appears

The simplest approach would be to use LINQ:

var count = text.TakeWhile(c => c == '$').Count();

There are certainly more efficient approaches, but that's probably the simplest.

Access Control Request Headers, is added to header in AJAX request with jQuery

Because you send custom headers so your CORS request is not a simple request, so the browser first sends a preflight OPTIONS request to check that the server allows your request.

Enter image description here

If you turn on CORS on the server then your code will work. You can also use JavaScript fetch instead (here)

_x000D_
_x000D_
let url='https://server.test-cors.org/server?enable=true&status=200&methods=POST&headers=My-First-Header,My-Second-Header';_x000D_
_x000D_
_x000D_
$.ajax({_x000D_
    type: 'POST',_x000D_
    url: url,_x000D_
    headers: {_x000D_
        "My-First-Header":"first value",_x000D_
        "My-Second-Header":"second value"_x000D_
    }_x000D_
}).done(function(data) {_x000D_
    alert(data[0].request.httpMethod + ' was send - open chrome console> network to see it');_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Here is an example configuration which turns on CORS on nginx (nginx.conf file):

_x000D_
_x000D_
location ~ ^/index\.php(/|$) {_x000D_
   ..._x000D_
    add_header 'Access-Control-Allow-Origin' "$http_origin" always;_x000D_
    add_header 'Access-Control-Allow-Credentials' 'true' always;_x000D_
    if ($request_method = OPTIONS) {_x000D_
        add_header 'Access-Control-Allow-Origin' "$http_origin"; # DO NOT remove THIS LINES (doubled with outside 'if' above)_x000D_
        add_header 'Access-Control-Allow-Credentials' 'true';_x000D_
        add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days_x000D_
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';_x000D_
        add_header 'Access-Control-Allow-Headers' 'My-First-Header,My-Second-Header,Authorization,Content-Type,Accept,Origin';_x000D_
        add_header 'Content-Length' 0;_x000D_
        add_header 'Content-Type' 'text/plain charset=UTF-8';_x000D_
        return 204;_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Here is an example configuration which turns on CORS on Apache (.htaccess file)

_x000D_
_x000D_
# ------------------------------------------------------------------------------_x000D_
# | Cross-domain Ajax requests                                                 |_x000D_
# ------------------------------------------------------------------------------_x000D_
_x000D_
# Enable cross-origin Ajax requests._x000D_
# http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity_x000D_
# http://enable-cors.org/_x000D_
_x000D_
# <IfModule mod_headers.c>_x000D_
#    Header set Access-Control-Allow-Origin "*"_x000D_
# </IfModule>_x000D_
_x000D_
#Header set Access-Control-Allow-Origin "http://example.com:3000"_x000D_
#Header always set Access-Control-Allow-Credentials "true"_x000D_
_x000D_
Header set Access-Control-Allow-Origin "*"_x000D_
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"_x000D_
Header always set Access-Control-Allow-Headers "My-First-Header,My-Second-Header,Authorization, content-type, csrf-token"
_x000D_
_x000D_
_x000D_

Distinct in Linq based on only one field of the table

You can try this:table1.GroupBy(t => t.Text).Select(shape => shape.r)).Distinct();

Convert a RGB Color Value to a Hexadecimal String

This is an adapted version of the answer given by Vivien Barousse with the update from Vulcan applied. In this example I use sliders to dynamically retreive the RGB values from three sliders and display that color in a rectangle. Then in method toHex() I use the values to create a color and display the respective Hex color code.

This example does not include the proper constraints for the GridBagLayout. Though the code will work, the display will look strange.

public class HexColor
{

  public static void main (String[] args)
  {
   JSlider sRed = new JSlider(0,255,1);
   JSlider sGreen = new JSlider(0,255,1);
   JSlider sBlue = new JSlider(0,255,1);
   JLabel hexCode = new JLabel();
   JPanel myPanel = new JPanel();
   GridBagLayout layout = new GridBagLayout();
   JFrame frame = new JFrame();

   //set frame to organize components using GridBagLayout 
   frame.setLayout(layout);

   //create gray filled rectangle 
   myPanel.paintComponent();
   myPanel.setBackground(Color.GRAY);

   //In practice this code is replicated and applied to sGreen and sBlue. 
   //For the sake of brevity I only show sRed in this post.
   sRed.addChangeListener(
         new ChangeListener()
         {
             @Override
             public void stateChanged(ChangeEvent e){
                 myPanel.setBackground(changeColor());
                 myPanel.repaint();
                 hexCode.setText(toHex());
         }
         }
     );
   //add each component to JFrame
   frame.add(myPanel);
   frame.add(sRed);
   frame.add(sGreen);
   frame.add(sBlue);
   frame.add(hexCode);
} //end of main

  //creates JPanel filled rectangle
  protected void paintComponent(Graphics g)
  {
      super.paintComponent(g);
      g.drawRect(360, 300, 10, 10);
      g.fillRect(360, 300, 10, 10);
  }

  //changes the display color in JPanel
  private Color changeColor()
  {
    int r = sRed.getValue();
    int b = sBlue.getValue();
    int g = sGreen.getValue();
    Color c;
    return  c = new Color(r,g,b);
  }

  //Displays hex representation of displayed color
  private String toHex()
  {
      Integer r = sRed.getValue();
      Integer g = sGreen.getValue();
      Integer b = sBlue.getValue();
      Color hC;
      hC = new Color(r,g,b);
      String hex = Integer.toHexString(hC.getRGB() & 0xffffff);
      while(hex.length() < 6){
          hex = "0" + hex;
      }
      hex = "Hex Code: #" + hex;
      return hex;
  }
}

A huge thank you to both Vivien and Vulcan. This solution works perfectly and was super simple to implement.

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

XmlSerializer xs = new XmlSerializer(typeof(User), new XmlRootAttribute("yourRootName")); 

.rar, .zip files MIME Type

As extension might contain more or less that three characters the following will test for an extension regardless of the length of it.

Try this:

$allowedExtensions = array( 'mkv', 'mp3', 'flac' );

$temp = explode(".", $_FILES[$file]["name"]);
$extension = strtolower(end($temp));

if( in_array( $extension, $allowedExtensions ) ) { ///

to check for all characters after the last '.'

How do you select the entire excel sheet with Range using VBA?

Refering to the very first question, I am looking into the same. The result I get, recording a macro, is, starting by selecting cell A76:

Sub find_last_row()
    Range("A76").Select
    Range(Selection, Selection.End(xlDown)).Select
End Sub

Determining if a number is prime

I came up with this:

int counter = 0;

bool checkPrime(int x) {
   for (int y = x; y > 0; y--){
      if (x%y == 0) {
         counter++;
      }
   }
   if (counter == 2) {
      counter = 0; //resets counter for next input
      return true; //if its only divisible by two numbers (itself and one) its a prime
   }
   else counter = 0;
        return false;
}

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

The 'best' way to do this would be to set a property on a view object once the update is successful. You can then access this property in the view and inform the user accordingly.

Having said that it would be possible to trigger an alert from the controller code by doing something like this -

public ActionResult ActionName(PostBackData postbackdata)
{
    //your DB code
    return new JavascriptResult { Script = "alert('Successfully registered');" };
}

You can find further info in this question - How to display "Message box" using MVC3 controller

What's the strangest corner case you've seen in C# or .NET?

I think the answer to the question is because .net uses string interning something that might cause equal strings to point to the same object (since a strings are mutable this is not a problem)

(I'm not talking about the overridden equality operator on the string class)

How can I create a correlation matrix in R?

An example,

 d <- data.frame(x1=rnorm(10),
                 x2=rnorm(10),
                 x3=rnorm(10))
cor(d) # get correlations (returns matrix)

Are there any free Xml Diff/Merge tools available?

While this is not a GUI tool, my quick tests indicated that diffxml has some promise. The author appears to have thought about the complexities of representing diffs for nested elements in a standardized way (his DUL - Delta Update Language specification).

Installing and running his tools, I can say that the raw text output is quite clear and concise. It doesn't offer the same degree of immediate apprehension as a GUI tool, but given that the output is standardized as DUL, perhaps you would be able to take that and build a tool to generate a visual representation. I'd certainly love to see one.

The author's "links" section does reference a few other XML differencing tools, but as you mentioned in your post, they're all proprietary.

How to force a hover state with jQuery?

I think the best solution I have come across is on this stackoverflow. This short jQuery code allows all your hover effects to show on click or touch..
No need to add anything within the function.

$('body').on('touchstart', function() {});

Hope this helps.

Apache Cordova - uninstall globally

Try sudo npm uninstall cordova -g to uninstall it globally and then just npm install cordova without the -g flag after cding to the local app directory

JQuery Find #ID, RemoveClass and AddClass

Try this

$('#testID').addClass('nameOfClass');

or

$('#testID').removeClass('nameOfClass');

Getting Current time to display in Label. VB.net

Try This.....

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load    
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Label12.Text = TimeOfDay.ToString("h:mm:ss tt")
End Sub

Hiding and Showing TabPages in tabControl

Always codes should be simple and easy to perform tasks for fast performance and for good reliability.

To add a page to a TabControl, the following code is enough.

If Tabcontrol1.Controls.Contains(TabPage1) Then
else Tabcontrol1.Controls.Add(TabPage1) End If

To remove a page from a TabControl, the following code is enough.

If Tabcontrol1.Controls.Contains(TabPage1) Then Tabcontrol1.Controls.Remove(TabPage1) End If

I wish to thank Stackoverflow.com for providing sincere help to programmers.

Various ways to remove local Git changes

Use:

git checkout -- <file>

To discard the changes in the working directory.

Is there a way to create key-value pairs in Bash script?

If you can use a simple delimiter, a very simple oneliner is this:

for i in a,b c_s,d ; do 
  KEY=${i%,*};
  VAL=${i#*,};
  echo $KEY" XX "$VAL;
done

Hereby i is filled with character sequences like "a,b" and "c_s,d". each separated by spaces. After the do we use parameter substitution to extract the part before the comma , and the part after it.

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

check below link in which you can download suitable AjaxControlToolkit which suits your .NET version.

http://ajaxcontroltoolkit.codeplex.com/releases/view/43475

AjaxControlToolkit.Binary.NET4.zip - used for .NET 4.0

AjaxControlToolkit.Binary.NET35.zip - used for .NET 3.5

How to download python from command-line?

Well if you are getting into a linux machine you can use the package manager of that linux distro.

If you are using Ubuntu just use apt-get search python, check the list and do apt-get install python2.7 (not sure if python2.7 or python-2.7, check the list)

You could use yum in fedora and do the same.

if you want to install it on your windows machine i dont know any package manager, i would download the wget for windows, donwload the package from python.org and install it

Link to a section of a webpage

Simple:

Use <section>.

and use <a href="page.html#tips">Visit the Useful Tips Section</a>

w3school.com/html_links

How to determine the encoding of text?

Here is an example of reading and taking at face value a chardet encoding prediction, reading n_lines from the file in the event it is large.

chardet also gives you a probability (i.e. confidence) of it's encoding prediction (haven't looked how they come up with that), which is returned with its prediction from chardet.predict(), so you could work that in somehow if you like.

def predict_encoding(file_path, n_lines=20):
    '''Predict a file's encoding using chardet'''
    import chardet

    # Open the file as binary data
    with open(file_path, 'rb') as f:
        # Join binary lines for specified number of lines
        rawdata = b''.join([f.readline() for _ in range(n_lines)])

    return chardet.detect(rawdata)['encoding']

Angular + Material - How to refresh a data source (mat-table)

This worked for me:

refreshTableSorce() {
    this.dataSource = new MatTableDataSource<Element>(this.newSource);
}

Authentication failed to bitbucket

I was using below command

git clone -b branch-name https://<username>@bitbucket.org/<repository>.git

Issue got resolved after adding password with username (see below command):

git clone -b branch-name https://<username>:<password>@bitbucket.org/<repository>.git

How to make the tab character 4 spaces instead of 8 spaces in nano?

If you use nano with a language like python (as in your example) it's also a good idea to convert tabs to spaces.

Edit your ~/.nanorc file (or create it) and add:

set tabsize 4
set tabstospaces

If you already got a file with tabs and want to convert them to spaces i recommend the expandcommand (shell):

expand -4 input.py > output.py

downloading all the files in a directory with cURL

If you're not bound to curl, you might want to use wget in recursive mode but restricting it to one level of recursion, try the following;

wget --no-verbose --no-parent --recursive --level=1\
--no-directories --user=login --password=pass ftp://ftp.myftpsite.com/
  • --no-parent : Do not ever ascend to the parent directory when retrieving recursively.
  • --level=depth : Specify recursion maximum depth level depth. The default maximum depth is five layers.
  • --no-directories : Do not create a hierarchy of directories when retrieving recursively.

How to add external JS scripts to VueJS Components

You can load the script you need with a promise based solution:

export default {
  data () {
    return { is_script_loading: false }
  },
  created () {
    // If another component is already loading the script
    this.$root.$on('loading_script', e => { this.is_script_loading = true })
  },
  methods: {
    load_script () {
      let self = this
      return new Promise((resolve, reject) => {

        // if script is already loading via another component
        if ( self.is_script_loading ){
          // Resolve when the other component has loaded the script
          this.$root.$on('script_loaded', resolve)
          return
        }

        let script = document.createElement('script')
        script.setAttribute('src', 'https://www.google.com/recaptcha/api.js')
        script.async = true
        
        this.$root.$emit('loading_script')

        script.onload = () => {
          /* emit to global event bus to inform other components
           * we are already loading the script */
          this.$root.$emit('script_loaded')
          resolve()
        }

        document.head.appendChild(script)

      })

    },
  
    async use_script () {
      try {
        await this.load_script()
        // .. do what you want after script has loaded
      } catch (err) { console.log(err) }

    }
  }
}

Please note that this.$root is a little hacky and you should use a vuex or eventHub solution for the global events instead.

You would make the above into a component and use it wherever needed, it will only load the script when used.

NOTE: This is a Vue 2.x based solution. Vue 3 has stopped supporting $on.

Set environment variables on Mac OS X Lion

Here's a bit more information specifically regarding the PATH variable in Lion OS 10.7.x:

If you need to set the PATH globally, the PATH is built by the system in the following order:

  1. Parsing the contents of the file /private/etc/paths, one path per line
  2. Parsing the contents of the folder /private/etc/paths.d. Each file in that folder can contain multiple paths, one path per line. Load order is determined by the file name first, and then the order of the lines in the file.
  3. A setenv PATH statement in /private/etc/launchd.conf, which will append that path to the path already built in #1 and #2 (you must not use $PATH to reference the PATH variable that has been built so far). But, setting the PATH here is completely unnecessary given the other two options, although this is the place where other global environment variables can be set for all users.

These paths and variables are inherited by all users and applications, so they are truly global -- logging out and in will not reset these paths -- they're built for the system and are created before any user is given the opportunity to login, so changes to these require a system restart to take effect.

BTW, a clean install of OS 10.7.x Lion doesn't have an environment.plist that I can find, so it may work but may also be deprecated.

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

Resolution:

Refer to this link: As there are various options to shut the warning off depending on the minSdkVersion, it is set below 20:

 android {
     defaultConfig {
         ...
         minSdkVersion 15 
         targetSdkVersion 26
         multiDexEnabled true
     }
     ... }

 dependencies {   compile 'com.android.support:multidex:1.0.3' }

If you have a minSdkVersion greater than 20 in your build.gradle set use the following to shut down the warning:

  android {
      defaultConfig {
          ...
          minSdkVersion 21 
          targetSdkVersion 26
          multiDexEnabled true
      }
      ... }

Update dependencies as follows:

     dependencies {
        implementation 'com.android.support:multidex:1.0.3'
     }

Again the only difference is the keywords in dependencies:

minSdkVersion below 20: use compile

minSdkVersion above 20: use implementation

  1. I hope this was helpful, please upvote if it solved your issue, Thank you for your time.
  2. Also for more info, on why this occurs, please read the first paragraph in the link, it will explain thoroughly why? and what does this warning mean.

Understanding the results of Execute Explain Plan in Oracle SQL Developer

The CBO builds a decision tree, estimating the costs of each possible execution path available per query. The costs are set by the CPU_cost or I/O_cost parameter set on the instance. And the CBO estimates the costs, as best it can with the existing statistics of the tables and indexes that the query will use. You should not tune your query based on cost alone. Cost allows you to understand WHY the optimizer is doing what it does. Without cost you could figure out why the optimizer chose the plan it did. Lower cost does not mean a faster query. There are cases where this is true and there will be cases where this is wrong. Cost is based on your table stats and if they are wrong the cost is going to be wrong.

When tuning your query, you should take a look at the cardinality and the number of rows of each step. Do they make sense? Is the cardinality the optimizer is assuming correct? Is the rows being return reasonable. If the information present is wrong then its very likely the optimizer doesn't have the proper information it needs to make the right decision. This could be due to stale or missing statistics on the table and index as well as cpu-stats. Its best to have stats updated when tuning a query to get the most out of the optimizer. Knowing your schema is also of great help when tuning. Knowing when the optimizer chose a really bad decision and pointing it in the correct path with a small hint can save a load of time.

ASP.NET MVC Razor render without encoding

Use @Html.Raw() with caution as you may cause more trouble with encoding and security. I understand the use case as I had to do this myself, but carefully... Just avoid allowing all text through. For example only preserve/convert specific character sequences and always encode the rest:

@Html.Raw(Html.Encode(myString).Replace("\n", "<br/>"))

Then you have peace of mind that you haven't created a potential security hole and any special/foreign characters are displayed correctly in all browsers.

Scroll to the top of the page after render in react.js

Finally.. I used:

componentDidMount() {
  window.scrollTo(0, 0)
}

EDIT: React v16.8+

useEffect(() => {
  window.scrollTo(0, 0)
}, [])

How to add a button dynamically in Android?

I've used this (or very similar) code to add several TextViews to a LinearLayout:

// Quick & dirty pre-made list of text labels...
String names[] = {"alpha", "beta", "gamma", "delta", "epsilon"};
int namesLength = 5;

// Create a LayoutParams...
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LinearLayout.LayoutParams.WRAP_CONTENT, 
    LinearLayout.LayoutParams.FILL_PARENT);

// Get existing UI containers...
LinearLayout nameButtons = (LinearLayout) view.findViewById(R.id.name_buttons);
TextView label = (TextView) view.findViewById(R.id.master_label);

TextView tv;

for (int i = 0; i < namesLength; i++) {
    // Grab the name for this "button"
    final String name = names[i];

    tv = new TextView(context);
    tv.setText(name);

    // TextViews CAN have OnClickListeners
    tv.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            label.setText("Clicked button for " + name); 
        }
    });

    nameButtons.addView(tv, params);
}

The main difference between this and dicklaw795's code is it doesn't set() and re-get() the ID for each TextView--I found it unnecessary, although I may need it to later identify each button in a common handler routine (e.g. one called by onClick() for each TextView).

UICollectionView Set number of columns

CollectionViews are very powerful, and they come at a price. Lots, and lots of options. As omz said:

there are multiple ways you could change the number of columns

I'd suggest implementing the <UICollectionViewDelegateFlowLayout> Protocol, giving you access to the following methods in which you can have greater control over the layout of your UICollectionView, without the need for subclassing it:

  • collectionView:layout:insetForSectionAtIndex:
  • collectionView:layout:minimumInteritemSpacingForSectionAtIndex:
  • collectionView:layout:minimumLineSpacingForSectionAtIndex:
  • collectionView:layout:referenceSizeForFooterInSection:
  • collectionView:layout:referenceSizeForHeaderInSection:
  • collectionView:layout:sizeForItemAtIndexPath:

Also, implementing the following method will force your UICollectionView to update it's layout on an orientation change: (say you wanted to re-size the cells for landscape and make them stretch)

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
                               duration:(NSTimeInterval)duration{

    [self.myCollectionView.collectionViewLayout invalidateLayout];
}

Additionally, here are 2 really good tutorials on UICollectionViews:

http://www.raywenderlich.com/22324/beginning-uicollectionview-in-ios-6-part-12

http://skeuo.com/uicollectionview-custom-layout-tutorial

Chrome desktop notification example

See also ServiceWorkerRegistration.showNotification

It appears that window.webkitNotifications has already been deprecated and removed. However, there's a new API, and it appears to work in the latest version of Firefox as well.

function notifyMe() {
  // Let's check if the browser supports notifications
  if (!("Notification" in window)) {
    alert("This browser does not support desktop notification");
  }

  // Let's check if the user is okay to get some notification
  else if (Notification.permission === "granted") {
    // If it's okay let's create a notification
    var notification = new Notification("Hi there!");
  }

  // Otherwise, we need to ask the user for permission
  // Note, Chrome does not implement the permission static property
  // So we have to check for NOT 'denied' instead of 'default'
  else if (Notification.permission !== 'denied') {
    Notification.requestPermission(function (permission) {

      // Whatever the user answers, we make sure we store the information
      if(!('permission' in Notification)) {
        Notification.permission = permission;
      }

      // If the user is okay, let's create a notification
      if (permission === "granted") {
        var notification = new Notification("Hi there!");
      }
    });
  } else {
    alert(`Permission is ${Notification.permission}`);
  }
}

codepen

MVC3 EditorFor readOnly

The EditorFor html helper does not have overloads that take HTML attributes. In this case, you need to use something more specific like TextBoxFor:

<div class="editor-field">
    @Html.TextBoxFor(model => model.userName, new 
        { disabled = "disabled", @readonly = "readonly" })
</div>

You can still use EditorFor, but you will need to have a TextBoxFor in a custom EditorTemplate:

public class MyModel
{
    [UIHint("userName")]
    public string userName { ;get; set; }
}

Then, in your Views/Shared/EditorTemplates folder, create a file userName.cshtml. In that file, put this:

@model string
@Html.TextBoxFor(m => m, new { disabled = "disabled", @readonly = "readonly" })

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

Count lines in large files

I have a 645GB text file, and none of the earlier exact solutions (e.g. wc -l) returned an answer within 5 minutes.

Instead, here is Python script that computes the approximate number of lines in a huge file. (My text file apparently has about 5.5 billion lines.) The Python script does the following:

A. Counts the number of bytes in the file.

B. Reads the first N lines in the file (as a sample) and computes the average line length.

C. Computes A/B as the approximate number of lines.

It follows along the line of Nico's answer, but instead of taking the length of one line, it computes the average length of the first N lines.

Note: I'm assuming an ASCII text file, so I expect the Python len() function to return the number of chars as the number of bytes.

Put this code into a file line_length.py:

#!/usr/bin/env python

# Usage:
# python line_length.py <filename> <N> 

import os
import sys
import numpy as np

if __name__ == '__main__':

    file_name = sys.argv[1]
    N = int(sys.argv[2]) # Number of first lines to use as sample.
    file_length_in_bytes = os.path.getsize(file_name)
    lengths = [] # Accumulate line lengths.
    num_lines = 0

    with open(file_name) as f:
        for line in f:
            num_lines += 1
            if num_lines > N:
                break
            lengths.append(len(line))

    arr = np.array(lengths)
    lines_count = len(arr)
    line_length_mean = np.mean(arr)
    line_length_std = np.std(arr)

    line_count_mean = file_length_in_bytes / line_length_mean

    print('File has %d bytes.' % (file_length_in_bytes))
    print('%.2f mean bytes per line (%.2f std)' % (line_length_mean, line_length_std))
    print('Approximately %d lines' % (line_count_mean))

Invoke it like this with N=5000.

% python line_length.py big_file.txt 5000

File has 645620992933 bytes.
116.34 mean bytes per line (42.11 std)
Approximately 5549547119 lines

So there are about 5.5 billion lines in the file.

Referencing system.management.automation.dll in Visual Studio

if it is 64bit them - C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell**3.0**

and version could be different

Converting Integers to Roman Numerals - Java

enum Numeral {
        I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000);
        int weight;

        Numeral(int weight) {
            this.weight = weight;
        }
    };

    public static String roman(long n) {

        if( n <= 0) {
            throw new IllegalArgumentException();
        }

        StringBuilder buf = new StringBuilder();

        final Numeral[] values = Numeral.values();
        for (int i = values.length - 1; i >= 0; i--) {
            while (n >= values[i].weight) {
                buf.append(values[i]);
                n -= values[i].weight;
            }
        }
        return buf.toString();
    }

    public static void test(long n) {
        System.out.println(n + " = " + roman(n));
    }

    public static void main(String[] args) {
        test(1999);
        test(25);
        test(944);
        test(0);
    }

Colorized grep -- viewing the entire file with highlighted matches

Here's my approach, inspired by @kepkin's solution:

# Adds ANSI colors to matched terms, similar to grep --color but without
# filtering unmatched lines. Example:
#   noisy_command | highlight ERROR INFO
#
# Each argument is passed into sed as a matching pattern and matches are
# colored. Multiple arguments will use separate colors.
#
# Inspired by https://stackoverflow.com/a/25357856
highlight() {
  # color cycles from 0-5, (shifted 31-36), i.e. r,g,y,b,m,c
  local color=0 patterns=()
  for term in "$@"; do
    patterns+=("$(printf 's|%s|\e[%sm\\0\e[0m|g' "${term//|/\\|}" "$(( color+31 ))")")
    color=$(( (color+1) % 6 ))
  done
  sed -f <(printf '%s\n' "${patterns[@]}")
}

This accepts multiple arguments (but doesn't let you customize the colors). Example:

$ noisy_command | highlight ERROR WARN

Saving timestamp in mysql table using php

If I know the database is MySQL, I'll use the NOW() function like this:

INSERT INTO table_name
   (id, name, created_at) 
VALUES 
   (1, 'Gordon', NOW()) 

JavaFX - create custom button with image

You just need to create your own class inherited from parent. Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.

public class ImageButton extends Parent {

    private static final Image NORMAL_IMAGE = ...;
    private static final Image PRESSED_IMAGE = ...;

    private final ImageView iv;

    public ImageButton() {
        this.iv = new ImageView(NORMAL_IMAGE);
        this.getChildren().add(this.iv);

        this.iv.setOnMousePressed(new EventHandler<MouseEvent>() {

            public void handle(MouseEvent evt) {
                iv.setImage(PRESSED_IMAGE);
            }

        });

        // TODO other event handlers like mouse up

    } 

}

How to submit a form using PhantomJS

As it was mentioned above CasperJS is the best tool to fill and send forms. Simplest possible example of how to fill & submit form using fill() function:

casper.start("http://example.com/login", function() {
//searches and fills the form with id="loginForm"
  this.fill('form#loginForm', {
    'login':    'admin',
    'password':    '12345678'
   }, true);
  this.evaluate(function(){
    //trigger click event on submit button
    document.querySelector('input[type="submit"]').click();
  });
});

How to quickly test some javascript code?

Following is a free list of tools you can use to check, test and verify your JS code:

  1. Google Code Playground
  2. JavaScript Sandbox
  3. jsbin
  4. jsfiddle
  5. pastebin
  6. jsdo.it
  7. firebug
  8. html5snippet.net

Hope this helps.

How to autosize a textarea using Prototype?

Facebook does it, when you write on people's walls, but only resizes vertically.

Horizontal resize strikes me as being a mess, due to word-wrap, long lines, and so on, but vertical resize seems to be pretty safe and nice.

None of the Facebook-using-newbies I know have ever mentioned anything about it or been confused. I'd use this as anecdotal evidence to say 'go ahead, implement it'.

Some JavaScript code to do it, using Prototype (because that's what I'm familiar with):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <script src="http://www.google.com/jsapi"></script>
        <script language="javascript">
            google.load('prototype', '1.6.0.2');
        </script>
    </head>

    <body>
        <textarea id="text-area" rows="1" cols="50"></textarea>

        <script type="text/javascript" language="javascript">
            resizeIt = function() {
              var str = $('text-area').value;
              var cols = $('text-area').cols;

              var linecount = 0;
              $A(str.split("\n")).each( function(l) {
                  linecount += Math.ceil( l.length / cols ); // Take into account long lines
              })
              $('text-area').rows = linecount + 1;
            };

            // You could attach to keyUp, etc. if keydown doesn't work
            Event.observe('text-area', 'keydown', resizeIt );

            resizeIt(); //Initial on load
        </script>
    </body>
</html>

PS: Obviously this JavaScript code is very naive and not well tested, and you probably don't want to use it on textboxes with novels in them, but you get the general idea.

How to ignore a particular directory or file for tslint?

As an addition

To disable all rules for the next line // tslint:disable-next-line

To disable specific rules for the next line: // tslint:disable-next-line:rule1 rule2...

To disable all rules for the current line: someCode(); // tslint:disable-line

To disable specific rules for the current line: someCode(); // tslint:disable-line:rule1

PIL image to array (numpy array to array) - Python

I think what you are looking for is:

list(im.getdata())

or, if the image is too big to load entirely into memory, so something like that:

for pixel in iter(im.getdata()):
    print pixel

from PIL documentation:

getdata

im.getdata() => sequence

Returns the contents of an image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.

Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations, including iteration and basic sequence access. To convert it to an ordinary sequence (e.g. for printing), use list(im.getdata()).

Does a "Find in project..." feature exist in Eclipse IDE?

First customize your search dialog. Ctrl+H. Click on the Customize button and select inly File Search while deselecting all the others. Close the dialog.

Now you can search by selecting the word and hitting the Ctrl+H and then Enter.

Java Replace Line In Text File

just how to replace strings :) as i do first arg will be filename second target string third one the string to be replaced instead of targe

public class ReplaceString{
      public static void main(String[] args)throws Exception {
        if(args.length<3)System.exit(0);
        String targetStr = args[1];
        String altStr = args[2];
        java.io.File file = new java.io.File(args[0]);
        java.util.Scanner scanner = new java.util.Scanner(file);
        StringBuilder buffer = new StringBuilder();
        while(scanner.hasNext()){
          buffer.append(scanner.nextLine().replaceAll(targetStr, altStr));
          if(scanner.hasNext())buffer.append("\n");
        }
        scanner.close();
        java.io.PrintWriter printer = new java.io.PrintWriter(file);
        printer.print(buffer);
        printer.close();
      }
    }

How to update and order by using ms sql

UPDATE messages SET 
 status=10 
WHERE ID in (SELECT TOP (10) Id FROM Table WHERE status=0 ORDER BY priority DESC);

What is the difference between JDK and JRE?

The answer above (by Pablo) is very right. This is just additional information.

The JRE is, as the name implies, an environment. It's basically a bunch of directories with Java-related files, to wit:

  • bin/ contains Java's executable programs. The most important is java (and for Windows, javaw as well), which launches the JVM. There are some other utilities here as well, such as keytool and policytool.
  • conf/ holds user-editable configuration files for Java experts to play with.
  • lib/ has a large number of supporting files: some .jars, configuration files, property files, fonts, translations, certs, etc. – all the "trimmings" of Java. The most important is modules, a file that contains the .class files of the Java standard library.
  • At a certain level, the Java standard library needs to call into native code. For this purpose, the JRE contains some .dll (Windows) or .dylib (macOS) or .so (Linux) files under bin/ or lib/ with supporting, system-specific native binary code.

The JDK is also a set of directories. It is a superset of the JRE, with some additions:

  • bin/ has been enlarged with development tools. The most important of them is javac; others include jar, javadoc and jshell.
  • jmods/, which holds JMOD files for the standard library, has been added. These files allow the standard library to be used with jlink.

How to convert C++ Code to C

This is an old thread but apparently the C++ Faq has a section (Archived 2013 version) on this. This apparently will be updated if the author is contacted so this will probably be more up to date in the long run, but here is the current version:

Depends on what you mean. If you mean, Is it possible to convert C++ to readable and maintainable C-code? then sorry, the answer is No — C++ features don't directly map to C, plus the generated C code is not intended for humans to follow. If instead you mean, Are there compilers which convert C++ to C for the purpose of compiling onto a platform that yet doesn't have a C++ compiler? then you're in luck — keep reading.

A compiler which compiles C++ to C does full syntax and semantic checking on the program, and just happens to use C code as a way of generating object code. Such a compiler is not merely some kind of fancy macro processor. (And please don't email me claiming these are preprocessors — they are not — they are full compilers.) It is possible to implement all of the features of ISO Standard C++ by translation to C, and except for exception handling, it typically results in object code with efficiency comparable to that of the code generated by a conventional C++ compiler.

Here are some products that perform compilation to C:

  • Comeau Computing offers a compiler based on Edison Design Group's front end that outputs C code.
  • LLVM is a downloadable compiler that emits C code. See also here and here. Here is an example of C++ to C conversion via LLVM.
  • Cfront, the original implementation of C++, done by Bjarne Stroustrup and others at AT&T, generates C code. However it has two problems: it's been difficult to obtain a license since the mid 90s when it started going through a maze of ownership changes, and development ceased at that same time and so it doesn't get bug fixes and doesn't support any of the newer language features (e.g., exceptions, namespaces, RTTI, member templates).

  • Contrary to popular myth, as of this writing there is no version of g++ that translates C++ to C. Such a thing seems to be doable, but I am not aware that anyone has actually done it (yet).

Note that you typically need to specify the target platform's CPU, OS and C compiler so that the generated C code will be specifically targeted for this platform. This means: (a) you probably can't take the C code generated for platform X and compile it on platform Y; and (b) it'll be difficult to do the translation yourself — it'll probably be a lot cheaper/safer with one of these tools.

One more time: do not email me saying these are just preprocessors — they are not — they are compilers.

Vertically aligning a checkbox

Its not a perfect solution, but a good workaround.

You need to assign your elements to behave as table with display: table-cell

Solution: Demo

HTML:

<ul>        
    <li>
        <div><input type="checkbox" value="1" name="test[]" id="myid1"></div>
        <div><label for="myid1">label1</label></div>
    </li>
    <li>
        <div><input type="checkbox" value="2" name="test[]" id="myid2"></div>
        <div><label for="myid2">label2</label></div>
    </li>
</ul>

CSS:

li div { display: table-cell; vertical-align: middle; }

'pip' is not recognized as an internal or external command

You can try pip3. Something like:

pip3 install pandas

What happens if you mount to a non-empty mount point with fuse?

Apparently nothing happens, it fails in a non-destructive way and gives you a warning.

I've had this happen as well very recently. One way you can solve this is by moving all the files in the non-empty mount point to somewhere else, e.g.:

mv /nonEmptyMountPoint/* ~/Desktop/mountPointDump/

This way your mount point is now empty, and your mount command will work.

Fit cell width to content

There are many ways to do this!

correct me if I'm wrong but the question is looking for this kind of result.

<table style="white-space:nowrap;width:100%;">
<tr>
<td class="block" style="width:50%">this should stretch</td>
<td class="block" style="width:50%">this should stretch</td>
<td class="block" style="width:auto">this should be the content width</td>
</tr>
</table>

The first 2 fields will "share" the remaining page (NOTE: if you add more text to either 50% fields it will take more space), and the last field will dominate the table constantly.

If you are happy to let text wrap you can move white-space:nowrap; to the style of the 3rd field
will be the only way to start a new line in that field.

alternatively, you can set a length on the last field ie. width:150px, and leave percentage's on the first 2 fields.

Hope this helps!

Set SSH connection timeout

The problem may be that ssh is trying to connect to all the different IPs that www.google.com resolves to. For example on my machine:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out

If I run it with a specific IP, it returns much faster.

EDIT: I've timed it (with time) and the results are:

  • www.google.com - 5.086 seconds
  • 173.94.43.16 - 1.054 seconds

Package Manager Console Enable-Migrations CommandNotFoundException only in a specific VS project

Just simply re-starting Visual Studio worked for me. No need to install packages, etc.

CSS two divs next to each other

I don't know if this is still a current issue or not but I just encountered the same problem and used the CSS display: inline-block; tag. Wrapping these in a div so that they can be positioned appropriately.

<div>
    <div style="display: inline-block;">Content1</div>
    <div style="display: inline-block;">Content2</div>
</div>

Note that the use of the inline style attribute was only used for the succinctness of this example of course these used be moved to an external CSS file.

How to have git log show filenames like svn log -v

NOTE: git whatchanged is deprecated, use git log instead

New users are encouraged to use git-log[1] instead. The whatchanged command is essentially the same as git-log[1] but defaults to show the raw format diff output and to skip merges.

The command is kept primarily for historical reasons; fingers of many people who learned Git long before git log was invented by reading Linux kernel mailing list are trained to type it.


You can use the command git whatchanged --stat to get a list of files that changed in each commit (along with the commit message).

References

No == operator found while comparing structs in C++

Because you did not write a comparison operator for your struct. The compiler does not generate it for you, so if you want comparison, you have to write it yourself.

File Upload with Angular Material

Nice solution by leocaseiro

<input class="ng-hide" id="input-file-id" multiple type="file" />
<label for="input-file-id" class="md-button md-raised md-primary">Choose Files</label>

enter image description here

View in codepen

git pull keeping local changes

There is a simple solution based on Git stash. Stash everything that you've changed, pull all the new stuff, apply your stash.

git stash
git pull
git stash pop

On stash pop there may be conflicts. In the case you describe there would in fact be a conflict for config.php. But, resolving the conflict is easy because you know that what you put in the stash is what you want. So do this:

git checkout --theirs -- config.php

MySQL - length() vs char_length()

LENGTH() returns the length of the string measured in bytes.
CHAR_LENGTH() returns the length of the string measured in characters.

This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:

select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1

As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282AC in UTF-8) even though it's only one character.

How to sort by column in descending order in Spark SQL?

You can also sort the column by importing the spark sql functions

import org.apache.spark.sql.functions._
df.orderBy(asc("col1"))

Or

import org.apache.spark.sql.functions._
df.sort(desc("col1"))

importing sqlContext.implicits._

import sqlContext.implicits._
df.orderBy($"col1".desc)

Or

import sqlContext.implicits._
df.sort($"col1".desc)

Generating a drop down list of timezones with PHP

I did this:

php -r "echo json_encode(array_combine(DateTimeZone::listIdentifiers(DateTimeZone::ALL), DateTimeZone::listIdentifiers(DateTimeZone::ALL)));" > list-of-timezones.json

Close all infowindows in Google Maps API v3

I had a dynamic loop that was creating the infowindows and markers based on how many were input into the CMS, so I didn't want to create a new InfoWindow() on every event click and bog it down with requests, if that ever arose. Instead, I tried to know what the specific infowindow variable for each instance was going to be out of the set amount of locations I had, and then prompt Maps to close all of them before it opened the correct one.

My array of locations was called locations, so the PHP I set up before the actual maps initilization to get my infowindow variable names was:

for($k = 0; $k < count($locations); $k++) {
        $infowindows[] = 'infowindow' . $k; 
} 

Then after initialzing the map and so forth, in the script I had a PHP foreach loop creating the dynamic info windows using a counter:

//...javascript map initilization
<?php 
$i=0;
foreach($locations as $location) {

    ..//get latitudes, longitude, image, etc...

echo 'var mapMarker' . $i . ' = new google.maps.Marker({
          position: myLatLng' . $i . ',
          map: map,
          icon: image
      });';

echo 'var contentString' . $i . ' = "<h1>' . $title[$i] . '</h1><h2>' . $address[$i] . '</h2>' . $content[$i] .         '";'; 
echo 'infowindow' . $i . ' = new google.maps.InfoWindow({ ';
echo '    content: contentString' . $i . '
          });';

echo 'google.maps.event.addListener(mapMarker' . $i . ', "click", function() { ';   
    foreach($infowindows as $window) {  
        echo $window . '.close();'; 
    }
        echo 'infowindow' . $i . '.open(map,mapMarker'. $i . ');
      });';

$i++; 
}
?>
...//continue with Maps script... 

So, the point is, before I called the entire map script, I had an array with the names I knew were going to be outputted when an InfoWindow() was created, like infowindow0, infowindow1, infowindow2, etc...

Then, on the click event for each marker, the foreach loop goes through and says close all of them before you follow through with the next step of opening them. It turns out looking like this:

google.maps.event.addListener(mapMarker0, "click", function() {
    infowindow0.close();
    infowindow1.close();
    infowindow2.close();
    infowindow0.open(map,mapMarker0);
}

Just a different way of doing things I suppose... but I hope it helps someone.

How do you add an ActionListener onto a JButton in Java

Two ways:

1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.

2. Use anonymous inner classes:

jBtnSelection.addActionListener(new ActionListener() { 
  public void actionPerformed(ActionEvent e) { 
    selectionButtonPressed();
  } 
} );

Later, you'll have to define selectionButtonPressed(). This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.

The second method also allows you to call the selection method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).

SQL is null and = null

I think that equality is something that can be absolutely determined. The trouble with null is that it's inherently unknown. Null combined with any other value is null - unknown. Asking SQL "Is my value equal to null?" would be unknown every single time, even if the input is null. I think the implementation of IS NULL makes it clear.

PHP: convert spaces in string into %20?

I believe that, if you need to use the %20 variant, you could perhaps use rawurlencode().

Android Studio don't generate R.java for my import project

So, this is the latest solution if anyone get's stuck like I did today especially, for R.Java file.

If you have lost the count of:

  • Clean Project
  • Rebuild Project
  • Invalidate Caches / Restart
  • deleted .gradle folder
  • deleted .idea folder
  • deleted app/build/generated folder
  • checked your xml files
  • checked your drawables and strings

then try this:

check your classpath dependency in your Project Gradle Scripts and if it's, this:

classpath 'com.android.tools.build:gradle:3.3.2'

then downgrade it to, this:

classpath 'com.android.tools.build:gradle:3.2.1'

How can I make a Python script standalone executable to run without ANY dependency?

I would like to compile some useful information about creating standalone files on Windows using Python 2.7.

I have used py2exe and it works, but I had some problems.

This last reason made me try PyInstaller http://www.pyinstaller.org/.

In my opinion, it is much better because:

  • It is easier to use.

I suggest creating a .bat file with the following lines for example (pyinstaller.exe must be in in the Windows path):

pyinstaller.exe --onefile MyCode.py

So, I think that, at least for python 2.7, a better and simpler option is PyInstaller.

How to send email using simple SMTP commands via Gmail?

Based on the existing answers, here's a step-by-step guide to sending automated e-mails over SMTP, using a GMail account, from the command line, without disclosing the password.

Requirements

First, install the following software packages:

These instructions assume a Linux operating system, but should be reasonably easy to port to Windows (via Cygwin or native equivalents), or other operating system.

Authentication

Save the following shell script as authentication.sh:

#!/bin/bash

# Asks for a username and password, then spits out the encoded value for
# use with authentication against SMTP servers.

echo -n "Email (shown): "
read email
echo -n "Password (hidden): "
read -s password
echo

TEXT="\0$email\0$password"

echo -ne $TEXT | base64

Make it executable and run it as follows:

chmod +x authentication.sh
./authentication.sh

When prompted, provide your e-mail address and password. This will look something like:

Email (shown): [email protected]
Password (hidden): 
AGJvYkBnbWFpbC5jb20AYm9iaXN0aGViZXN0cGVyc29uZXZlcg==

Copy the last line (AGJ...==), as this will be used for authentication.

Notification

Save the following expect script as notify.sh (note the first line refers to the expect program):

#!/usr/bin/expect

set address "[lindex $argv 0]"
set subject "[lindex $argv 1]"
set ts_date "[lindex $argv 2]"
set ts_time "[lindex $argv 3]"

set timeout 10
spawn openssl s_client -connect smtp.gmail.com:465 -crlf -ign_eof 

expect "220" {
  send "EHLO localhost\n"

  expect "250" {
    send "AUTH PLAIN YOUR_AUTHENTICATION_CODE\n"

    expect "235" {
      send "MAIL FROM: <YOUR_EMAIL_ADDRESS>\n"

      expect "250" {
        send "RCPT TO: <$address>\n"

        expect "250" {
          send "DATA\n"

          expect "354" {
            send "Subject: $subject\n\n"
            send "Email sent on $ts_date at $ts_time.\n"
            send "\n.\n"

            expect "250" {
                send "quit\n"
            }
          }
        }
      }
    }
  }
}

Make the following changes:

  1. Paste over YOUR_AUTHENTICATION_CODE with the authentication code generated by the authentication script.
  2. Change YOUR_EMAIL_ADDRESS with the e-mail address used to generate the authentication code.
  3. Save the file.

For example (note the angle brackets are retained for the e-mail address):

send "AUTH PLAIN AGJvYkBnbWFpbC5jb20AYm9iaXN0aGViZXN0cGVyc29uZXZlcg==\n"
send "MAIL FROM: <[email protected]>\n"

Lastly, make the notify script executable as follows:

chmod +x notify.sh

Send E-mail

Send an e-mail from the command line as follows:

./notify.sh [email protected] "Command Line" "March 14" "15:52"

The request was aborted: Could not create SSL/TLS secure channel

In my case I had this problem when a Windows service tried to connected to a web service. Looking in Windows events finally I found a error code.

Event ID 36888 (Schannel) is raised:

The following fatal alert was generated: 40. The internal error state is 808.

Finally it was related with a Windows Hotfix. In my case: KB3172605 and KB3177186

The proposed solution in vmware forum was add a registry entry in windows. After adding the following registry all works fine.

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\KeyExchangeAlgorithms\Diffie-Hellman]

"ClientMinKeyBitLength"=dword:00000200

Apparently it's related with a missing value in the https handshake in the client side.

List your Windows HotFix:

wmic qfe list

Solution Thread:

https://communities.vmware.com/message/2604912#2604912

Hope it's helps.

POSTing JSON to URL via WebClient in C#

The question is already answered but I think I've found the solution that is simpler and more relevant to the question title, here it is:

var cli = new WebClient();
cli.Headers[HttpRequestHeader.ContentType] = "application/json";
string response = cli.UploadString("http://some/address", "{some:\"json data\"}");

PS: In the most of .net implementations, but not in all WebClient is IDisposable, so of cource it is better to do 'using' or 'Dispose' on it. However in this particular case it is not really necessary.

How to reload/refresh jQuery dataTable?

Allan Jardine’s DataTables is a very powerful and slick jQuery plugin for displaying tabular data. It has many features and can do most of what you might want. One thing that’s curiously difficult though, is how to refresh the contents in a simple way, so I for my own reference, and possibly for the benefit of others as well, here’s a complete example of one way if doing this:

HTML

<table id="HelpdeskOverview">
  <thead>
    <tr>
      <th>Ärende</th>
      <th>Rapporterad</th>
      <th>Syst/Utr/Appl</th>
      <th>Prio</th>
      <th>Rubrik</th>
      <th>Status</th>
      <th>Ägare</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Javascript

function InitOverviewDataTable()
{
  oOverviewTable =$('#HelpdeskOverview').dataTable(
  {
    "bPaginate": true,
    "bJQueryUI": true,  // ThemeRoller-stöd
    "bLengthChange": false,
    "bFilter": false,
    "bSort": false,
    "bInfo": true,
    "bAutoWidth": true,
    "bProcessing": true,
    "iDisplayLength": 10,
    "sAjaxSource": '/Helpdesk/ActiveCases/noacceptancetest'
  });
}

function RefreshTable(tableId, urlData)
{
  $.getJSON(urlData, null, function( json )
  {
    table = $(tableId).dataTable();
    oSettings = table.fnSettings();

    table.fnClearTable(this);

    for (var i=0; i<json.aaData.length; i++)
    {
      table.oApi._fnAddData(oSettings, json.aaData[i]);
    }

    oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
    table.fnDraw();
  });
}

function AutoReload()
{
  RefreshTable('#HelpdeskOverview', '/Helpdesk/ActiveCases/noacceptancetest');

  setTimeout(function(){AutoReload();}, 30000);
}

$(document).ready(function () {
  InitOverviewDataTable();
  setTimeout(function(){AutoReload();}, 30000);
});

Source

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

The OP actually mentioned offset as well, so for ex. if you'd like to get the items from 30 to 60, you would do:

var foo = (From t In MyTable
       Select t.Foo).Skip(30).Take(30);

Use the "Skip" method for offset.
Use the "Take" method for limit.

Change color of Label in C#

You can try this with Color.FromArgb:

Random rnd = new Random();
lbl.ForeColor = Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));

Android get image path from drawable as string

based on the some of above replies i improvised it a bit

create this method and call it by passing your resource

Reusable Method

public String getURLForResource (int resourceId) {
    //use BuildConfig.APPLICATION_ID instead of R.class.getPackage().getName() if both are not same
    return Uri.parse("android.resource://"+R.class.getPackage().getName()+"/" +resourceId).toString();
}

Sample call

getURLForResource(R.drawable.personIcon)

complete example of loading image

String imageUrl = getURLForResource(R.drawable.personIcon);
// Load image
 Glide.with(patientProfileImageView.getContext())
          .load(imageUrl)
          .into(patientProfileImageView);

you can move the function getURLForResource to a Util file and make it static so it can be reused

How To Pass GET Parameters To Laravel From With GET Method ?

An alternative to msturdy's solution is using the request helper method available to you.

This works in exactly the same way, without the need to import the Input namespace use Illuminate\Support\Facades\Input at the top of your controller.

For example:

class SearchController extends BaseController {

    public function search()
    {
        $category = request('category', 'default');
        $term = request('term'); // no default defined

        ...
    }
}

Get max and min value from array in JavaScript

use this and it works on both the static arrays and dynamically generated arrays.

var array = [12,2,23,324,23,123,4,23,132,23];
var getMaxValue = Math.max.apply(Math, array );

I had the issue when I use trying to find max value from code below

$('#myTabs').find('li.active').prevAll().andSelf().each(function () {
            newGetWidthOfEachTab.push(parseInt($(this).outerWidth()));
        });

        for (var i = 0; i < newGetWidthOfEachTab.length; i++) {
            newWidthOfEachTabTotal += newGetWidthOfEachTab[i];
            newGetWidthOfEachTabArr.push(parseInt(newWidthOfEachTabTotal));
        }

        getMaxValue = Math.max.apply(Math, array);

I was getting 'NAN' when I use

    var max_value = Math.max(12, 21, 23, 2323, 23);

with my code

Changing Locale within the app itself

If you want to effect on the menu options for changing the locale immediately.You have to do like this.

//onCreate method calls only once when menu is called first time.
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //1.Here you can add your  locale settings . 
    //2.Your menu declaration.
}
//This method is called when your menu is opend to again....
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
    menu.clear();
    onCreateOptionsMenu(menu);
    return super.onMenuOpened(featureId, menu);
}

How to draw interactive Polyline on route google maps v2 android

You should use options.addAll(allPoints); instead of options.add(point);

Tomcat 7 is not running on browser(http://localhost:8080/ )

You can run below commands.

 ./catalina.sh run

Note: Make sure the port 8080 is open. If not, kill the process that is using 8080 port using sudo kill -9 $(sudo lsof -t -i:8080)

How to use a variable from a cursor in the select statement of another cursor in pl/sql

You need to use dynamic SQL to achieve this; something like:

DECLARE
    TYPE cur_type IS REF CURSOR;

    CURSOR client_cur IS
        SELECT DISTING username
        FROM all_users
        WHERE length(username) = 3;

    emails_cur cur_type;
    l_cur_string VARCHAR2(128);
    l_email_id <type>;
    l_name <type>;
BEGIN
    FOR client IN client_cur LOOP
        dbms_output.put_line('Client is '|| client.username);
        l_cur_string := 'SELECT id, name FROM '
            || client.username || '.org';
        OPEN emails_cur FOR l_cur_string;
        LOOP
            FETCH emails_cur INTO l_email_id, l_name;
            EXIT WHEN emails_cur%NOTFOUND;
            dbms_output.put_line('Org id is ' || l_email_id
                || ' org name ' || l_name);
        END LOOP;
        CLOSE emails_cur;
    END LOOP;
END;
/

Edited to correct two errors, and to add links to 10g documentation for OPEN-FOR and an example. Edited to make the inner cursor query a string variable.

How to convert a byte array to its numeric value (Java)?

Each cell in the array is treated as unsigned int:

private int unsignedIntFromByteArray(byte[] bytes) {
int res = 0;
if (bytes == null)
    return res;


for (int i=0;i<bytes.length;i++){
    res = res | ((bytes[i] & 0xff) << i*8);
}
return res;
}

How to set a cookie to expire in 1 hour in Javascript?

Code :

var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);
document.cookie = 
'username=' + value + 
'; expires=' + now.toUTCString() + 
'; path=/';

how to log in to mysql and query the database from linux terminal

To your first question:

mysql -u root -p

or

mysqladmin -u root -p "your_command"

depending on what you want to do. The password will be asked of you once you hit enter! I'm guessing you really want to use mysql and not mysqladmin.

For restarting or stopping the MySQL-server on linux, it depends on your installation, but in the common debian derivatives this will work for starting, stopping and restarting the service:

sudo /etc/init.d/mysql start
sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql restart
sudo /etc/init.d/mysql status

In some newer distros this might work as well if MySQL is set up as a deamon/service.

sudo service mysql start
sudo service mysql stop
sudo service mysql restart
sudo service mysql status

But the question is really impossible to answer without knowing your particular setup.

How can I insert a line break into a <Text> component in React Native?

You can do it as follows:

{'Create\nYour Account'}

Loop through array of values with Arrow Function

In short:

someValues.forEach((element) => {
    console.log(element);
});

If you care about index, then second parameter can be passed to receive the index of current element:

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);
    console.log(element);
});

Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

How do I hide an element on a click event anywhere outside of the element?

Just 2 small improvements to the above suggestions:

  • unbind the document.click when done
  • stop propagation on the event that triggered this, assuming its a click

    jQuery(thelink).click(function(e){
        jQuery(thepop).show();
    
        // bind the hide controls
        var jpop=jQuery(thepop);
        jQuery(document).bind("click.hidethepop", function() {
                jpop.hide();
                // unbind the hide controls
                jQuery(document).unbind("click.hidethepop");
        });
        // dont close thepop when you click on thepop
        jQuery(thepop).click(function(e) {
            e.stopPropagation();
        });
        // and dont close thepop now 
        e.stopPropagation();
    });
    

Docker - Ubuntu - bash: ping: command not found

Sometimes, the minimal installation of Linux in Docker doesn't define the path and therefore it is necessary to call ping using ....

cd /usr/sbin
ping <ip>

Iterate a list with indexes in Python

If you have multiple lists, you can do this combining enumerate and zip:

list1 = [1, 2, 3, 4, 5]
list2 = [10, 20, 30, 40, 50]
list3 = [100, 200, 300, 400, 500]
for i, (l1, l2, l3) in enumerate(zip(list1, list2, list3)):
    print(i, l1, l2, l3)
Output:
0 1 10 100
1 2 20 200
2 3 30 300
3 4 40 400
4 5 50 500

Note that parenthesis is required after i. Otherwise you get the error: ValueError: need more than 2 values to unpack

C# Change A Button's Background Color

this.button2.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(29)))), ((int)(((byte)(190)))), ((int)(((byte)(149)))));

White spaces are required between publicId and systemId

Change the order of statments. For me, changing the block of code

xsi:schemaLocation="http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/context
                    http://www.springframework.org/schema/beans/spring-beans.xsd" 

with

xsi:schemaLocation="http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/context"

is valid.

Unable to Install Any Package in Visual Studio 2015

In my case, there was an empty packages.config file in the soultion directory, after deleting this, update succeeded

What order are the Junit @Before/@After called?

One potential gotcha that has bitten me before:

I like to have at most one @Before method in each test class, because order of running the @Before methods defined within a class is not guaranteed. Typically, I will call such a method setUpTest().

But, although @Before is documented as The @Before methods of superclasses will be run before those of the current class. No other ordering is defined., this only applies if each method marked with @Before has a unique name in the class hierarchy.

For example, I had the following:

public class AbstractFooTest {
  @Before
  public void setUpTest() { 
     ... 
  }
}

public void FooTest extends AbstractFooTest {
  @Before
  public void setUpTest() { 
    ...
  }
}

I expected AbstractFooTest.setUpTest() to run before FooTest.setUpTest(), but only FooTest.setupTest() was executed. AbstractFooTest.setUpTest() was not called at all.

The code must be modified as follows to work:

public void FooTest extends AbstractFooTest {
  @Before
  public void setUpTest() {
    super.setUpTest();
    ...
  }
}

How do I prevent Eclipse from hanging on startup?

UFT causing issues with RDz (Eclipse based) after install These suggestions will allow to work around this situation even with the environment variables in place and with corresponding values.

Note: Conflicting application will not be recognized in a java context because it is being excluded from the java support mechanism.

  1. Impact: Excludes Add-ins support from hooking to conflicting application executable via Windows Registry Editor Requirement: The application must be started by an EXE file, except Java.exe/Javaw.exe/jpnlauncher.exe

Instructions:

a. Locate the executable filename of the application conflicting with add-in(s) support. Either use the Task Manager or the Microsoft Process Explorer.

b. Open Windows Registry Editor.

c. Navigate to: HKEY_LOCAL_MACHINE\SOFTWARE\Mercury Interactive\JavaAgent\Modules For 32bits applications on Windows x64: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Mercury Interactive\JavaAgent\Modules

d. Create a DWORD value with the name of the conflicting software executable filenmae and set the value to 0.

Updated Registry

Backup/Restore a dockerized PostgreSQL database

Okay, I've figured this out. Postgresql does not detect changes to the folder /var/lib/postgresql once it's launched, at least not the kind of changes I want it do detect.

The first solution is to start a container with bash instead of starting the postgres server directly, restore the data, and then start the server manually.

The second solution is to use a data container. I didn't get the point of it before, now I do. This data container allows to restore the data before starting the postgres container. Thus, when the postgres server starts, the data are already there.

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

@Amit's answer is good because it will work in both Mustache and Handlebars.

As far as Handlebars-only solutions, I've seen a few and I like the each_with_key block helper at https://gist.github.com/1371586 the best.

  • It allows you to iterate over object literals without having to restructure them first, and
  • It gives you control over what you call the key variable. With many other solutions you have to be careful about using object keys named 'key', or 'property', etc.

Easy way of running the same junit test over and over?

Inspired by the following resources:

Example

Create and use a @Repeat annotation as follows:

public class MyTestClass {

    @Rule
    public RepeatRule repeatRule = new RepeatRule();

    @Test
    @Repeat(10)
    public void testMyCode() {
        //your test code goes here
    }
}

Repeat.java

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.METHOD;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention( RetentionPolicy.RUNTIME )
@Target({ METHOD, ANNOTATION_TYPE })
public @interface Repeat {
    int value() default 1;
}

RepeatRule.java

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class RepeatRule implements TestRule {

    private static class RepeatStatement extends Statement {
        private final Statement statement;
        private final int repeat;    

        public RepeatStatement(Statement statement, int repeat) {
            this.statement = statement;
            this.repeat = repeat;
        }

        @Override
        public void evaluate() throws Throwable {
            for (int i = 0; i < repeat; i++) {
                statement.evaluate();
            }
        }

    }

    @Override
    public Statement apply(Statement statement, Description description) {
        Statement result = statement;
        Repeat repeat = description.getAnnotation(Repeat.class);
        if (repeat != null) {
            int times = repeat.value();
            result = new RepeatStatement(statement, times);
        }
        return result;
    }
}

PowerMock

Using this solution with @RunWith(PowerMockRunner.class), requires updating to Powermock 1.6.5 (which includes a patch).

Get the date (a day before current time) in Bash

#!/bin/bash
OFFSET=1;
eval `date "+day=%d; month=%m; year=%Y"`
# Subtract offset from day, if it goes below one use 'cal'
# to determine the number of days in the previous month.
day=`expr $day - $OFFSET`
if [ $day -le 0 ] ;then
month=`expr $month - 1`
if [ $month -eq 0 ] ;then
year=`expr $year - 1`
month=12
fi
set `cal $month $year`
xday=${$#}
day=`expr $xday + $day`
fi
echo $year-$month-$day

Key Shortcut for Eclipse Imports

You also can enable this import as automatic operation. In the properties dialog of your Java projects, enable organize imports via Java Editor - Save Action. After saving your Java files, IDE will do organizing imports, formatting code and so on for you.

Using json_encode on objects in PHP (regardless of scope)

In RedBeanPHP 2.0 there is a mass-export function which turns an entire collection of beans into arrays. This works with the JSON encoder..

json_encode( R::exportAll( $beans ) );

Declaration of Methods should be Compatible with Parent Methods in PHP

This message means that there are certain possible method calls which may fail at run-time. Suppose you have

class A { public function foo($a = 1) {;}}
class B extends A { public function foo($a) {;}}
function bar(A $a) {$a->foo();}

The compiler only checks the call $a->foo() against the requirements of A::foo() which requires no parameters. $a may however be an object of class B which requires a parameter and so the call would fail at runtime.

This however can never fail and does not trigger the error

class A { public function foo($a) {;}}
class B extends A { public function foo($a = 1) {;}}
function bar(A $a) {$a->foo();}

So no method may have more required parameters than its parent method.

The same message is also generated when type hints do not match, but in this case PHP is even more restrictive. This gives an error:

class A { public function foo(StdClass $a) {;}}
class B extends A { public function foo($a) {;}}

as does this:

class A { public function foo($a) {;}}
class B extends A { public function foo(StdClass $a) {;}}

That seems more restrictive than it needs to be and I assume is due to internals.

Visibility differences cause a different error, but for the same basic reason. No method can be less visible than its parent method.

NSAttributedString add text alignment

As NSAttributedString is primarily used with Core Text on iOS, you have to use CTParagraphStyle instead of NSParagraphStyle. There is no mutable variant.

For example:

CTTextAlignment alignment = kCTCenterTextAlignment;

CTParagraphStyleSetting alignmentSetting;
alignmentSetting.spec = kCTParagraphStyleSpecifierAlignment;
alignmentSetting.valueSize = sizeof(CTTextAlignment);
alignmentSetting.value = &alignment;

CTParagraphStyleSetting settings[1] = {alignmentSetting};

size_t settingsCount = 1;
CTParagraphStyleRef paragraphRef = CTParagraphStyleCreate(settings, settingsCount);
NSDictionary *attributes = @{(__bridge id)kCTParagraphStyleAttributeName : (__bridge id)paragraphRef};
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:@"Hello World" attributes:attributes];

What does __FILE__ mean in Ruby?

It is a reference to the current file name. In the file foo.rb, __FILE__ would be interpreted as "foo.rb".

Edit: Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in his comment. With these files:

# test.rb
puts __FILE__
require './dir2/test.rb'
# dir2/test.rb
puts __FILE__

Running ruby test.rb will output

test.rb
/full/path/to/dir2/test.rb

How can I run dos2unix on an entire directory?

It's probably best to skip hidden files and folders, such as .git. So instead of using find, if your bash version is recent enough or if you're using zsh, just do:

dos2unix **

Note that for Bash, this will require:

shopt -s globstar

....but this is a useful enough feature that you should honestly just put it in your .bashrc anyway.

If you don't want to skip hidden files and folders, but you still don't want to mess with find (and I wouldn't blame you), you can provide a second recursive-glob argument to match only hidden entries:

dos2unix ** **/.*

Note that in both cases, the glob will expand to include directories, so you will see the following warning (potentially many times over): Skipping <dir>, not a regular file.

How to completely uninstall python 2.7.13 on Ubuntu 16.04

How I do:

# Remove python2
sudo apt purge -y python2.7-minimal

# You already have Python3 but 
# don't care about the version 
sudo ln -s /usr/bin/python3 /usr/bin/python

# Same for pip
sudo apt install -y python3-pip
sudo ln -s /usr/bin/pip3 /usr/bin/pip

# Confirm the new version of Python: 3
python --version

'mvn' is not recognized as an internal or external command,

Make sure you have your maven bin directory in the path and the JAVA_HOME property set

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

Essentially it means you don't have the index you are trying to reference. For example:

df = pd.DataFrame()
df['this']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #I haven't yet assigned how long df[data] should be!
print(df)

will give me the error you are referring to, because I haven't told Pandas how long my dataframe is. Whereas if I do the exact same code but I DO assign an index length, I don't get an error:

df = pd.DataFrame(index=[0,1,2,3,4])
df['this']=np.nan
df['is']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #since I've properly labelled my index, I don't run into this problem!
print(df)

Hope that answers your question!