Programs & Examples On #Openbsd

OpenBSD is an advanced unix-like operating system for modern server, desktop, and embedded computer platforms. It is open source and licensed under the BSD license.

Forward X11 failed: Network error: Connection refused

The D-Bus error can be fixed with dbus-launch :

dbus-launch command

How can bcrypt have built-in salts?

I believe that phrase should have been worded as follows:

bcrypt has salts built into the generated hashes to prevent rainbow table attacks.

The bcrypt utility itself does not appear to maintain a list of salts. Rather, salts are generated randomly and appended to the output of the function so that they are remembered later on (according to the Java implementation of bcrypt). Put another way, the "hash" generated by bcrypt is not just the hash. Rather, it is the hash and the salt concatenated.

'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

As you're using Windows, installation should automatically edit the %PATH% variable. Therefore, I suspect you simply need to reboot your system after installing.

How do you get git to always pull from a specific branch?

Not wanting to edit my git config file I followed the info in @mipadi's post and used:

$ git pull origin master

Angular 2 TypeScript how to find element in Array

Use this code in your service:

return this.getReports(accessToken)
        .then(reports => reports.filter(report => report.id === id)[0]);

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

In your Case you can write the following jquery code:

$(document).ready(function(){

   $('.staff_on_site').click(function(){

     var rBtnVal = $(this).val();

     if(rBtnVal == "yes"){
         $("#no_of_staff").attr("readonly", false); 
     }
     else{ 
         $("#no_of_staff").attr("readonly", true); 
     }
   });
});

Here is the Fiddle: http://jsfiddle.net/P4QWx/3/

How to prevent IFRAME from redirecting top-level window

I use sandbox="..."

  • allow-forms allows form submission
  • allow-popups allows popups
  • allow-pointer-lock allows pointer lock
  • allow-same-origin allows the document to maintain its origin
  • allow-scripts allows JavaScript execution, and also allows features to trigger automatically
  • allow-top-navigation allows the document to break out of the frame by navigating the top-level window

Top navigation is what you want to prevent, so leave that out and it will not be allowed. Anything left out will be blocked

ex.

        <iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms" src="http://www.example.com"</iframe>

How to make <div> fill <td> height

Really have to do this with JS. Here's a solution. I didn't use your class names, but I called the div within the td class name of "full-height" :-) Used jQuery, obviously. Note this was called from jQuery(document).ready(function(){ setFullHeights();}); Also note if you have images, you are going to have to iterate through them first with something like:

function loadedFullHeights(){
var imgCount = jQuery(".full-height").find("img").length;
if(imgCount===0){
    return setFullHeights();
}
var loaded = 0;
jQuery(".full-height").find("img").load(function(){
    loaded++;
    if(loaded ===imgCount){
        setFullHeights()
    }
});

}

And you would want to call the loadedFullHeights() from docReady instead. This is actually what I ended up using just in case. Got to think ahead you know!

function setFullHeights(){
var par;
var height;
var $ = jQuery;
var heights=[];
var i = 0;
$(".full-height").each(function(){
    par =$(this).parent();
    height = $(par).height();
    var tPad = Number($(par).css('padding-top').replace('px',''));
    var bPad = Number($(par).css('padding-bottom').replace('px',''));
    height -= tPad+bPad;
    heights[i]=height;
    i++;
});
for(ii in heights){
    $(".full-height").eq(ii).css('height', heights[ii]+'px');
}

}

jQuery and TinyMCE: textarea value doesn't submit

I used:

var save_and_add = function(){
    tinyMCE.triggerSave();
    $('.new_multi_text_block_item').submit();
};

This is all you need to do.

CFLAGS vs CPPFLAGS

The implicit make rule for compiling a C program is

%.o:%.c
    $(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<

where the $() syntax expands the variables. As both CPPFLAGS and CFLAGS are used in the compiler call, which you use to define include paths is a matter of personal taste. For instance if foo.c is a file in the current directory

make foo.o CPPFLAGS="-I/usr/include"
make foo.o CFLAGS="-I/usr/include"

will both call your compiler in exactly the same way, namely

gcc -I/usr/include -c -o foo.o foo.c

The difference between the two comes into play when you have multiple languages which need the same include path, for instance if you have bar.cpp then try

make bar.o CPPFLAGS="-I/usr/include"
make bar.o CFLAGS="-I/usr/include"

then the compilations will be

g++ -I/usr/include -c -o bar.o bar.cpp
g++ -c -o bar.o bar.cpp

as the C++ implicit rule also uses the CPPFLAGS variable.

This difference gives you a good guide for which to use - if you want the flag to be used for all languages put it in CPPFLAGS, if it's for a specific language put it in CFLAGS, CXXFLAGS etc. Examples of the latter type include standard compliance or warning flags - you wouldn't want to pass -std=c99 to your C++ compiler!

You might then end up with something like this in your makefile

CPPFLAGS=-I/usr/include
CFLAGS=-std=c99
CXXFLAGS=-Weffc++

Excel formula to display ONLY month and year?

Try the formula

=TEXT(TODAY(),"MMYYYY")

How to access List elements

Recursive solution to print all items in a list:

def printItems(l):
   for i in l:
      if isinstance(i,list):
         printItems(i)
      else:
         print i


l = [['vegas','London'],['US','UK']]
printItems(l)

Xcode variables

Here's a list of the environment variables. I think you might want CURRENT_VARIANT. See also BUILD_VARIANTS.

mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists

You may try the following if your database does not have any data OR you have another away to restore that data. You will need to know the Ubuntu server root password but not the mysql root password.

It is highly probably that many of us have installed "mysql_secure_installation" as this is a best practice. Navigate to bin directory where mysql_secure_installation exist. It can be found in the /bin directory on Ubuntu systems. By rerunning the installer, you will be prompted about whether to change root database password.

Very simple C# CSV reader

Here's a simple function I made. It accepts a string CSV line and returns an array of fields:

It works well with Excel generated CSV files, and many other variations.

    public static string[] ParseCsvRow(string r)
    {

        string[] c;
        string t;
        List<string> resp = new List<string>();
        bool cont = false;
        string cs = "";

        c = r.Split(new char[] { ',' }, StringSplitOptions.None);

        foreach (string y in c)
        {
            string x = y;


            if (cont)
            {
                // End of field
                if (x.EndsWith("\""))
                {
                    cs += "," + x.Substring(0, x.Length - 1);
                    resp.Add(cs);
                    cs = "";
                    cont = false;
                    continue;

                }
                else
                {
                    // Field still not ended
                    cs += "," + x;
                    continue;
                }
            }

            // Fully encapsulated with no comma within
            if (x.StartsWith("\"") && x.EndsWith("\""))
            {
                if ((x.EndsWith("\"\"") && !x.EndsWith("\"\"\"")) && x != "\"\"")
                {
                    cont = true;
                    cs = x;
                    continue;
                }

                resp.Add(x.Substring(1, x.Length - 2));
                continue;
            }

            // Start of encapsulation but comma has split it into at least next field
            if (x.StartsWith("\"") && !x.EndsWith("\""))
            {
                cont = true;
                cs += x.Substring(1);
                continue;
            }

            // Non encapsulated complete field
            resp.Add(x);

        }

        return resp.ToArray();

    }

Origin <origin> is not allowed by Access-Control-Allow-Origin

use dataType: 'jsonp', works for me.

   async function get_ajax_data(){

       var _reprojected_lat_lng = await $.ajax({

                                type: 'GET',

                                dataType: 'jsonp',

                                data: {},

                                url: _reprojection_url,

                                error: function (jqXHR, textStatus, errorThrown) {

                                    console.log(jqXHR)

                                },

                                success: function (data) {

                                    console.log(data);



                                    // note: data is already json type, you just specify dataType: jsonp

                                    return data;

                                }

                            });





 } // function               

Change action bar color in android

if you have in your layout activity_main

<android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

you have to put

in your Activity this code

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setBackgroundColor(Color.CYAN);
}

Read input from console in Ruby?

if you want to hold the arguments from Terminal, try the following code:

A = ARGV[0].to_i
B = ARGV[1].to_i

puts "#{A} + #{B} = #{A + B}"

Set start value for column with autoincrement

From Resetting SQL Server Identity Columns:

Retrieving the identity for the table Employees:

DBCC checkident ('Employees')

Repairing the identity seed (if for some reason the database is inserting duplicate identities):

DBCC checkident ('Employees', reseed)

Changing the identity seed for the table Employees to 1000:

DBCC checkident ('Employees', reseed, 1000)

The next row inserted will begin at 1001.

Calling a function every 60 seconds

use the

setInterval(function, 60000);

EDIT : (In case if you want to stop the clock after it is started)

Script section

<script>
var int=self.setInterval(function, 60000);
</script>

and HTML Code

<!-- Stop Button -->
<a href="#" onclick="window.clearInterval(int);return false;">Stop</a>

Twitter Bootstrap alert message close and open again

If you're using an MVVM library such as knockout.js (which I highly recommend) you can do it more cleanly:

<div class="alert alert-info alert-dismissible" data-bind="visible:showAlert">
   <button type="button" class="close" data-bind="click:function(){showAlert(false);}>
        <span aria-hidden="true">&times;</span>
        <span class="sr-only">Close</span>
   </button>
   Warning! Better check yourself, you're not looking too good.
</div>

http://jsfiddle.net/bce9gsav/5/

What does ON [PRIMARY] mean?

To add a very important note on what Mark S. has mentioned in his post. In the specific SQL Script that has been mentioned in the question you can NEVER mention two different file groups for storing your data rows and the index data structure.

The reason why is due to the fact that the index being created in this case is a clustered Index on your primary key column. The clustered index data and the data rows of your table can NEVER be on different file groups.

So in case you have two file groups on your database e.g. PRIMARY and SECONDARY then below mentioned script will store your row data and clustered index data both on PRIMARY file group itself even though I've mentioned a different file group ([SECONDARY]) for the table data. More interestingly the script runs successfully as well (when I was expecting it to give an error as I had given two different file groups :P). SQL Server does the trick behind the scene silently and smartly.

CREATE TABLE [dbo].[be_Categories](
    [CategoryID] [uniqueidentifier] ROWGUIDCOL  NOT NULL CONSTRAINT [DF_be_Categories_CategoryID]  DEFAULT (newid()),
    [CategoryName] [nvarchar](50) NULL,
    [Description] [nvarchar](200) NULL,
    [ParentID] [uniqueidentifier] NULL,
 CONSTRAINT [PK_be_Categories] PRIMARY KEY CLUSTERED 
(
    [CategoryID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [SECONDARY]
GO

NOTE: Your index can reside on a different file group ONLY if the index being created is non-clustered in nature.

The below script which creates a non-clustered index will get created on [SECONDARY] file group instead when the table data already resides on [PRIMARY] file group:

CREATE NONCLUSTERED INDEX [IX_Categories] ON [dbo].[be_Categories]
(
    [CategoryName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Secondary]
GO

You can get more information on how storing non-clustered indexes on a different file group can help your queries perform better. Here is one such link.

Closing Bootstrap modal onclick

If the button tag is inside the div element who contains the modal, you can do something like:

<button class="btn btn-default" data-dismiss="modal" aria-label="Close">Cancel</button>

Send File Attachment from Form Using phpMailer and PHP

File could not be Attached from client PC (upload)

In the HTML form I have not added following line, so no attachment was going:

enctype="multipart/form-data"

After adding above line in form (as below), the attachment went perfect.

<form id="form1" name="form1" method="post" action="form_phpm_mailer.php"  enctype="multipart/form-data">

PHP prepend leading zero before single digit number, on-the-fly

You can use str_pad for adding 0's

str_pad($month, 2, '0', STR_PAD_LEFT); 

string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

Python Replace \\ with \

Your original string, a = 'a\\nb' does not actually have two '\' characters, the first one is an escape for the latter. If you do, print a, you'll see that you actually have only one '\' character.

>>> a = 'a\\nb'
>>> print a
a\nb

If, however, what you mean is to interpret the '\n' as a newline character, without escaping the slash, then:

>>> b = a.replace('\\n', '\n')
>>> b
'a\nb'
>>> print b
a
b

How To Auto-Format / Indent XML/HTML in Notepad++

Install Tidy2 plugin. I have Notepad++ v6.2.2, and Tidy2 works fine so far.

How to use the CancellationToken property?

You can implement your work method as follows:

private static void Work(CancellationToken cancelToken)
{
    while (true)
    {
        if(cancelToken.IsCancellationRequested)
        {
            return;
        }
        Console.Write("345");
    }
}

That's it. You always need to handle cancellation by yourself - exit from method when it is appropriate time to exit (so that your work and data is in consistent state)

UPDATE: I prefer not writing while (!cancelToken.IsCancellationRequested) because often there are few exit points where you can stop executing safely across loop body, and loop usually have some logical condition to exit (iterate over all items in collection etc.). So I believe it's better not to mix that conditions as they have different intention.

Cautionary note about avoiding CancellationToken.ThrowIfCancellationRequested():

Comment in question by Eamon Nerbonne:

... replacing ThrowIfCancellationRequested with a bunch of checks for IsCancellationRequested exits gracefully, as this answer says. But that's not just an implementation detail; that affects observable behavior: the task will no longer end in the cancelled state, but in RanToCompletion. And that can affect not just explicit state checks, but also, more subtly, task chaining with e.g. ContinueWith, depending on the TaskContinuationOptions used. I'd say that avoiding ThrowIfCancellationRequested is dangerous advice.

How to get the list of all printers in computer

If you need more information than just the name of the printer you can use the System.Management API to query them:

var printerQuery = new ManagementObjectSearcher("SELECT * from Win32_Printer");
foreach (var printer in printerQuery.Get())
{
    var name = printer.GetPropertyValue("Name");
    var status = printer.GetPropertyValue("Status");
    var isDefault = printer.GetPropertyValue("Default");
    var isNetworkPrinter = printer.GetPropertyValue("Network");

    Console.WriteLine("{0} (Status: {1}, Default: {2}, Network: {3}", 
                name, status, isDefault, isNetworkPrinter);
}

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

I solved this with this commands:

1- Run the container

# docker run -d <image-name>

2- List containers

   # docker ps -a

3- Use the container ID

# docker exec -it <container-id> /bin/sh

Reading in a JSON File Using Swift

Follow the below code :

if let path = NSBundle.mainBundle().pathForResource("test", ofType: "json")
{
    if let jsonData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)
    {
        if let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary
        {
            if let persons : NSArray = jsonResult["person"] as? NSArray
            {
                // Do stuff
            }
        }
     }
}

The array "persons" will contain all data for key person. Iterate throughs to fetch it.

Swift 4.0:

if let path = Bundle.main.path(forResource: "test", ofType: "json") {
    do {
          let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
          let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves)
          if let jsonResult = jsonResult as? Dictionary<String, AnyObject>, let person = jsonResult["person"] as? [Any] {
                    // do stuff
          }
      } catch {
           // handle error
      }
}

How to generate an entity-relationship (ER) diagram using Oracle SQL Developer

Oracle used to have a component in SQL Developer called Data Modeler. It no longer exists in the product since at least 3.2.20.10.

It's now a separate download that you can find here:

http://www.oracle.com/technetwork/developer-tools/datamodeler/overview/index.html

Convert JsonObject to String

you can use

JsonObject.getString("msg"); 

An efficient way to Base64 encode a byte array?

byte[] base64EncodedStringBytes = Encoding.ASCII.GetBytes(Convert.ToBase64String(binaryData))

REST API using POST instead of GET

It is nice that REST brings meaning to HTTP verbs (as they defined) but I prefer to agree with Scott Peal.

Here is also item from WIKI's extended explanation on POST request:

There are times when HTTP GET is less suitable even for data retrieval. An example of this is when a great deal of data would need to be specified in the URL. Browsers and web servers can have limits on the length of the URL that they will handle without truncation or error. Percent-encoding of reserved characters in URLs and query strings can significantly increase their length, and while Apache HTTP Server can handle up to 4,000 characters in a URL,[5] Microsoft Internet Explorer is limited to 2,048 characters in any URL.[6] Equally, HTTP GET should not be used where sensitive information, such as user names and passwords, have to be submitted along with other data for the request to complete. Even if HTTPS is used, preventing the data from being intercepted in transit, the browser history and the web server's logs will likely contain the full URL in plaintext, which may be exposed if either system is hacked. In these cases, HTTP POST should be used.[7]

I could only suggest to REST team to consider more secure use of HTTP protocol to avoid making consumers struggle with non-secure "good practice".

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

got the below error

PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> npm install vue npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY npm ERR! errno UNABLE_TO_GET_ISSUER_CERT_LOCALLY npm ERR! request to https://registry.npmjs.org/vue failed, reason: unable to get local issuer certificate

npm ERR! A complete log of this run can be found in: npm ERR!
C:\Users\chpr\AppData\Roaming\npm-cache_logs\2020-07-29T03_22_40_225Z-debug.log PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> PS C:\Users\chpr\Documents\GitHub\vue-nwjs-hours-tracking> npm ERR!
C:\Users\chpr\AppData\Roaming\npm-cache_logs\2020-07-29T03_22_40_225Z-debug.log

Below command solved the issue:

npm config set strict-ssl false

Set port for php artisan.php serve

You can use many ports together for each project,

  php artisan serve --port=8000

  php artisan serve --port=8001   

  php artisan serve --port=8002

  php artisan serve --port=8003

How do you define a class of constants in Java?

My preferred method is not to do that at all. The age of constants pretty much died when Java 5 introduced typesafe enums. And even before then Josh Bloch published a (slightly more wordy) version of that, which worked on Java 1.4 (and earlier).

Unless you need interoperability with some legacy code there's really no reason to use named String/integer constants anymore.

Echo off but messages are displayed

@echo off
// quote the path or else it won't work if there are spaces in the path
SET INSTALL_PATH="c:\\etc etc\\test";
if exist %INSTALL_PATH% (
   //
   echo 222;
)

How do you share constants in NodeJS modules?

I don't think is a good practice to invade the GLOBAL space from modules, but in scenarios where could be strictly necessary to implement it:

Object.defineProperty(global,'MYCONSTANT',{value:'foo',writable:false,configurable:false});

It has to be considered the impact of this resource. Without proper naming of those constants, the risk of OVERWRITTING already defined global variables, is something real.

Changing upload_max_filesize on PHP

This solution can be applied only if the issue is on a WordPress installation!

If you don't have FTP access or too lazy to edit files,

You can use Increase Maximum Upload File Size plugin to increase the maximum upload file size.

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

select t1.Column as Price, t2.Column as Other_Price
from table1 as t1 INNER JOIN table2 as t2 
ON t1.Key = t2.Key 

like this ?

Run JavaScript code on window close or page refresh?

jQuery version:

$(window).unload(function(){
    // Do Something
});

Update: jQuery 3:

$(window).on("unload", function(e) {
    // Do Something
});

Thanks Garrett

How to add a new row to an empty numpy array

In this case you might want to use the functions np.hstack and np.vstack

arr = np.array([])
arr = np.hstack((arr, np.array([1,2,3])))
# arr is now [1,2,3]

arr = np.vstack((arr, np.array([4,5,6])))
# arr is now [[1,2,3],[4,5,6]]

You also can use the np.concatenate function.

Cheers

iPhone UILabel text soft shadow

I tried almost all of these techniques (except FXLabel) and couldn't get any of them to work with iOS 7. I did eventually find THLabel which is working perfectly for me. I used THLabel in Interface Builder and setup User Defined Runtime Attributes so that it's easy for a non programmer to control the look and feel.

https://github.com/MuscleRumble/THLabel

How to check if a variable is empty in python?

See section 5.1:

http://docs.python.org/library/stdtypes.html

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

None

False

zero of any numeric type, for example, 0, 0L, 0.0, 0j.

any empty sequence, for example, '', (), [].

any empty mapping, for example, {}.

instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False. [1]

All other values are considered true — so objects of many types are always true.

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

Multiple Inheritance in C#

Since the question of multiple inheritance (MI) pops up from time to time, I'd like to add an approach which addresses some problems with the composition pattern.

I build upon the IFirst, ISecond,First, Second, FirstAndSecond approach, as it was presented in the question. I reduce sample code to IFirst, since the pattern stays the same regardless of the number of interfaces / MI base classes.

Lets assume, that with MI First and Second would both derive from the same base class BaseClass, using only public interface elements from BaseClass

This can be expressed, by adding a container reference to BaseClass in the First and Second implementation:

class First : IFirst {
  private BaseClass ContainerInstance;
  First(BaseClass container) { ContainerInstance = container; }
  public void FirstMethod() { Console.WriteLine("First"); ContainerInstance.DoStuff(); } 
}
...

Things become more complicated, when protected interface elements from BaseClass are referenced or when First and Second would be abstract classes in MI, requiring their subclasses to implement some abstract parts.

class BaseClass {
  protected void DoStuff();
}

abstract class First : IFirst {
  public void FirstMethod() { DoStuff(); DoSubClassStuff(); }
  protected abstract void DoStuff(); // base class reference in MI
  protected abstract void DoSubClassStuff(); // sub class responsibility
}

C# allows nested classes to access protected/private elements of their containing classes, so this can be used to link the abstract bits from the First implementation.

class FirstAndSecond : BaseClass, IFirst, ISecond {
  // link interface
  private class PartFirst : First {
    private FirstAndSecond ContainerInstance;
    public PartFirst(FirstAndSecond container) {
      ContainerInstance = container;
    }
    // forwarded references to emulate access as it would be with MI
    protected override void DoStuff() { ContainerInstance.DoStuff(); }
    protected override void DoSubClassStuff() { ContainerInstance.DoSubClassStuff(); }
  }
  private IFirst partFirstInstance; // composition object
  public FirstMethod() { partFirstInstance.FirstMethod(); } // forwarded implementation
  public FirstAndSecond() {
    partFirstInstance = new PartFirst(this); // composition in constructor
  }
  // same stuff for Second
  //...
  // implementation of DoSubClassStuff
  private void DoSubClassStuff() { Console.WriteLine("Private method accessed"); }
}

There is quite some boilerplate involved, but if the actual implementation of FirstMethod and SecondMethod are sufficiently complex and the amount of accessed private/protected methods is moderate, then this pattern may help to overcome lacking multiple inheritance.

Most efficient conversion of ResultSet to JSON?

If anyone plan to use this implementation, You might wanna check this out and this

This is my version of that convertion code:

public class ResultSetConverter {
public static JSONArray convert(ResultSet rs) throws SQLException,
        JSONException {
    JSONArray json = new JSONArray();
    ResultSetMetaData rsmd = rs.getMetaData();
    int numColumns = rsmd.getColumnCount();
    while (rs.next()) {

        JSONObject obj = new JSONObject();

        for (int i = 1; i < numColumns + 1; i++) {
            String column_name = rsmd.getColumnName(i);

            if (rsmd.getColumnType(i) == java.sql.Types.ARRAY) {
                obj.put(column_name, rs.getArray(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BIGINT) {
                obj.put(column_name, rs.getLong(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.REAL) {
                obj.put(column_name, rs.getFloat(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BOOLEAN) {
                obj.put(column_name, rs.getBoolean(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BLOB) {
                obj.put(column_name, rs.getBlob(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DOUBLE) {
                obj.put(column_name, rs.getDouble(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.FLOAT) {
                obj.put(column_name, rs.getDouble(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.INTEGER) {
                obj.put(column_name, rs.getInt(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.NVARCHAR) {
                obj.put(column_name, rs.getNString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.VARCHAR) {
                obj.put(column_name, rs.getString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.CHAR) {
                obj.put(column_name, rs.getString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.NCHAR) {
                obj.put(column_name, rs.getNString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.LONGNVARCHAR) {
                obj.put(column_name, rs.getNString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.LONGVARCHAR) {
                obj.put(column_name, rs.getString(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TINYINT) {
                obj.put(column_name, rs.getByte(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.SMALLINT) {
                obj.put(column_name, rs.getShort(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DATE) {
                obj.put(column_name, rs.getDate(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TIME) {
                obj.put(column_name, rs.getTime(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.TIMESTAMP) {
                obj.put(column_name, rs.getTimestamp(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BINARY) {
                obj.put(column_name, rs.getBytes(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.VARBINARY) {
                obj.put(column_name, rs.getBytes(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.LONGVARBINARY) {
                obj.put(column_name, rs.getBinaryStream(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.BIT) {
                obj.put(column_name, rs.getBoolean(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.CLOB) {
                obj.put(column_name, rs.getClob(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.NUMERIC) {
                obj.put(column_name, rs.getBigDecimal(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DECIMAL) {
                obj.put(column_name, rs.getBigDecimal(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.DATALINK) {
                obj.put(column_name, rs.getURL(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.REF) {
                obj.put(column_name, rs.getRef(column_name));
            } else if (rsmd.getColumnType(i) == java.sql.Types.STRUCT) {
                obj.put(column_name, rs.getObject(column_name)); // must be a custom mapping consists of a class that implements the interface SQLData and an entry in a java.util.Map object.
            } else if (rsmd.getColumnType(i) == java.sql.Types.DISTINCT) {
                obj.put(column_name, rs.getObject(column_name)); // must be a custom mapping consists of a class that implements the interface SQLData and an entry in a java.util.Map object.
            } else if (rsmd.getColumnType(i) == java.sql.Types.JAVA_OBJECT) {
                obj.put(column_name, rs.getObject(column_name));
            } else {
                obj.put(column_name, rs.getString(i));
            }
        }

        json.put(obj);
    }

    return json;
}
}

Modular multiplicative inverse function in Python

The code above will not run in python3 and is less efficient compared to the GCD variants. However, this code is very transparent. It triggered me to create a more compact version:

def imod(a, n):
 c = 1
 while (c % a > 0):
     c += n
 return c // a

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

An alternative would to use the jdbc.drivers System property to specify your required drivers(s) on the command line when you start the JVM.

Filtering Sharepoint Lists on a "Now" or "Today"

Have you tried this: create a Computed column, called 'Expiry', with a formula that amounts to '[Created] + 7 days'. Then use the computed column in your View's filter. Let us know whether this worked or what problems this poses!

Updating PartialView mvc 4

Thanks all for your help! Finally I used JQuery/AJAX as you suggested, passing the parameter using model.

So, in JS:

$('#divPoints').load('/Schedule/UpdatePoints', UpdatePointsAction);
var points= $('#newpoints').val();
$element.find('PointsDiv').html("You have" + points+ " points");

In Controller:

var model = _newPoints;
return PartialView(model);

In View

<div id="divPoints"></div>
@Html.Hidden("newpoints", Model)

You cannot call a method on a null-valued expression

The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code

$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider

The error was because you are trying to execute a method that does not exist.

PS C:\Users\Matt> $md5 | gm


   TypeName: System.Security.Cryptography.MD5CryptoServiceProvider

Name                       MemberType Definition                                                                                                                            
----                       ---------- ----------                                                                                                                            
Clear                      Method     void Clear()                                                                                                                          
ComputeHash                Method     byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...

The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.

PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

PowerShell by default allows this to happen as defined its StrictMode

When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.

How to connect to a MS Access file (mdb) using C#?

You should use "Microsoft OLE DB Provider for ODBC Drivers" to get to access to Microsoft Access. Here is the sample tutorial on using it

http://msdn.microsoft.com/en-us/library/aa288452(v=vs.71).aspx

ORA-00060: deadlock detected while waiting for resource

I was testing a function that had multiple UPDATE statements within IF-ELSE blocks.

I was testing all possible paths, so I reset the tables to their previous values with 'manual' UPDATE statements each time before running the function again.

I noticed that the issue would happen just after those UPDATE statements;

I added a COMMIT; after the UPDATE statement I used to reset the tables and that solved the problem.

So, caution, the problem was not the function itself...

Get the last element of a std::string

You probably want to check the length of the string first and do something like this:

if (!myStr.empty())
{
    char lastChar = *myStr.rbegin();
}

MySQL Creating tables with Foreign Keys giving errno: 150

As pointed by @andrewdotn the best way is to see the detailed error(SHOW ENGINE INNODB STATUS;) instead of just an error code.

One of the reasons could be that an index already exists with the same name, may be in another table. As a practice, I recommend prefixing table name before the index name to avoid such collisions. e.g. instead of idx_userId use idx_userActionMapping_userId.

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

Based on the link provided by Philip I got this to working

Worksheets("Final Analysis Sheet").Range("A4:G112").CopyPicture xlScreen, xlBitmap

    Application.DisplayAlerts = False
    Set oCht = Charts.Add
    With oCht
        .Paste
        .Export Filename:="C:\FTPDailycheck\TodaysImages\SavedRange.jpg", Filtername:="JPG"
        .Delete
    End With

HttpWebRequest using Basic authentication

For those using RestSharp, it might fail when using SimpleAuthenticator (possibly due to not using ISO-8859-1 behind the scene). I managed to get it done by explicitly sending Basic Authentication headers:

string username = "...";
string password = "...";

public IRestResponse GetResponse(string url, Method method = Method.GET)
{
    string encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{username}:{password}"));
    var client = new RestClient(url);
    var request = new RestRequest(method );
    request.AddHeader("Authorization", $"Basic {encoded}");
    IRestResponse response = client.Execute(request);
    return response;
}

var response = GetResponse(url);
txtResult.Text = response.Content;

Set Session variable using javascript in PHP

Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.

How to add "active" class to Html.ActionLink in ASP.NET MVC

In Bootstrap the active class needs to be applied to the <li> element and not the <a>. See the first example here: http://getbootstrap.com/components/#navbar

The way you handle your UI style based on what is active or not has nothing to do with ASP.NET MVC's ActionLink helper. This is the proper solution to follow how the Bootstrap framework was built.

<ul class="nav navbar-nav">
    <li class="active">@Html.ActionLink("Home", "Index", "Home")</li>
    <li>@Html.ActionLink("About", "About", "Home")</li>
    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>

Edit:

Since you will most likely be reusing your menu on multiple pages, it would be smart to have a way to apply that selected class automatically based on the current page rather than copy the menu multiple times and do it manually.

The easiest way is to simply use the values contained in ViewContext.RouteData, namely the Action and Controller values. We could build on what you currently have with something like this:

<ul class="nav navbar-nav">
    <li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Index" ? "active" : "")">@Html.ActionLink("Home", "Index", "Home")</li>
    <li class="@(ViewContext.RouteData.Values["Action"].ToString() == "About" ? "active" : "")">@Html.ActionLink("About", "About", "Home")</li>
    <li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Contact" ? "active" : "")">@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>

It's not pretty in code, but it'll get the job done and allow you to extract your menu into a partial view if you like. There are ways to do this in a much cleaner way, but since you're just getting started I'll leave it at that. Best of luck learning ASP.NET MVC!


Late edit:

This question seems to be getting a bit of traffic so I figured I'd throw in a more elegant solution using an HtmlHelper extension.

Edit 03-24-2015: Had to rewrite this method to allow for multiple actions and controllers triggering the selected behavior, as well as handling for when the method is called from a child action partial view, thought I'd share the update!

public static string IsSelected(this HtmlHelper html, string controllers = "", string actions = "", string cssClass = "selected")
{
    ViewContext viewContext = html.ViewContext;
    bool isChildAction = viewContext.Controller.ControllerContext.IsChildAction;

    if (isChildAction)
        viewContext = html.ViewContext.ParentActionViewContext;

    RouteValueDictionary routeValues = viewContext.RouteData.Values;
    string currentAction = routeValues["action"].ToString();
    string currentController = routeValues["controller"].ToString();

    if (String.IsNullOrEmpty(actions))
        actions = currentAction;

    if (String.IsNullOrEmpty(controllers))
        controllers = currentController;

    string[] acceptedActions = actions.Trim().Split(',').Distinct().ToArray();
    string[] acceptedControllers = controllers.Trim().Split(',').Distinct().ToArray();

    return acceptedActions.Contains(currentAction) && acceptedControllers.Contains(currentController) ?
        cssClass : String.Empty;
}

Works with .NET Core:

public static string IsSelected(this IHtmlHelper htmlHelper, string controllers, string actions, string cssClass = "selected")
{
    string currentAction = htmlHelper.ViewContext.RouteData.Values["action"] as string;
    string currentController = htmlHelper.ViewContext.RouteData.Values["controller"] as string;

    IEnumerable<string> acceptedActions = (actions ?? currentAction).Split(',');
    IEnumerable<string> acceptedControllers = (controllers ?? currentController).Split(',');

    return acceptedActions.Contains(currentAction) && acceptedControllers.Contains(currentController) ?
        cssClass : String.Empty;
}

Sample usage:

<ul>
    <li class="@Html.IsSelected(actions: "Home", controllers: "Default")">
        <a href="@Url.Action("Home", "Default")">Home</a>
    </li>
    <li class="@Html.IsSelected(actions: "List,Detail", controllers: "Default")">
        <a href="@Url.Action("List", "Default")">List</a>
    </li>
</ul>

Using the Jersey client to do a POST operation

Simplest:

Form form = new Form();
form.add("id", "1");    
form.add("name", "supercobra");
ClientResponse response = webResource
  .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
  .post(ClientResponse.class, form);

How to open port in Linux

The following configs works on Cent OS 6 or earlier

As stated above first have to disable selinux.

Step 1 nano /etc/sysconfig/selinux

Make sure the file has this configurations

SELINUX=disabled

SELINUXTYPE=targeted

Then restart the system

Step 2

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

Step 3

sudo service iptables save

For Cent OS 7

step 1

firewall-cmd --zone=public --permanent --add-port=8080/tcp

Step 2

firewall-cmd --reload

How do you get/set media volume (not ringtone volume) in Android?

If you happen to have a volume bar that you want to adjust –similar to what you see on iPhone's iPod app– here's how.

    @Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    switch (keyCode) {
    case KeyEvent.KEYCODE_VOLUME_UP:
        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
        //Raise the Volume Bar on the Screen
        volumeControl.setProgress( audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
                + AudioManager.ADJUST_RAISE);
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        //Adjust the Volume
        audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
        //Lower the VOlume Bar on the Screen
        volumeControl.setProgress(audioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC)
                + AudioManager.ADJUST_LOWER);
        return true;
    default:
        return false;
    }

Recover SVN password from local cache

On Windows, Subversion stores the auth data in %APPDATA%\Subversion\auth. The passwords however are stored encrypted, not in plaintext.

You can decrypt those, but only if you log in to Windows as the same user for which the auth data was saved.

Someone even wrote a tool to decrypt those. Never tried the tool myself so I don't know how well it works, but you might want to try it anyway:

http://www.leapbeyond.com/ric/TSvnPD/

Update: In TortoiseSVN 1.9 and later, you can do it without any additional tools:

Settings Dialog -> Saved Data, then click the "Clear..." button right of the text "Authentication Data". A new dialog pops up, showing all stored authentication data where you can chose which one(s) to clear. Instead of clearing, hold down the Shift and Ctrl button, and then double click on the list. A new column is shown in the dialog which shows the password in clear.

To enable extensions, verify that they are enabled in those .ini files - Vagrant/Ubuntu/Magento 2.0.2

First installed

sudo apt-get install php5-gd

then

sudo apt-get install php5-intl

and last one was

sudo apt-get install php5-xsl

After that, it is installing as it should.

How to list all tags along with the full message in git?

Use --format option

git tag -l --format='%(tag) %(subject)'

How to set seekbar min and max value

You can set max value for your seekbar by using this code:

    sb1.setMax(100);

This will set the max value for your seekbar.

But you cannot set the minimum value but yes you can do some arithmetic to adjust value. Use arithmetic to adjust your application-required value.

For example, suppose you have data values from -50 to 100 you want to display on the SeekBar. Set the SeekBar's maximum to be 150 (100-(-50)), then subtract 50 from the raw value to get the number you should use when setting the bar position.

You can get more info via this link.

How to terminate a window in tmux?

If you just want to do it once, without adding a shortcut, you can always type

<prefix> 
:
kill-window
<enter>

Maven : error in opening zip file when running maven

Probably, contents of the JAR files in your local .m2 repository are HTML saying "301 Moved Permanently". It seems that mvn does not handle "301 Moved Permanently" properly as expected. In such a case, download the JAR files manually from somewhere (the central repository, for example) and put them into your .m2 repository.

See also:

asm-3.1.jar; error in opening zip file
http://darutk-oboegaki.blogspot.jp/2012/07/asm-31jar-error-in-opening-zip-file.html

Plotting of 1-dimensional Gaussian distribution function

you can read this tutorial for how to use functions of statistical distributions in python. http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html

from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np 

#initialize a normal distribution with frozen in mean=-1, std. dev.= 1
rv = norm(loc = -1., scale = 1.0)
rv1 = norm(loc = 0., scale = 2.0)
rv2 = norm(loc = 2., scale = 3.0)

x = np.arange(-10, 10, .1)

#plot the pdfs of these normal distributions 
plt.plot(x, rv.pdf(x), x, rv1.pdf(x), x, rv2.pdf(x))

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

Assuming you're dealing with Windows 7 x64 and something that was previously installed with some sort of an installer, you can open regedit and search the keys under

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

(which references 32-bit programs) for part of the name of the program, or

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

(if it actually was a 64-bit program).

If you find something that matches your program in one of those, the contents of UninstallString in that key usually give you the exact command you are looking for (that you can run in a script).

If you don't find anything relevant in those registry locations, then it may have been "installed" by unzipping a file. Because you mentioned removing it by the Control Panel, I gather this likely isn't then case; if it's in the list of programs there, it should be in one of the registry keys I mentioned.

Then in a .bat script you can do

if exist "c:\program files\whatever\program.exe" (place UninstallString contents here)
if exist "c:\program files (x86)\whatever\program.exe" (place UninstallString contents here)

How can I create a dynamically sized array of structs?

In C++, use a vector. It's like an array but you can easily add and remove elements and it will take care of allocating and deallocating memory for you.

I know the title of the question says C, but you tagged your question with C and C++...

Model summary in pytorch

You can just use x.shape, in order to measure tensor's x dimensions

Sorting arraylist in alphabetical order (case insensitive)

def  lst = ["A2", "A1", "k22", "A6", "a3", "a5", "A4", "A7"]; 

println lst.sort { a, b -> a.compareToIgnoreCase b }

This should be able to sort with case insensitive but I am not sure how to tackle the alphanumeric strings lists

Debugging WebSocket in Google Chrome

I'm just posting this since Chrome changes alot, and none of the answers were quite up to date.

  1. Open dev tools
  2. REFRESH YOUR PAGE (so that the WS connection is captured by the network tab)
  3. Click your request
  4. Click the "Frames" sub-tab
  5. You should see somthing like this:

enter image description here

add an onclick event to a div

Is it possible to add onclick to a div and have it occur if any area of the div is clicked.

Yes … although it should be done with caution. Make sure there is some mechanism that allows keyboard access. Build on things that work

If yes then why is the onclick method not going through to my div.

You are assigning a string where a function is expected.

divTag.onclick = printWorking;

There are nicer ways to assign event handlers though, although older versions of Internet Explorer are sufficiently different that you should use a library to abstract it. There are plenty of very small event libraries and every major library jQuery) has event handling functionality.

That said, now it is 2019, older versions of Internet Explorer no longer exist in practice so you can go direct to addEventListener

SVG Positioning

I know this is old but neither an <svg> group tag nor a <g> fixed the issue I was facing. I needed to adjust the y position of a tag which also had animation on it.

The solution was to use both the and tag together:

<svg y="1190" x="235">
   <g class="light-1">
     <path />
   </g>
</svg>

INSERT SELECT statement in Oracle 11G

Your query should be:

insert into table1 (col1, col2) 
select t1.col1, t2.col2 
from oldtable1 t1, oldtable2 t2

I.e. without the VALUES part.

Quickly create large file on a Windows system

Temp files should be stored in the Windows Temp Folder. Based on the answer from Rod you can use the following one liner to create a 5 GB temp file which returns the filename

[System.IO.Path]::GetTempFileName() | % { [System.IO.File]::Create($_).SetLength(5gb).Close;$_ } | ? { $_ }

Explanation:

  • [System.IO.Path]::GetTempFileName() generates a random filename with random extension in the Windows Temp Folder
  • The Pipeline is used to pass the name to [System.IO.File]::Create($_) which creates the file
  • The file name is set to the newly created file with .SetLength(5gb). I was a bit surprised to discover, that PowerShell supports Byte Conversion, which is really helpful.
  • The file handle needs to be closed with .close to allow other applications to access it
  • With ;$_ the filename is returned and with | ? { $_ } it is ensured that only the filename is returned and not the empty string returned by [System.IO.File]::Create($_)

Setting up and using environment variables in IntelliJ Idea

In addition to the above answer and restarting the IDE didn't do, try restarting "Jetbrains Toolbox" if you use it, this did it for me

Creating threads - Task.Factory.StartNew vs new Thread()

Your first block of code tells CLR to create a Thread (say. T) for you which is can be run as background (use thread pool threads when scheduling T ). In concise, you explicitly ask CLR to create a thread for you to do something and call Start() method on thread to start.

Your second block of code does the same but delegate (implicitly handover) the responsibility of creating thread (background- which again run in thread pool) and the starting thread through StartNew method in the Task Factory implementation.

This is a quick difference between given code blocks. Having said that, there are few detailed difference which you can google or see other answers from my fellow contributors.

LDAP filter for blank (empty) attribute

This article http://technet.microsoft.com/en-us/library/ee198810.aspx led me to the solution. The only change is the placement of the exclamation mark.

(!manager=*)

It seems to be working just as wanted.

Editor does not contain a main type

Try 'Update Project'. Once I did this, The Run as Java Application option appeared.

How to install an APK file on an Android phone?

Put the APK file into the tools folder in the Android SDK and give the path to tools in the command prompt and use the command:

adb install "name".apk file

pandas get rows which are NOT in other dataframe

Here is another way of solving this:

df1[~df1.index.isin(df1.merge(df2, how='inner', on=['col1', 'col2']).index)]

Or:

df1.loc[df1.index.difference(df1.merge(df2, how='inner', on=['col1', 'col2']).index)]

Android: Test Push Notification online (Google Cloud Messaging)

POSTMAN : A google chrome extension

Use postman to send message instead of server. Postman settings are as follows :

Request Type: POST

URL: https://android.googleapis.com/gcm/send

Header
  Authorization  : key=your key //Google API KEY
  Content-Type : application/json

JSON (raw) :
{       
  "registration_ids":["yours"],
  "data": {
    "Hello" : "World"
  } 
}

on success you will get

Response :
{
  "multicast_id": 6506103988515583000,
  "success": 1,
  "failure": 0,
  "canonical_ids": 0,
  "results": [
    {
      "message_id": "0:1432811719975865%54f79db3f9fd7ecd"
    }
  ]
}

How to set corner radius of imageView?

import UIKit

class BorderImage: UIImageView {

    override func awakeFromNib() {
        self.layoutIfNeeded()
        layer.cornerRadius = self.frame.height / 10.0
        layer.masksToBounds = true
    }
}

Based on @DCDC's answer

Connection timeout for SQL server

Yes, you could append ;Connection Timeout=30 to your connection string and specify the value you wish.

The timeout value set in the Connection Timeout property is a time expressed in seconds. If this property isn't set, the timeout value for the connection is the default value (15 seconds).

Moreover, setting the timeout value to 0, you are specifying that your attempt to connect waits an infinite time. As described in the documentation, this is something that you shouldn't set in your connection string:

A value of 0 indicates no limit, and should be avoided in a ConnectionString because an attempt to connect waits indefinitely.

How can I parse a YAML file from a Linux shell script?

You can also consider using Grunt (The JavaScript Task Runner). Can be easily integrated with shell. It supports reading YAML (grunt.file.readYAML) and JSON (grunt.file.readJSON) files.

This can be achieved by creating a task in Gruntfile.js (or Gruntfile.coffee), e.g.:

module.exports = function (grunt) {

    grunt.registerTask('foo', ['load_yml']);

    grunt.registerTask('load_yml', function () {
        var data = grunt.file.readYAML('foo.yml');
        Object.keys(data).forEach(function (g) {
          // ... switch (g) { case 'my_key':
        });
    });

};

then from shell just simply run grunt foo (check grunt --help for available tasks).

Further more you can implement exec:foo tasks (grunt-exec) with input variables passed from your task (foo: { cmd: 'echo bar <%= foo %>' }) in order to print the output in whatever format you want, then pipe it into another command.


There is also similar tool to Grunt, it's called gulp with additional plugin gulp-yaml.

Install via: npm install --save-dev gulp-yaml

Sample usage:

var yaml = require('gulp-yaml');

gulp.src('./src/*.yml')
  .pipe(yaml())
  .pipe(gulp.dest('./dist/'))

gulp.src('./src/*.yml')
  .pipe(yaml({ space: 2 }))
  .pipe(gulp.dest('./dist/'))

gulp.src('./src/*.yml')
  .pipe(yaml({ safe: true }))
  .pipe(gulp.dest('./dist/'))

To more options to deal with YAML format, check YAML site for available projects, libraries and other resources which can help you to parse that format.


Other tools:

  • Jshon

    parses, reads and creates JSON

Select objects based on value of variable in object using jq

I had a similar related question: What if you wanted the original object format back (with key names, e.g. FOO, BAR)?

Jq provides to_entries and from_entries to convert between objects and key-value pair arrays. That along with map around the select

These functions convert between an object and an array of key-value pairs. If to_entries is passed an object, then for each k: v entry in the input, the output array includes {"key": k, "value": v}.

from_entries does the opposite conversion, and with_entries(foo) is a shorthand for to_entries | map(foo) | from_entries, useful for doing some operation to all keys and values of an object. from_entries accepts key, Key, name, Name, value and Value as keys.

jq15 < json 'to_entries | map(select(.value.location=="Stockholm")) | from_entries'

{
  "FOO": {
    "name": "Donald",
    "location": "Stockholm"
  },
  "BAR": {
    "name": "Walt",
    "location": "Stockholm"
  }
}

Using the with_entries shorthand, this becomes:

jq15 < json 'with_entries(select(.value.location=="Stockholm"))'
{
  "FOO": {
    "name": "Donald",
    "location": "Stockholm"
  },
  "BAR": {
    "name": "Walt",
    "location": "Stockholm"
  }
}

Date Comparison using Java

You are probably looking for:

!toDate.before(currentDate)

before() and after() test whether the date is strictly before or after. So you have to take the negation of the other one to get non strict behaviour.

Is it possible to move/rename files in Git and maintain their history?

I make moving the files and then do

git add -A

which put in the sataging area all deleted/new files. Here git realizes that the file is moved.

git commit -m "my message"
git push

I do not know why but this works for me.

Encode a FileStream to base64 with c#

A simple Stream extension method would do the job:

public static class StreamExtensions
{
    public static string ConvertToBase64(this Stream stream)
    {
        var bytes = new Byte[(int)stream.Length];

        stream.Seek(0, SeekOrigin.Begin);
        stream.Read(bytes, 0, (int)stream.Length);

        return Convert.ToBase64String(bytes);
    }
}

The methods for Read (and also Write) and optimized for the respective class (whether is file stream, memory stream, etc.) and will do the work for you. For simple task like this, there is no need of readers, and etc.

The only drawback is that the stream is copied into byte array, but that is how the conversion to base64 via Convert.ToBase64String works unfortunately.

Google Maps JS API v3 - Simple Multiple Marker Example

Here is a nearly complete example javascript function that will allow multiple markers defined in a JSONObject.

It will only display the markers that are with in the bounds of the map.

This is important so you are not doing extra work.

You can also set a limit to the markers so you are not showing an extreme amount of markers (if there is a possibility of a thing in your usage);

it will also not display markers if the center of the map has not changed more than 500 meters.
This is important because if a user clicks on the marker and accidentally drags the map while doing so you don't want the map to reload the markers.

I attached this function to the idle event listener for the map so markers will show only when the map is idle and will redisplay the markers after a different event.

In action screen shot there is a little change in the screen shot showing more content in the infowindow. enter image description here pasted from pastbin.com

_x000D_
_x000D_
<script src="//pastebin.com/embed_js/uWAbRxfg"></script>
_x000D_
_x000D_
_x000D_

How do I enable TODO/FIXME/XXX task tags in Eclipse?

There are apparently distributions or custom builds in which the ability to set Task Tags for non-Java files is not present. This post mentions that ColdFusion Builder (built on Eclipse) does not let you set non-Java Task Tags, but the beta version of CF Builder 2 does. (I know the OP wasn't using CF Builder, but I am, and I was wondering about this question myself ... because he didn't see the ability to set non-Java tags, I thought others might be in the same position.)

How do I iterate through children elements of a div using jQuery?

I don't think that you need to use each(), you can use standard for loop

var children = $element.children().not(".pb-sortable-placeholder");
for (var i = 0; i < children.length; i++) {
    var currentChild = children.eq(i);
    // whatever logic you want
    var oldPosition = currentChild.data("position");
}

this way you can have the standard for loop features like break and continue works by default

also, the debugging will be easier

jQuery return ajax result into outside variable

So this is long after the initial question, and technically it isn't a direct answer to how to use Ajax call to populate exterior variable as the question asks. However in research and responses it's been found to be extremely difficult to do this without disabling asynchronous functions within the call, or by descending into what seems like the potential for callback hell. My solution for this has been to use Axios. Using this has dramatically simplified my usages of asynchronous calls getting in the way of getting at data.

For example if I were trying to access session variables in PHP, like the User ID, via a call from JS this might be a problem. Doing something like this..

async function getSession() {
 'use strict';
 const getSession = await axios("http:" + url + "auth/" + "getSession");
 log(getSession.data);//test
 return getSession.data;
}

Which calls a PHP function that looks like this.

public function getSession() {
 $session = new SessionController();
 $session->Session();
 $sessionObj = new \stdClass();
 $sessionObj->user_id = $_SESSION["user_id"];
 echo json_encode($sessionObj);
}

To invoke this using Axios do something like this.

getSession().then(function (res) {
 log(res);//test
 anyVariable = res;
 anyFunction(res);//set any variable or populate another function waiting for the data
});

The result would be, in this case a Json object from PHP.

{"user_id":"1111111-1111-1111-1111-111111111111"}

Which you can either use in a function directly in the response section of the Axios call or set a variable or invoke another function.

Proper syntax for the Axios call would actually look like this.

getSession().then(function (res) {
 log(res);//test
 anyVariable = res;
 anyFunction(res);//set any variable or populate another function waiting for the data
}).catch(function (error) {
 console.log(error);
});

For proper error handling.

I hope this helps anyone having these issues. And yes I am aware this technically is not a direct answer to the question but given the answers supplied already I felt the need to provide this alternative solution which dramatically simplified my code on the client and server sides.

How can I set the maximum length of 6 and minimum length of 6 in a textbox?

You can't set a minimum length on a text field. Otherwise, users wouldn't be able to type in the first five characters.

Your best bet is to validate the input when the form is submitted to ensure that the length is six.

maxlength is not a validation attribute. It is designed to prevent the user from physically typing in more than six characters. The corresponding minlengh is not in scope of the HTML specification, because its implementation would render the textbox unusable.

String field value length in mongoDB

Here is one of the way in mongodb you can achieve this.

db.usercollection.find({ $where: 'this.name.length < 4' })

how to increase the limit for max.print in R

set the function options(max.print=10000) in top of your program. since you want intialize this before it works. It is working for me.

How good is Java's UUID.randomUUID?

Many of the answers discuss how many UUIDs would have to be generated to reach a 50% chance of a collision. But a 50%, 25%, or even 1% chance of collision is worthless for an application where collision must be (virtually) impossible.

Do programmers routinely dismiss as "impossible" other events that can and do occur?

When we write data to a disk or memory and read it back again, we take for granted that the data are correct. We rely on the device's error correction to detect any corruption. But the chance of undetected errors is actually around 2-50.

Wouldn't it make sense to apply a similar standard to random UUIDs? If you do, you will find that an "impossible" collision is possible in a collection of around 100 billion random UUIDs (236.5).

This is an astronomical number, but applications like itemized billing in a national healthcare system, or logging high frequency sensor data on a large array of devices could definitely bump into these limits. If you are writing the next Hitchhiker's Guide to the Galaxy, don't try to assign UUIDs to each article!

Difference between Hashing a Password and Encrypting it

Hashing is a one way function (well, a mapping). It's irreversible, you apply the secure hash algorithm and you cannot get the original string back. The most you can do is to generate what's called "a collision", that is, finding a different string that provides the same hash. Cryptographically secure hash algorithms are designed to prevent the occurrence of collisions. You can attack a secure hash by the use of a rainbow table, which you can counteract by applying a salt to the hash before storing it.

Encrypting is a proper (two way) function. It's reversible, you can decrypt the mangled string to get original string if you have the key.

The unsafe functionality it's referring to is that if you encrypt the passwords, your application has the key stored somewhere and an attacker who gets access to your database (and/or code) can get the original passwords by getting both the key and the encrypted text, whereas with a hash it's impossible.

People usually say that if a cracker owns your database or your code he doesn't need a password, thus the difference is moot. This is naïve, because you still have the duty to protect your users' passwords, mainly because most of them do use the same password over and over again, exposing them to a greater risk by leaking their passwords.

Can I have onScrollListener for a ScrollView?

This might be very useful. Use NestedScrollView instead of ScrollView. Support Library 23.1 introduced an OnScrollChangeListener to NestedScrollView. So you can do something like this.

 myScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
        @Override
        public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
            Log.d("ScrollView","scrollX_"+scrollX+"_scrollY_"+scrollY+"_oldScrollX_"+oldScrollX+"_oldScrollY_"+oldScrollY);
            //Do something
        }
    });

AngularJS app.run() documentation?

Specifically...

How and where is app.run() used? After module definition or after app.config(), after app.controller()?

Where:

In your package.js E.g. /packages/dashboard/public/controllers/dashboard.js

How:

Make it look like this

var app = angular.module('mean.dashboard', ['ui.bootstrap']);

app.controller('DashboardController', ['$scope', 'Global', 'Dashboard',
    function($scope, Global, Dashboard) {
        $scope.global = Global;
        $scope.package = {
            name: 'dashboard'
        };
        // ...
    }
]);

app.run(function(editableOptions) {
    editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});

Single vs Double quotes (' vs ")

In HTML I don't believe it matters whether you use " or ', but it should be used consistently throughout the document.

My own usage prefers that attributes/html use ", whereas all javascript uses ' instead.

This makes it slightly easier, for me, to read and check. If your use makes more sense for you than mine would, there's no need for change. But, to me, your code would feel messy. It's personal is all.

Way to insert text having ' (apostrophe) into a SQL table

try this

INSERT INTO exampleTbl VALUES('he doesn''t work for me')

What is the most efficient way to concatenate N arrays?

If there are only two arrays to concat, and you actually need to append one of arrays rather than create a new one, push or loop is the way to go.

Benchmark: https://jsperf.com/concat-small-arrays-vs-push-vs-loop/

Using PHP with Socket.io

UPDATE: Aug 2014 The current socket.io v1.0 site has a PHP example:- https://github.com/rase-/socket.io-php-emitter

CSS Display an Image Resized and Cropped

.imgContainer {
  overflow: hidden;
  width: 200px;
  height: 100px;
}
.imgContainer img {
  width: 200px;
  height: 120px;
}
<div class="imgContainer">
  <img src="imageSrc" />
</div>

The containing div with essentially crop the image by hiding the overflow.

How do I add a placeholder on a CharField in Django?

Great question. There are three solutions I know about:

Solution #1

Replace the default widget.

class SearchForm(forms.Form):  
    q = forms.CharField(
            label='Search',
            widget=forms.TextInput(attrs={'placeholder': 'Search'})
        )

Solution #2

Customize the default widget. If you're using the same widget that the field usually uses then you can simply customize that one instead of instantiating an entirely new one.

class SearchForm(forms.Form):  
    q = forms.CharField(label='Search')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['q'].widget.attrs.update({'placeholder': 'Search'})

Solution #3

Finally, if you're working with a model form then (in addition to the previous two solutions) you have the option to specify a custom widget for a field by setting the widgets attribute of the inner Meta class.

class CommentForm(forms.ModelForm):  
    class Meta:
        model = Comment
        widgets = {
            'body': forms.Textarea(attrs={'cols': 80, 'rows': 20})
        }

How do you resize a form to fit its content automatically?

This technique solved my problem:

In parent form:

frmEmployee frm = new frmEmployee();
frm.MdiParent = this;
frm.Dock = DockStyle.Fill;
frm.Show();

In the child form (Load event):

this.WindowState = FormWindowState.Maximized;

Get current rowIndex of table in jQuery

Try this,

$('td').click(function(){
   var row_index = $(this).parent().index();
   var col_index = $(this).index();
});

If you need the index of table contain td then you can change it to

var row_index = $(this).parent('table').index(); 

Decompile .smali files on an APK

I second that.

Dex2jar will generate a WORKING jar, which you can add as your project source, with the xmls you got from apktool.

However, JDGUI generates .java files which have ,more often than not, errors.

It has got something to do with code obfuscation I guess.

Can't specify the 'async' modifier on the 'Main' method of a console app

In Main try changing the call to GetList to:

Task.Run(() => bs.GetList());

isset PHP isset($_GET['something']) ? $_GET['something'] : ''

If you want an empty string default then a preferred way is one of these (depending on your need):

$str_value = strval($_GET['something']);
$trimmed_value = trim($_GET['something']);
$int_value = intval($_GET['somenumber']);

If the url parameter something doesn't exist in the url then $_GET['something'] will return null

strval($_GET['something']) -> strval(null) -> ""

and your variable $value is set to an empty string.

  • trim() might be prefered over strval() depending on code (e.g. a Name parameter might want to use it)
  • intval() if only numeric values are expected and the default is zero. intval(null) -> 0

Cases to consider:

...&something=value1&key2=value2 (typical)

...&key2=value2 (parameter missing from url $_GET will return null for it)

...&something=+++&key2=value (parameter is " ")

Why this is a preferred approach:

  • It fits neatly on one line and is clear what's going on.
  • It's readable than $value = isset($_GET['something']) ? $_GET['something'] : '';
  • Lower risk of copy/paste mistake or a typo: $value=isset($_GET['something'])?$_GET['somthing']:'';
  • It's compatible with older and newer php.

Update Strict mode may require something like this:

$str_value = strval(@$_GET['something']);
$trimmed_value = trim(@$_GET['something']);
$int_value = intval(@$_GET['somenumber']);

Checking to see if one array's elements are in another array in PHP

You could also use in_array as follows:

<?php
$found = null;
$people = array(3,20,2);
$criminals = array( 2, 4, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
foreach($people as $num) {
    if (in_array($num,$criminals)) {
        $found[$num] = true;
    } 
}
var_dump($found);
// array(2) { [20]=> bool(true)   [2]=> bool(true) }

While array_intersect is certainly more convenient to use, it turns out that its not really superior in terms of performance. I created this script too:

<?php
$found = null;
$people = array(3,20,2);
$criminals = array( 2, 4, 8, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
$fastfind = array_intersect($people,$criminals);
var_dump($fastfind);
// array(2) { [1]=> int(20)   [2]=> int(2) }

Then, I ran both snippets respectively at: http://3v4l.org/WGhO7/perf#tabs and http://3v4l.org/g1Hnu/perf#tabs and checked the performance of each. The interesting thing is that the total CPU time, i.e. user time + system time is the same for PHP5.6 and the memory also is the same. The total CPU time under PHP5.4 is less for in_array than array_intersect, albeit marginally so.

How to create hyperlink to call phone number on mobile devices?

- doesnt make matter but + sign is important when mobile user is in roaming
this is the standard format

<a href="tel:+4917640206387">+49 (0)176 - 402 063 87</a>

You can read more about it in the spec, see Make Telephone Numbers "Click-to-Call".

CSS no text wrap

Additionally to overflow:hidden, use

white-space:nowrap;

How to delete a module in Android Studio

Remove from File > File Structure > Dependencies > - button. Then if it is stull there you can remove the module by going to the settings.gradle file and removing it from the include line.

app.config for a class library

You do want to add App.config to your tests class library, if you're using a tracer/logger. Otherwise nothing gets logged when you run the test through a test runner such as TestDriven.Net.

For example, I use TraceSource in my programs, but running tests doesn't log anything unless I add an App.config file with the trace/log configuration to the test class library too.

Otherwise, adding App.config to a class library doesn't do anything.

Force div element to stay in same place, when page is scrolled

You can do this replacing position:absolute; by position:fixed;.

Add a auto increment primary key to existing table in oracle

Snagged from Oracle OTN forums

Use alter table to add column, for example:

alter table tableName add(columnName NUMBER);

Then create a sequence:

CREATE SEQUENCE SEQ_ID
START WITH 1
INCREMENT BY 1
MAXVALUE 99999999
MINVALUE 1
NOCYCLE;

and, the use update to insert values in column like this

UPDATE tableName SET columnName = seq_test_id.NEXTVAL

How to use PowerShell select-string to find more than one pattern in a file?

You can specify multiple patterns in an array.

select-string VendorEnquiry,Failed C:\Logs

This works with -notmatch as well:

select-string -notmatch VendorEnquiry,Failed C:\Logs

How to force maven update?

Just in case someone wants only update project's snapshot dependencies and doesn't want to install artifact:

mvn dependency:resolve -U

Don't forget to reimport dependencies in your IDE. In IDEA you need to right click on pom file and choose Maven -> Reimport

UILabel - auto-size label to fit text?

@implementation UILabel (UILabel_Auto)

- (void)adjustHeight {

    if (self.text == nil) {
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.bounds.size.width, 0);
        return;
    }

    CGSize aSize = self.bounds.size;
    CGSize tmpSize = CGRectInfinite.size;
    tmpSize.width = aSize.width;

    tmpSize = [self.text sizeWithFont:self.font constrainedToSize:tmpSize];

    self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, aSize.width, tmpSize.height);
}

@end

This is category method. You must set text first, than call this method to adjust UILabel's height.

how to convert a string to date in mysql?

As was told at MySQL Using a string column with date text as a date field, you can do

SELECT  STR_TO_DATE(yourdatefield, '%m/%d/%Y')
FROM    yourtable

You can also handle these date strings in WHERE clauses. For example

SELECT whatever
  FROM yourtable
 WHERE STR_TO_DATE(yourdatefield, '%m/%d/%Y') > CURDATE() - INTERVAL 7 DAY

You can handle all kinds of date/time layouts this way. Please refer to the format specifiers for the DATE_FORMAT() function to see what you can put into the second parameter of STR_TO_DATE().

How to pass parameters in GET requests with jQuery

The data parameter of ajax method allows you send data to server side.On server side you can request the data.See the code

var id=5;
$.ajax({
    type: "get",
    url: "url of server side script",
    data:{id:id},
    success: function(res){
        console.log(res);
    },
error:function(error)
{
console.log(error);
}
});

At server side receive it using $_GET variable.

$_GET['id'];

How to set value to form control in Reactive Forms in Angular

Try this.

editqueForm =  this.fb.group({
   user: [this.question.user],
   questioning: [this.question.questioning, Validators.required],
   questionType: [this.question.questionType, Validators.required],
   options: new FormArray([])
})

setValue() and patchValue()

if you want to set the value of one control, this will not work, therefor you have to set the value of both controls:

formgroup.setValue({name: ‘abc’, age: ‘25’});

It is necessary to mention all the controls inside the method. If this is not done, it will throw an error.

On the other hand patchvalue() is a lot easier on that part, let’s say you only want to assign the name as a new value:

formgroup.patchValue({name:’abc’});

Single quotes vs. double quotes in C or C++

Use single quote with single char as:

char ch = 'a';

here 'a' is a char constant and is equal to the ASCII value of char a.

Use double quote with strings as:

char str[] = "foo";

here "foo" is a string literal.

Its okay to use "a" but its not okay to use 'foo'

How to update column value in laravel

Version 1:

// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();

Version 2:

$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();

In case of answered question you can use them:

$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();

What is the best way to delete a component with CLI

Since it is not yet supported using angular CLI

so here is the possible way, before that please observe what happens when you create a component/service using CLI (ex. ng g c demoComponent).

  1. It creates a separate folder named demoComponent (ng g c demoComponent).
  2. It generate HTML,CSS,ts and a spec file dedicated to demoComponent.
  3. Also, It adds dependency inside app.module.ts file to add that component to your project.

so do it in reverse order

  1. Remove Dependency from app.module.ts
  2. Delete that component folder.

when removing the dependency you have to do two things.

  1. Remove the import line reference from app.module.ts file.
  2. Remove the component declaration from @NgModule declaration array in app.module.ts.

Conditional HTML Attributes using Razor MVC3

Note you can do something like this(at least in MVC3):

<td align="left" @(isOddRow ? "class=TopBorder" : "style=border:0px") >

What I believed was razor adding quotes was actually the browser. As Rism pointed out when testing with MVC 4(I haven't tested with MVC 3 but I assume behavior hasn't changed), this actually produces class=TopBorder but browsers are able to parse this fine. The HTML parsers are somewhat forgiving on missing attribute quotes, but this can break if you have spaces or certain characters.

<td align="left" class="TopBorder" >

OR

<td align="left" style="border:0px" >

What goes wrong with providing your own quotes

If you try to use some of the usual C# conventions for nested quotes, you'll end up with more quotes than you bargained for because Razor is trying to safely escape them. For example:

<button type="button" @(true ? "style=\"border:0px\"" : string.Empty)>

This should evaluate to <button type="button" style="border:0px"> but Razor escapes all output from C# and thus produces:

style=&quot;border:0px&quot;

You will only see this if you view the response over the network. If you use an HTML inspector, often you are actually seeing the DOM, not the raw HTML. Browsers parse HTML into the DOM, and the after-parsing DOM representation already has some niceties applied. In this case the Browser sees there aren't quotes around the attribute value, adds them:

style="&quot;border:0px&quot;"

But in the DOM inspector HTML character codes display properly so you actually see:

style=""border:0px""

In Chrome, if you right-click and select Edit HTML, it switch back so you can see those nasty HTML character codes, making it clear you have real outer quotes, and HTML encoded inner quotes.

So the problem with trying to do the quoting yourself is Razor escapes these.

If you want complete control of quotes

Use Html.Raw to prevent quote escaping:

<td @Html.Raw( someBoolean ? "rel='tooltip' data-container='.drillDown a'" : "" )>

Renders as:

<td rel='tooltip' title='Drilldown' data-container='.drillDown a'>

The above is perfectly safe because I'm not outputting any HTML from a variable. The only variable involved is the ternary condition. However, beware that this last technique might expose you to certain security problems if building strings from user supplied data. E.g. if you built an attribute from data fields that originated from user supplied data, use of Html.Raw means that string could contain a premature ending of the attribute and tag, then begin a script tag that does something on behalf of the currently logged in user(possibly different than the logged in user). Maybe you have a page with a list of all users pictures and you are setting a tooltip to be the username of each person, and one users named himself '/><script>$.post('changepassword.php?password=123')</script> and now any other user who views this page has their password instantly changed to a password that the malicious user knows.

jQuery Popup Bubble/Tooltip

Although qTip (the accepted answer) is good, I started using it, and it lacked some features I needed.

I then stumbled upon PoshyTip - it is very flexible, and really easy to use. (And I could do what I needed)

Equivalent to AssemblyInfo in dotnet core/csproj

Those settings has moved into the .csproj file.

By default they don't show up but you can discover them from Visual Studio 2017 in the project properties Package tab.

Project properties, tab Package

Once saved those values can be found in MyProject.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <Version>1.2.3.4</Version>
    <Authors>Author 1</Authors>
    <Company>Company XYZ</Company>
    <Product>Product 2</Product>
    <PackageId>MyApp</PackageId>
    <AssemblyVersion>2.0.0.0</AssemblyVersion>
    <FileVersion>3.0.0.0</FileVersion>
    <NeutralLanguage>en</NeutralLanguage>
    <Description>Description here</Description>
    <Copyright>Copyright</Copyright>
    <PackageLicenseUrl>License URL</PackageLicenseUrl>
    <PackageProjectUrl>Project URL</PackageProjectUrl>
    <PackageIconUrl>Icon URL</PackageIconUrl>
    <RepositoryUrl>Repo URL</RepositoryUrl>
    <RepositoryType>Repo type</RepositoryType>
    <PackageTags>Tags</PackageTags>
    <PackageReleaseNotes>Release</PackageReleaseNotes>
  </PropertyGroup>

In the file explorer properties information tab, FileVersion is shown as "File Version" and Version is shown as "Product version"

how to get multiple checkbox value using jquery

You can do it like this,

$('.ads_Checkbox:checked')

You can iterate through them with each() and fill the array with checkedbox values.

Live Demo

To get the values of selected checkboxes in array

var i = 0;
$('#save_value').click(function () {
       var arr = [];
       $('.ads_Checkbox:checked').each(function () {
           arr[i++] = $(this).val();
       });      
});

Edit, using .map()

You can also use jQuery.map with get() to get the array of selected checkboxe values.

As a side note using this.value instead of $(this).val() would give better performance.

Live Demo

$('#save_value').click(function(){
    var arr = $('.ads_Checkbox:checked').map(function(){
        return this.value;
    }).get();
}); 

JavaScript: Collision detection

Mozilla has a good article on this, with the code shown below.

2D collision detection

Rectangle collision

if (rect1.x < rect2.x + rect2.width &&
   rect1.x + rect1.width > rect2.x &&
   rect1.y < rect2.y + rect2.height &&
   rect1.height + rect1.y > rect2.y) {
    // Collision detected!
}

Circle collision

if (distance < circle1.radius + circle2.radius) {
    // Collision detected!
}

Python Serial: How to use the read or readline function to read more than 1 character at a time

I see a couple of issues.

First:

ser.read() is only going to return 1 byte at a time.

If you specify a count

ser.read(5)

it will read 5 bytes (less if timeout occurrs before 5 bytes arrive.)

If you know that your input is always properly terminated with EOL characters, better way is to use

ser.readline()

That will continue to read characters until an EOL is received.

Second:

Even if you get ser.read() or ser.readline() to return multiple bytes, since you are iterating over the return value, you will still be handling it one byte at a time.

Get rid of the

for line in ser.read():

and just say:

line = ser.readline()

Oracle: not a valid month

You can also change the value of this database parameter for your session by using the ALTER SESSION command and use it as you wanted

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY';
SELECT TO_DATE('05-12-2015') FROM dual;

05/12/2015

Accessing UI (Main) Thread safely in WPF

Use [Dispatcher.Invoke(DispatcherPriority, Delegate)] to change the UI from another thread or from background.

Step 1. Use the following namespaces

using System.Windows;
using System.Threading;
using System.Windows.Threading;

Step 2. Put the following line where you need to update UI

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
{
    //Update UI here
}));

Syntax

[BrowsableAttribute(false)]
public object Invoke(
  DispatcherPriority priority,
  Delegate method
)

Parameters

priority

Type: System.Windows.Threading.DispatcherPriority

The priority, relative to the other pending operations in the Dispatcher event queue, the specified method is invoked.

method

Type: System.Delegate

A delegate to a method that takes no arguments, which is pushed onto the Dispatcher event queue.

Return Value

Type: System.Object

The return value from the delegate being invoked or null if the delegate has no return value.

Version Information

Available since .NET Framework 3.0

How can I return the current action in an ASP.NET MVC view?

I know this is an older question, but I saw it and I thought you might be interested in an alternative version than letting your view handle retrieving the data it needs to do it's job.

An easier way in my opinion would be to override the OnActionExecuting method. You are passed the ActionExecutingContext that contains the ActionDescriptor member which you can use to obtain the information you are looking for, which is the ActionName and you can also reach the ControllerDescriptor and it contains the ControllerName.

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    ActionDescriptor actionDescriptor = filterContext.ActionDescriptor;
    string actionName = actionDescriptor.ActionName;
    string controllerName = actionDescriptor.ControllerDescriptor.ControllerName;
    // Now that you have the values, set them somewhere and pass them down with your ViewModel
    // This will keep your view cleaner and the controller will take care of everything that the view needs to do it's job.
}

Hope this helps. If anything, at least it will show an alternative for anybody else that comes by your question.

git push: permission denied (public key)

None of the above solutions worked for me. For context, I'm running ubuntu, and I had already gone through the ssh-key setup documentation. The fix for me was to run ssh-add in the terminal. This fixed the issue.

Source: http://baptiste-wicht.com/posts/2010/07/tip-how-to-solve-agent-admitted-failure-to-sign-using-the-key-error.html

How to set the min and max height or width of a Frame?

There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.

Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.

import Tkinter as tk

root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")

frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")

root.mainloop()

How to convert date in to yyyy-MM-dd Format?

String s;
Format formatter;
Date date = new Date();

// 2012-12-01
formatter = new SimpleDateFormat("yyyy-MM-dd");
s = formatter.format(date);
System.out.println(s);

How can I revert multiple Git commits (already pushed) to a published repository?

git revert HEAD -m 1

In the above code line. "Last argument represents"

  • 1 - reverts one commits. 2 - reverts last commits. n - reverts last n commits

or

git reset --hard siriwjdd

java.io.IOException: Broken pipe

Basically, what is happening is that your user is either closing the browser tab, or is navigating away to a different page, before communication was complete. Your webserver (Jetty) generates this exception because it is unable to send the remaining bytes.

org.eclipse.jetty.io.EofException: null
! at org.eclipse.jetty.http.HttpGenerator.flushBuffer(HttpGenerator.java:914)
! at org.eclipse.jetty.http.HttpGenerator.complete(HttpGenerator.java:798)
! at org.eclipse.jetty.server.AbstractHttpConnection.completeResponse(AbstractHttpConnection.java:642)
! 

This is not an error on your application logic side. This is simply due to user behavior. There is nothing wrong in your code per se.

There are two things you may be able to do:

  1. Ignore this specific exception so that you don't log it.
  2. Make your code more efficient/packed so that it transmits less data. (Not always an option!)

Catch KeyError in Python

If it's raising a KeyError with no message, then it won't print anything. If you do...

try:
    connection = manager.connect("I2Cx")
except Exception as e:
    print repr(e)

...you'll at least get the exception class name.

A better alternative is to use multiple except blocks, and only 'catch' the exceptions you intend to handle...

try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print 'I got a KeyError - reason "%s"' % str(e)
except IndexError as e:
    print 'I got an IndexError - reason "%s"' % str(e)

There are valid reasons to catch all exceptions, but you should almost always re-raise them if you do...

try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print 'I got a KeyError - reason "%s"' % str(e)
except:
    print 'I got another exception, but I should re-raise'
    raise

...because you probably don't want to handle KeyboardInterrupt if the user presses CTRL-C, nor SystemExit if the try-block calls sys.exit().

Using two values for one switch case statement

The case values are just codeless "goto" points that can share the same entry point:

case text1:
case text4: 
    //blah
    break;

Note that the braces are redundant.

ASP.NET MVC Ajax Error handling

After googling I write a simple Exception handing based on MVC Action Filter:

public class HandleExceptionAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest() && filterContext.Exception != null)
        {
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            filterContext.Result = new JsonResult
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = new
                {
                    filterContext.Exception.Message,
                    filterContext.Exception.StackTrace
                }
            };
            filterContext.ExceptionHandled = true;
        }
        else
        {
            base.OnException(filterContext);
        }
    }
}

and write in global.ascx:

 public static void RegisterGlobalFilters(GlobalFilterCollection filters)
 {
      filters.Add(new HandleExceptionAttribute());
 }

and then write this script on the layout or Master page:

<script type="text/javascript">
      $(document).ajaxError(function (e, jqxhr, settings, exception) {
                       e.stopPropagation();
                       if (jqxhr != null)
                           alert(jqxhr.responseText);
                     });
</script>

Finally you should turn on custom error. and then enjoy it :)

Can scripts be inserted with innerHTML?

You can also wrap your <script> like this and it will get executed:

<your target node>.innerHTML = '<iframe srcdoc="<script>alert(top.document.title);</script>"></iframe>';

Please note: The scope inside srcdoc refers to the iframe, so you have to use top like in the example above to access the parent document.

How to fix a Div to top of page with CSS only

You can simply make the top div fixed:

#top { position: fixed; top: 20px; left: 20px; }

How to properly add cross-site request forgery (CSRF) token using PHP

Security Warning: md5(uniqid(rand(), TRUE)) is not a secure way to generate random numbers. See this answer for more information and a solution that leverages a cryptographically secure random number generator.

Looks like you need an else with your if.

if (!isset($_SESSION['token'])) {
    $token = md5(uniqid(rand(), TRUE));
    $_SESSION['token'] = $token;
    $_SESSION['token_time'] = time();
}
else
{
    $token = $_SESSION['token'];
}

How to automatically convert strongly typed enum into int?

As many said, there is no way to automatically convert without adding overheads and too much complexity, but you can reduce your typing a bit and make it look better by using lambdas if some cast will be used a bit much in a scenario. That would add a bit of function overhead call, but will make code more readable compared to long static_cast strings as can be seen below. This may not be useful project wide, but only class wide.

#include <bitset>
#include <vector>

enum class Flags { ......, Total };
std::bitset<static_cast<unsigned int>(Total)> MaskVar;
std::vector<Flags> NewFlags;

-----------
auto scui = [](Flags a){return static_cast<unsigned int>(a); };

for (auto const& it : NewFlags)
{
    switch (it)
    {
    case Flags::Horizontal:
        MaskVar.set(scui(Flags::Horizontal));
        MaskVar.reset(scui(Flags::Vertical)); break;
    case Flags::Vertical:
        MaskVar.set(scui(Flags::Vertical));
        MaskVar.reset(scui(Flags::Horizontal)); break;

   case Flags::LongText:
        MaskVar.set(scui(Flags::LongText));
        MaskVar.reset(scui(Flags::ShorTText)); break;
    case Flags::ShorTText:
        MaskVar.set(scui(Flags::ShorTText));
        MaskVar.reset(scui(Flags::LongText)); break;

    case Flags::ShowHeading:
        MaskVar.set(scui(Flags::ShowHeading));
        MaskVar.reset(scui(Flags::NoShowHeading)); break;
    case Flags::NoShowHeading:
        MaskVar.set(scui(Flags::NoShowHeading));
        MaskVar.reset(scui(Flags::ShowHeading)); break;

    default:
        break;
    }
}

Print a list of all installed node.js modules

for package in `sudo npm -g ls --depth=0 --parseable`; do
    printf "${package##*/}\n";
done

Clone only one branch

I have done with below single git command:

git clone [url] -b [branch-name] --single-branch

changing iframe source with jquery

Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).

Example:

var divMapLoaded = false;
$("#container").scroll(function() {
    if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
    $("#map-iframe").html("<iframe id=\"map-iframe\" " +
        "width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
        "marginheight=\"0\" marginwidth=\"0\" " +
        "src=\"http://www.google.it/maps?t=m&amp;cid=0x3e589d98063177ab&amp;ie=UTF8&amp;iwloc=A&amp;brcurrent=5,0,1&amp;ll=41.123115,16.853177&amp;spn=0.005617,0.009943&amp;output=embed\"" +
        "></iframe>");
    divMapLoaded = true;
}

How does Java deal with multiple conditions inside a single IF statement

Yes,that is called short-circuiting.

Please take a look at this wikipedia page on short-circuiting

Where can I download english dictionary database in a text format?

The Gutenberg Project hosts Webster's Unabridged English Dictionary plus many other public domain literary works. Actually it looks like they've got several versions of the dictionary hosted with copyright from different years. The one I linked has a 2009 copyright. You may want to poke around the site and investigate the different versions of Webster's dictionary.

Jetty: HTTP ERROR: 503/ Service Unavailable

None of these answers worked for me.

I had to remove all deployed java web app:

  • Windows/Show View/Other...
  • Go the the Server folder and select "Servers"
  • Right-click on the J2EE Preview at localhost
  • Click to Add and Remove... Click Remove all

Then run the project on the server

The Error is gone!

You will have to stop the server before deploying another project because it will not be found by the server. Otherwise you will get a 404 error

What is the C# equivalent of friend?

There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.

Given a class with this definition:

public class Class1
{
    private int CallMe()
    {
        return 1;
    }
}

You can invoke it using this code:

Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);

int result = (int)callMeMethod.Invoke(c, null);

Console.WriteLine(result);

If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..."

Group dataframe and get sum AND count?

try this:

In [110]: (df.groupby('Company Name')
   .....:    .agg({'Organisation Name':'count', 'Amount': 'sum'})
   .....:    .reset_index()
   .....:    .rename(columns={'Organisation Name':'Organisation Count'})
   .....: )
Out[110]:
          Company Name   Amount  Organisation Count
0  Vifor Pharma UK Ltd  4207.93                   5

or if you don't want to reset index:

df.groupby('Company Name')['Amount'].agg(['sum','count'])

or

df.groupby('Company Name').agg({'Amount': ['sum','count']})

Demo:

In [98]: df.groupby('Company Name')['Amount'].agg(['sum','count'])
Out[98]:
                         sum  count
Company Name
Vifor Pharma UK Ltd  4207.93      5

In [99]: df.groupby('Company Name').agg({'Amount': ['sum','count']})
Out[99]:
                      Amount
                         sum count
Company Name
Vifor Pharma UK Ltd  4207.93     5

Ignore files that have already been committed to a Git repository

Complex answers everywhere!

Just use the following

git rm -r --cached .

It will remove the files you are trying to ignore from the origin and not from the master on your computer!

After that just commit and push!

How to get just one file from another branch

Supplemental to VonC's and chhh's answers.

git show experiment:path/to/relative/app.js > app.js
# If your current working directory is relative than just use
git show experiment:app.js > app.js

or

git checkout experiment -- app.js

How do I run a spring boot executable jar in a Production environment?

By far the most easiest and reliable way to run Spring Boot applications in production is with Docker. Use Docker Compose, Docker Swarm or Kubernetes if you need to use multiple connected services.

Here's a simple Dockerfile from the official Spring Boot Docker guide to get you started:

FROM frolvlad/alpine-oraclejdk8:slim
VOLUME /tmp
ADD YOUR-APP-NAME.jar app.jar
RUN sh -c 'touch /app.jar'
ENV JAVA_OPTS=""
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]

Here's a sample command line to run the container as a daemon:

docker run \
  -d --restart=always \
  -e "SPRING_PROFILES_ACTIVE=prod" \
  -p 8080:8080 \
  prefix/imagename

Align text to the bottom of a div

Flex Solution

It is perfectly fine if you want to go with the display: table-cell solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;. flex is something which has a decent support.

_x000D_
_x000D_
.wrap {_x000D_
  height: 200px;_x000D_
  width: 200px;_x000D_
  border: 1px solid #aaa;_x000D_
  margin: 10px;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.wrap span {_x000D_
  align-self: flex-end;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <span>Align me to the bottom</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In the above example, we first set the parent element to display: flex; and later, we use align-self to flex-end. This helps you push the item to the end of the flex parent.


Old Solution (Valid if you are not willing to use flex)

If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell; with vertical-align: bottom; is enough

_x000D_
_x000D_
div {_x000D_
  display: table-cell;_x000D_
  vertical-align: bottom;_x000D_
  border: 1px solid #f00;_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
}
_x000D_
<div>Hello</div>
_x000D_
_x000D_
_x000D_

(Or JSFiddle)

Set background color of WPF Textbox in C# code

I know this has been answered in another SOF post. However, you could do this if you know the hexadecimal.

textBox1.Background = (SolidColorBrush)new BrushConverter().ConvertFromString("#082049");

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

This is intended behavior.

When you make an HTTP request, the server normally returns code 200 OK. If you set If-Modified-Since, the server may return 304 Not modified (and the response will not have the content). This is supposed to be your cue that the page has not been modified.

The authors of the class have foolishly decided that 304 should be treated as an error and throw an exception. Now you have to clean up after them by catching the exception every time you try to use If-Modified-Since.

Android Studio: Application Installation Failed

In real device do below tasks..

1.clean all cache memory.

2.check the internal storage space (if space is just 500 mb free, then remove some data or app in the internal storage maintain at least 1 gb space.

3.again do clean all cache memory.

4.now goto android studio or eclipse click on app goto run select the device and run I hope app will install and it will run..!!!

TempData keep() vs peek()

When an object in a TempDataDictionary is read, it will be marked for deletion at the end of that request.

That means if you put something on TempData like

TempData["value"] = "someValueForNextRequest";

And on another request you access it, the value will be there but as soon as you read it, the value will be marked for deletion:

//second request, read value and is marked for deletion
object value = TempData["value"];

//third request, value is not there as it was deleted at the end of the second request
TempData["value"] == null

The Peek and Keep methods allow you to read the value without marking it for deletion. Say we get back to the first request where the value was saved to TempData.

With Peek you get the value without marking it for deletion with a single call, see msdn:

//second request, PEEK value so it is not deleted at the end of the request
object value = TempData.Peek("value");

//third request, read value and mark it for deletion
object value = TempData["value"];

With Keep you specify a key that was marked for deletion that you want to keep. Retrieving the object and later on saving it from deletion are 2 different calls. See msdn

//second request, get value marking it from deletion
object value = TempData["value"];
//later on decide to keep it
TempData.Keep("value");

//third request, read value and mark it for deletion
object value = TempData["value"];

You can use Peek when you always want to retain the value for another request. Use Keep when retaining the value depends on additional logic.

You have 2 good questions about how TempData works here and here

Hope it helps!

How to configure SMTP settings in web.config

Set IIS to forward your mail to the remote server. The specifics vary greatly depending on the version of IIS. For IIS 7.5:

  1. Open IIS Manager
  2. Connect to your server if needed
  3. Select the server node; you should see an SMTP option on the right in the ASP.NET section
  4. Double-click the SMTP icon.
  5. Select the "Deliver e-mail to SMTP server" option and enter your server name, credentials, etc.

Check for database connection, otherwise display message

Try this:

<?php
$servername   = "localhost";
$database = "database";
$username = "user";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
  echo "Connected successfully";
?>

What is the difference between `Enum.name()` and `Enum.toString()`?

Use toString when you need to display the name to the user.

Use name when you need the name for your program itself, e.g. to identify and differentiate between different enum values.

How to convert characters to HTML entities using plain JavaScript

Best solution is posted at phpjs.org implementation of PHP function htmlentities

The format is htmlentities(string, quote_style, charset, double_encode) Full documentation on the PHP function which is identical can be read here

Setting width and height

In my case, passing responsive: false under options solved the problem. I'm not sure why everybody is telling you to do the opposite, especially since true is the default.

Converting Hexadecimal String to Decimal Integer

My way:

private static int hexToDec(String hex) {
    return Integer.parseInt(hex, 16);
}

Error: Unable to run mksdcard SDK tool

Just to say 16.04, I'm running

sudo apt-get install lib32z1 lib32ncurses5 libbz2-1.0:i386 lib32stdc++6

seems to work on a vanilla install after installing oracle-jdk-8

How Stuff and 'For Xml Path' work in SQL Server?

Declare @Temp As Table (Id Int,Name Varchar(100))
Insert Into @Temp values(1,'A'),(1,'B'),(1,'C'),(2,'D'),(2,'E'),(3,'F'),(3,'G'),(3,'H'),(4,'I'),(5,'J'),(5,'K')
Select X.ID,
stuff((Select ','+ Z.Name from @Temp Z Where X.Id =Z.Id For XML Path('')),1,1,'')
from @Temp X
Group by X.ID

VBA Check if variable is empty

For a number, it is tricky because if a numeric cell is empty VBA will assign a default value of 0 to it, so it is hard for your VBA code to tell the difference between an entered zero and a blank numeric cell.

The following check worked for me to see if there was an actual 0 entered into the cell:

If CStr(rng.value) = "0" then
    'your code here'
End If

Make the image go behind the text and keep it in center using CSS

Make it a background image that is centered.

.wrapper {background:transparent url(yourimage.jpg) no-repeat center center;}

<div class="wrapper">
 ...input boxes and labels and submit button here
</div>

Visual Studio Code always asking for git credentials

All I had to do was to run this command:

git config --global credential.helper wincred

Then I was prompted for password twice.

Next time it worked without prompting me for password.

LINQ .Any VS .Exists - What's the difference?

When you correct the measurements - as mentioned above: Any and Exists, and adding average - we'll get following output:

Executing search Exists() 1000 times ... 
Average Exists(): 35566,023
Fastest Exists() execution: 32226 

Executing search Any() 1000 times ... 
Average Any(): 58852,435
Fastest Any() execution: 52269 ticks

Benchmark finished. Press any key.

Microsoft.ACE.OLEDB.12.0 provider is not registered

I've got the same error on a fully updated Windows Vista Family 64bit with a .NET application that I've compiled to 32 bit only - the program is installed in the programx86 folder on 64 bit machines. It fails with this error message even with 2007 access database provider installed, with/wiothout the SP2 of the same installed, IIS installed and app pool set for 32bit app support... yes I've tried every solution everywhere and still no success.

I switched my app to ACE OLE DB.12.0 because JET4.0 was failing on 64bit machines - and it's no better :-/ The most promising thread I've found was this:

http://ellisweb.net/2010/01/connecting-to-excel-and-access-files-using-net-on-a-64-bit-server/

but when you try to install the 64 bit "2010 Office System Driver Beta: Data Connectivity Components" it tells you that you can't install the 64 bit version without uninstalling all 32bit office applications... and installing the 32 bit version of 2010 Office System Driver Beta: Data Connectivity Components doesn't solve the initial problem, even with "Microsoft.ACE.OLEDB.12.0" as provider instead of "Microsoft.ACE.OLEDB.14.0" which that page (and others) recommend.

My next attempt will be to follow this post:

The issue is due to the wrong flavor of OLEDB32.DLL and OLEDB32r.DLL being registered on the server. If the 64 bit versions are registered, they need to be unregistered, and then the 32 bit versions registered instead. To fix this, unregister the versions located in %Program Files%/Common Files/System/OLE DB. Then register the versions at the same path but in the %Program Files (x86)% directory.

Has anyone else had so much trouble with both JET4.0 and OLEDB ACE providers on 64 bit machines? Has anyone found a solution if none of the others work?

How do I set the default value for an optional argument in Javascript?

If str is null, undefined or 0, this code will set it to "hai"

function(nodeBox, str) {
  str = str || "hai";
.
.
.

If you also need to pass 0, you can use:

function(nodeBox, str) {
  if (typeof str === "undefined" || str === null) { 
    str = "hai"; 
  }
.
.
.

Find duplicates and delete all in notepad++

If it is possible to change the sequence of the lines you could do:

  1. sort line with Edit -> Line Operations -> Sort Lines Lexicographically ascending
  2. do a Find / Replace:
    • Find What: ^(.*\r?\n)\1+
    • Replace with: (Nothing, leave empty)
    • Check Regular Expression in the lower left
    • Click Replace All

How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n) and captures the line in \1 then it continues and tries to find \1 one or more times (+) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.

The \r?\n should deal nicely with Windows and Unix lineendings.

Uninstall Eclipse under OSX?

BTW. AppZapper is a great OSX tool for uninstalling apps and their preferences.

It sometimes comes a part of MacHeist

How to check if number is divisible by a certain number?

n % x == 0

Means that n can be divided by x. So... for instance, in your case:

boolean isDivisibleBy20 = number % 20 == 0;

Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:

boolean even = (number & 1) == 0;
boolean odd  = (number & 1) != 0;

Get element from within an iFrame

If iframe is not in the same domain such that you cannot get access to its internals from the parent but you can modify the source code of the iframe then you can modify the page displayed by the iframe to send messages to the parent window, which allows you to share information between the pages. Some sources:

Android - java.lang.SecurityException: Permission Denial: starting Intent

Add android:exported="true" in your 'com.example.lib.MainActivity' activity tag.

From the android:exported documentation,

android:exported Whether or not the activity can be launched by components of other applications — "true" if it can be, and "false" if not. If "false", the activity can be launched only by components of the same application or applications with the same user ID.

From your logcat output, clearly a mismatch in uid is causing the issue. So adding the android:exported="true" should do the trick.

Failed to start mongod.service: Unit mongod.service not found

[Solution]

Just type

sudo mongod

It will work.

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

I faced similar problem on windows server 2012 STD 64 bit , my problem is resolved after updating windows with all available windows updates.

Find files with size in Unix

Find can be used to print out the file-size in bytes with %s as a printf. %h/%f prints the directory prefix and filename respectively. \n forces a newline.

Example

find . -size +10000k -printf "%h/%f,%s\n"

Output

./DOTT/extract/DOTT/TENTACLE.001,11358470
./DOTT/Day Of The Tentacle.nrg,297308316
./DOTT/foo.iso,297001116

Is the order of elements in a JSON list preserved?

Some JavaScript engines keep keys in insertion order. V8, for instance, keeps all keys in insertion order except for keys that can be parsed as unsigned 32-bit integers.

This means that if you run either of the following:

var animals = {};
animals['dog'] = true;
animals['bear'] = true;
animals['monkey'] = true;
for (var animal in animals) {
  if (animals.hasOwnProperty(animal)) {
    $('<li>').text(animal).appendTo('#animals');
  }
}
var animals = JSON.parse('{ "dog": true, "bear": true, "monkey": true }');
for (var animal in animals) {
  $('<li>').text(animal).appendTo('#animals');
}

You'll consistently get dog, bear, and monkey in that order, on Chrome, which uses V8. Node.js also uses V8. This will hold true even if you have thousands of items. YMMV with other JavaScript engines.

Demo here and here.

How to check if another instance of the application is running

It's not sure what you mean with 'the program', but if you want to limit your application to one instance then you can use a Mutex to make sure that your application isn't already running.

[STAThread]
static void Main()
{
    Mutex mutex = new System.Threading.Mutex(false, "MyUniqueMutexName");
    try
    {
        if (mutex.WaitOne(0, false))
        {
            // Run the application
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
        else
        {
            MessageBox.Show("An instance of the application is already running.");
        }
    }
    finally
    {
        if (mutex != null)
        {
            mutex.Close();
            mutex = null;
        }
    }
}

Subtract two variables in Bash

White space is important, expr expects its operands and operators as separate arguments. You also have to capture the output. Like this:

COUNT=$(expr $FIRSTV - $SECONDV)

but it's more common to use the builtin arithmetic expansion:

COUNT=$((FIRSTV - SECONDV))

Is there a way to compile node.js source files?

I maybe very late but you can use "nexe" module that compile nodejs + your script in one executable: https://github.com/crcn/nexe