Programs & Examples On #Colon

This tag refers to the ASCII colon (:) character.

What does the colon (:) operator do?

You usually see it in the ternary assignment operator;

Syntax

variable =  `condition ? result 1 : result 2;`

example:

boolean isNegative = number > 0 ? false : true;

which is "equivalent" in nature to the if else

if(number > 0){
    isNegative = false;
}
else{
    isNegative = true;
}

Other than examples given by different posters,

you can also use : to signify a label for a block which you can use in conjunction with continue and break..

for example:

public void someFunction(){
     //an infinite loop
     goBackHere: { //label
          for(int i = 0; i < 10 ;i++){
               if(i == 9 ) continue goBackHere;
          }
     }
}

Maven build debug in Eclipse

Easiest way I find is to:

  1. Right click project

  2. Debug as -> Maven build ...

  3. In the goals field put -Dmaven.surefire.debug test

  4. In the parameters put a new parameter called forkCount with a value of 0 (previously was forkMode=never but it is deprecated and doesn't work anymore)

Set your breakpoints down and run this configuration and it should hit the breakpoint.

How to get the file path from URI?

File myFile = new File(uri.toString());
myFile.getAbsolutePath()

should return u the correct path

EDIT

As @Tron suggested the working code is

File myFile = new File(uri.getPath());
myFile.getAbsolutePath()

jQuery + client-side template = "Syntax error, unrecognized expression"

EugeneXa mentioned it in a comment, but it deserves to be an answer:

var template = $("#modal_template").html().trim();

This trims the offending whitespace from the beginning of the string. I used it with Mustache, like so:

var markup = Mustache.render(template, data);
$(markup).appendTo(container);

Connecting to Oracle Database through C#?

Using Nuget

  1. Right click Project, select Manage NuGet packages...
  2. Select the Browse tab, search for Oracle and install Oracle.ManagedDataAccess

Oracle NuGet package

  1. In code use the following command (Ctrl+. to automatically add the using directive).

  2. Note the different DataSource string which in comparison to Java is different.

    // create connection
    OracleConnection con = new OracleConnection();
    
    // create connection string using builder
    OracleConnectionStringBuilder ocsb = new OracleConnectionStringBuilder();
    ocsb.Password = "autumn117";
    ocsb.UserID = "john";
    ocsb.DataSource = "database.url:port/databasename";
    
    // connect
    con.ConnectionString = ocsb.ConnectionString;
    con.Open();
    Console.WriteLine("Connection established (" + con.ServerVersion + ")");
    

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

For me, this js reproduces the same problem that happens with Paola

My solution:

$(document.body).tooltip({selector: '[title]'})
.on('click mouseenter mouseleave','[title]', function(ev) {
    $(this).tooltip('mouseenter' === ev.type? 'show': 'hide');
});

Rotate a div using javascript

To rotate a DIV we can add some CSS that, well, rotates the DIV using CSS transform rotate.

To toggle the rotation we can keep a flag, a simple variable with a boolean value that tells us what way to rotate.

var rotated = false;

document.getElementById('button').onclick = function() {
    var div = document.getElementById('div'),
        deg = rotated ? 0 : 66;

    div.style.webkitTransform = 'rotate('+deg+'deg)'; 
    div.style.mozTransform    = 'rotate('+deg+'deg)'; 
    div.style.msTransform     = 'rotate('+deg+'deg)'; 
    div.style.oTransform      = 'rotate('+deg+'deg)'; 
    div.style.transform       = 'rotate('+deg+'deg)'; 

    rotated = !rotated;
}

_x000D_
_x000D_
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    var div = document.getElementById('div'),_x000D_
        deg = rotated ? 0 : 66;_x000D_
_x000D_
    div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
    div.style.mozTransform    = 'rotate('+deg+'deg)'; _x000D_
    div.style.msTransform     = 'rotate('+deg+'deg)'; _x000D_
    div.style.oTransform      = 'rotate('+deg+'deg)'; _x000D_
    div.style.transform       = 'rotate('+deg+'deg)'; _x000D_
    _x000D_
    rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

To add some animation to the rotation all we have to do is add CSS transitions

div {
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
}

_x000D_
_x000D_
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    var div = document.getElementById('div'),_x000D_
        deg = rotated ? 0 : 66;_x000D_
_x000D_
    div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
    div.style.mozTransform    = 'rotate('+deg+'deg)'; _x000D_
    div.style.msTransform     = 'rotate('+deg+'deg)'; _x000D_
    div.style.oTransform      = 'rotate('+deg+'deg)'; _x000D_
    div.style.transform       = 'rotate('+deg+'deg)'; _x000D_
    _x000D_
    rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
    -webkit-transition: all 0.5s ease-in-out;_x000D_
    -moz-transition: all 0.5s ease-in-out;_x000D_
    -o-transition: all 0.5s ease-in-out;_x000D_
    transition: all 0.5s ease-in-out;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

Another way to do it is using classes, and setting all the styles in a stylesheet, thus keeping them out of the javascript

document.getElementById('button').onclick = function() {
    document.getElementById('div').classList.toggle('rotated');
}

_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    document.getElementById('div').classList.toggle('rotated');_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
    -webkit-transition: all 0.5s ease-in-out;_x000D_
    -moz-transition: all 0.5s ease-in-out;_x000D_
    -o-transition: all 0.5s ease-in-out;_x000D_
    transition: all 0.5s ease-in-out;_x000D_
}_x000D_
_x000D_
#div.rotated {_x000D_
    -webkit-transform : rotate(66deg); _x000D_
    -moz-transform : rotate(66deg); _x000D_
    -ms-transform : rotate(66deg); _x000D_
    -o-transform : rotate(66deg); _x000D_
    transform : rotate(66deg); _x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

enable cors in .htaccess

Will be work 100%, Apply in .htaccess:

# Enable cross domain access control
SetEnvIf Origin "^http(s)?://(.+\.)?(1xyz\.com|2xyz\.com)$" REQUEST_ORIGIN=$0
Header always set Access-Control-Allow-Origin %{REQUEST_ORIGIN}e env=REQUEST_ORIGIN
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "x-test-header, Origin, X-Requested-With, Content-Type, Accept"

# Force to request 200 for options
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule .* / [R=200,L]

How to use data-binding with Fragment

Try this in Android DataBinding

FragmentMainBinding binding;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_main, container, false);
        View rootView = binding.getRoot();
        initInstances(savedInstanceState);
        return rootView;
}

Is there any way to debug chrome in any IOS device

If you don't need full debugging support, you can now view JavaScript console logs directly within Chrome for iOS at chrome://inspect.

https://blog.chromium.org/2019/03/debugging-websites-in-chrome-for-ios.html

Chrome for iOS Console

MS SQL Date Only Without Time

DATEADD(d, 0, DATEDIFF(d, 0, [tstamp]))

Edit: While this will remove the time portion of your datetime, it will also make the condition non SARGable. If that's important for this query, an indexed view or a between clause is more appropriate.

Resetting a multi-stage form with jQuery

here is my solution, which also works with the new html5 input-types:

/**
 * removes all value attributes from input/textarea/select-fields the element with the given css-selector
 * @param {string} ele css-selector of the element | #form_5
 */
function clear_form_elements(ele) {
    $(ele).find(':input').each(function() {
        switch (this.type) {
            case 'checkbox':
            case 'radio':
                this.checked = false;
            default:
                $(this).val('');
                break;
        }
    });
}

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

After using following load balancer setting my problem solved for wss but for ws problem still exists for specific one ISP.

calssic-load-balancer

Nginx reverse proxy causing 504 Gateway Timeout

If you want to increase or add time limit to all sites then you can add below lines to the nginx.conf file.

Add below lines to the http section of /usr/local/etc/nginx/nginx.conf or /etc/nginx/nginx.conf file.

fastcgi_read_timeout 600;
proxy_read_timeout 600;

If the above lines doesn't exist in conf file then add them, otherwise increase fastcgi_read_timeout and proxy_read_timeout to make sure that nginx and php-fpm did not timeout.

To increase time limit for only one site then you can edit in vim /etc/nginx/sites-available/example.com

location ~ \.php$ {
    include /etc/nginx/fastcgi_params;
        fastcgi_pass  unix:/var/run/php5-fpm.sock;
    fastcgi_read_timeout 300; 
}

and after adding these lines in nginx.conf, then don't forget to restart nginx.

service php7-fpm reload 
service nginx reload

or, if you're using valet then simply type valet restart.

How do I check if a string contains another string in Objective-C?

With iOS 8 and Swift, we can use localizedCaseInsensitiveContainsString method

 let string: NSString = "Café"
 let substring: NSString = "É"

 string.localizedCaseInsensitiveContainsString(substring) // true

Show SOME invisible/whitespace characters in Eclipse

I use Checkstlye plugin for such a purpose. In Checkstyle configuration, I add special regexp rules to detect lines with TABs and then mark such lines as checkstyle ERROR, which is clearly visible in Eclipse editor. Works fine.

Reset the Value of a Select Box

use the .val('') setter

jsfiddle example

$('select').val('1');

Can you nest html forms?

In a word, no. You can have several forms in a page but they should not be nested.

From the html5 working draft:

4.10.3 The form element

Content model:

Flow content, but with no form element descendants.

Using a string variable as a variable name

You can use setattr

name  = 'varname'
value = 'something'

setattr(self, name, value) #equivalent to: self.varname= 'something'

print (self.varname)
#will print 'something'

But, since you should inform an object to receive the new variable, this only works inside classes or modules.

Difference Between $.getJSON() and $.ajax() in jQuery

Content-type

You don't need to specify that content-type on calls to MVC controller actions. The special "application/json; charset=utf-8" content-type is only necessary when calling ASP.NET AJAX "ScriptServices" and page methods. jQuery's default contentType of "application/x-www-form-urlencoded" is appropriate for requesting an MVC controller action.

More about that content-type here: JSON Hijacking and How ASP.NET AJAX 1.0 Avoids these Attacks

Data

The data is correct as you have it. By passing jQuery a JSON object, as you have, it will be serialized as patientID=1 in the POST data. This standard form is how MVC expects the parameters.

You only have to enclose the parameters in quotes like "{ 'patientID' : 1 }" when you're using ASP.NET AJAX services. They expect a single string representing a JSON object to be parsed out, rather than the individual variables in the POST data.

JSON

It's not a problem in this specific case, but it's a good idea to get in the habit of quoting any string keys or values in your JSON object. If you inadvertently use a JavaScript reserved keyword as a key or value in the object, without quoting it, you'll run into a confusing-to-debug problem.

Conversely, you don't have to quote numeric or boolean values. It's always safe to use them directly in the object.

So, assuming you do want to POST instead of GET, your $.ajax() call might look like this:

$.ajax({
  type: 'POST',
  url: '/Services/GetPatient',
  data: { 'patientID' : 1 },
  dataType: 'json',
  success: function(jsonData) {
    alert(jsonData);
  },
  error: function() {
    alert('Error loading PatientID=' + id);
  }
});

failed to lazily initialize a collection of role

as suggested here solving the famous LazyInitializationException is one of the following methods:

(1) Use Hibernate.initialize

Hibernate.initialize(topics.getComments());

(2) Use JOIN FETCH

You can use the JOIN FETCH syntax in your JPQL to explicitly fetch the child collection out. This is somehow like EAGER fetching.

(3) Use OpenSessionInViewFilter

LazyInitializationException often occurs in the view layer. If you use Spring framework, you can use OpenSessionInViewFilter. However, I do not suggest you to do so. It may leads to a performance issue if not used correctly.

Converting from hex to string

My Net 5 solution that also handles null characters at the end:

hex = ConvertFromHex( hex.AsSpan(), Encoding.Default );

static string ConvertFromHex( ReadOnlySpan<char> hexString, Encoding encoding )
{
    int realLength = 0;
    for ( int i = hexString.Length - 2; i >= 0; i -= 2 )
    {
        byte b = byte.Parse( hexString.Slice( i, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
        if ( b != 0 ) //not NULL character
        {
            realLength = i + 2;
            break;
        }
    }
    
    var bytes = new byte[realLength / 2];
    for ( var i = 0; i < bytes.Length; i++ )
    {
        bytes[i] = byte.Parse( hexString.Slice( i * 2, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
    }

    return encoding.GetString( bytes );
}

What should I do if the current ASP.NET session is null?

If your Session instance is null and your in an 'ashx' file, just implement the 'IRequiresSessionState' interface.

This interface doesn't have any members so you just need to add the interface name after the class declaration (C#):

public class MyAshxClass : IHttpHandler, IRequiresSessionState

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController'

Make sure that you have added ojdbc14.jar into your library.

For oracle 11g, usie ojdbc6.jar.

How to remove MySQL root password

I have also been through this problem,

First i tried setting my password of root to blank using command :

SET PASSWORD FOR root@localhost=PASSWORD('');

But don't be happy , PHPMYADMIN uses 127.0.0.1 not localhost , i know you would say both are same but that is not the case , use the command mentioned underneath and you are done.

SET PASSWORD FOR [email protected]=PASSWORD('');

Just replace localhost with 127.0.0.1 and you are done .

Why is this error, 'Sequence contains no elements', happening?

In the following line.

temp.Response = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();

You are calling First but the collection returned from db.Responses.Where is empty.

Trigger event on body load complete js/jquery

The below code will call a function while the script is done loading

<html>
 <body></body>
<script>
 call();
 function call(){ alert("Hello Word");}
</script>
</html>

Format date and time in a Windows batch script

As has been noted, parsing the date and time is only useful if you know the format being used by the current user (for example, MM/dd/yy or dd-MM-yyyy just to name two). This could be determined, but by the time you do all the stressing and parsing, you will still end up with some situation where there is an unexpected format used, and more tweaks will be be necessary.

You can also use some external program that will return a date slug in your preferred format, but that has disadvantages of needing to distribute the utility program with your script/batch.

There are also batch tricks using the CMOS clock in a pretty raw way, but that is tooo close to bare wires for most people, and also not always the preferred place to retrieve the date/time.

Below is a solution that avoids the above problems. Yes, it introduces some other issues, but for my purposes I found this to be the easiest, clearest, most portable solution for creating a datestamp in .bat files for modern Windows systems. This is just an example, but I think you will see how to modify for other date and/or time formats, etc.

reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f
reg add "HKCU\Control Panel\International" /v sShortDate /d "yyMMdd" /f
@REM reg query "HKCU\Control Panel\International" /v sShortDate
set LogDate=%date%
reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f

Select the first 10 rows - Laravel Eloquent

The simplest way in laravel 5 is:

$listings=Listing::take(10)->get();

return view('view.name',compact('listings'));

Android fade in and fade out with ImageView

you can do it by two simple point and change in your code

1.In your xml in anim folder of your project, Set the fade in and fade out duration time not equal

2.In you java class before the start of fade out animation, set second imageView visibility Gone then after fade out animation started set second imageView visibility which you want to fade in visible

fadeout.xml

<alpha
    android:duration="4000"
    android:fromAlpha="1.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="0.0" />

fadein.xml

<alpha
    android:duration="6000"
    android:fromAlpha="0.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="1.0" />

In you java class

Animation animFadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);
    ImageView iv = (ImageView) findViewById(R.id.imageView1);
    ImageView iv2 = (ImageView) findViewById(R.id.imageView2);
    iv.setVisibility(View.VISIBLE);
    iv2.setVisibility(View.GONE);
    animFadeOut.reset();
    iv.clearAnimation();
    iv.startAnimation(animFadeOut);

    Animation animFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
    iv2.setVisibility(View.VISIBLE);
    animFadeIn.reset();
    iv2.clearAnimation();
    iv2.startAnimation(animFadeIn);

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

Friend, don't worry, if you have any application installed built in codeigniter and you wanna add some language pack just follow these steps:

1. Add language files in folder application/language/arabic (i add arabic lang in sma2 built in ci)

2. Go to the file named setting.php in application/modules/settings/views/setting.php. Here you find the array

<?php /*

 $lang = array (
  'english' => 'English',

  'arabic' => 'Arabic',  // i add this here

  'spanish' => 'Español'

Now save and run the application. It's worked fine.

How to write URLs in Latex?

A minimalist implementation of the \url macro that uses only Tex primitives:

\def\url#1{\expandafter\string\csname #1\endcsname}

This url absolutely won't break over lines, though; the hypperef package is better for that.

How do I correctly setup and teardown for my pytest class with tests?

When you write "tests defined as class methods", do you really mean class methods (methods which receive its class as first parameter) or just regular methods (methods which receive an instance as first parameter)?

Since your example uses self for the test methods I'm assuming the latter, so you just need to use setup_method instead:

class Test:

    def setup_method(self, test_method):
        # configure self.attribute

    def teardown_method(self, test_method):
        # tear down self.attribute

    def test_buttons(self):
        # use self.attribute for test

The test method instance is passed to setup_method and teardown_method, but can be ignored if your setup/teardown code doesn't need to know the testing context. More information can be found here.

I also recommend that you familiarize yourself with py.test's fixtures, as they are a more powerful concept.

What is the most efficient way to deep clone an object in JavaScript?

I am late to answer this question, but I have an another way of cloning the object:

function cloneObject(obj) {
    if (obj === null || typeof(obj) !== 'object')
        return obj;
    var temp = obj.constructor(); // changed
    for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
            obj['isActiveClone'] = null;
            temp[key] = cloneObject(obj[key]);
            delete obj['isActiveClone'];
        }
    }
    return temp;
}

var b = cloneObject({"a":1,"b":2});   // calling

which is much better and faster then:

var a = {"a":1,"b":2};
var b = JSON.parse(JSON.stringify(a));  

and

var a = {"a":1,"b":2};

// Deep copy
var newObject = jQuery.extend(true, {}, a);

I have bench-marked the code and you can test the results here:

and sharing the results: enter image description here References: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

How can I remove time from date with Moment.js?

formatCalendarDate = function (dateTime) {
    return moment.utc(dateTime).format('LL')
}

Checking for the correct number of arguments

#!/bin/sh
if [ "$#" -ne 1 ] || ! [ -d "$1" ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi

Translation: If number of arguments is not (numerically) equal to 1 or the first argument is not a directory, output usage to stderr and exit with a failure status code.

More friendly error reporting:

#!/bin/sh
if [ "$#" -ne 1 ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi
if ! [ -e "$1" ]; then
  echo "$1 not found" >&2
  exit 1
fi
if ! [ -d "$1" ]; then
  echo "$1 not a directory" >&2
  exit 1
fi

Disabling radio buttons with jQuery

Remove your "each" and just use:

$('input[name=ticketID]').attr("disabled",true);

That simple. It works

Pip install - Python 2.7 - Windows 7

pip is installed by default when we install Python in windows. After setting up the environment variables path for python executables, we can run python interpreter from the command line on windows CMD After that, we can directly use the python command with pip option to install further packages as following:-

C:\ python -m pip install python_module_name

This will install the module using pip.

Convert Rtf to HTML

Mike Stall posted the code for one he wrote in c# here :

http://blogs.msdn.com/jmstall/archive/2006/10/20/rtf_5F00_html.aspx

MySQL CREATE FUNCTION Syntax

MySQL create function syntax:

DELIMITER //

CREATE FUNCTION GETFULLNAME(fname CHAR(250),lname CHAR(250))
    RETURNS CHAR(250)
    BEGIN
        DECLARE fullname CHAR(250);
        SET fullname=CONCAT(fname,' ',lname);
        RETURN fullname;
    END //

DELIMITER ;

Use This Function In Your Query

SELECT a.*,GETFULLNAME(a.fname,a.lname) FROM namedbtbl as a


SELECT GETFULLNAME("Biswarup","Adhikari") as myname;

Watch this Video how to create mysql function and how to use in your query

Create Mysql Function Video Tutorial

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

No, this is, as you say "rubbish code". If it works as should, it is because browsers try to "read the writer's mind" - in other words, they have algorithms to try to make sense of "rubbish code", guess at the probable intent and internally change it into something that actually makes sense.

In other words, your code only works by accident, and probably not in all browsers.

Is this what you're trying to do?

<a href="#" onClick="alert('Hello World!')"><img title="The Link" /></a>

Permissions error when connecting to EC2 via SSH on Mac OSx

The key for me to be able to connect was to use the "ec2-user" user rather than root. I.e.:

ssh -i [full path to keypair file] ec2-user@[EC2 instance hostname or IP address]

How to fix "The ConnectionString property has not been initialized"

Simply in Code Behind Page use:-

SqlConnection con = new SqlConnection("Data Source = DellPC; Initial Catalog = Account; user = sa; password = admin");

It Should Work Just Fine

How can I capitalize the first letter of each word in a string?

In case you want to downsize

# Assuming you are opening a new file
with open(input_file) as file:
    lines = [x for x in reader(file) if x]

# for loop to parse the file by line
for line in lines:
    name = [x.strip().lower() for x in line if x]
    print(name) # Check the result

How to discover number of *logical* cores on Mac OS X?

On a MacBook Pro running Mavericks, sysctl -a | grep hw.cpu will only return some cryptic details. Much more detailed and accessible information is revealed in the machdep.cpu section, ie:

sysctl -a | grep machdep.cpu

In particular, for processors with HyperThreading (HT), you'll see the total enumerated CPU count (logical_per_package) as double that of the physical core count (cores_per_package).

sysctl -a | grep machdep.cpu  | grep per_package

Detect Android phone via Javascript / jQuery

How about this one-liner?

var isAndroid = /(android)/i.test(navigator.userAgent);

The i modifier is used to perform case-insensitive matching.


Technique taken from Cordova AdMob test project: https://github.com/floatinghotpot/cordova-admob-pro/wiki/00.-How-To-Use-with-PhoneGap-Build

How to SELECT a dropdown list item by value programmatically

combobox1.SelectedValue = x;

I suspect you may want yo hear something else, but this is what you asked for.

TypeScript - Append HTML to container element in Angular 2

You could do something like this:

htmlComponent.ts

htmlVariable: string = "<b>Some html.</b>"; //this is html in TypeScript code that you need to display

htmlComponent.html

<div [innerHtml]="htmlVariable"></div> //this is how you display html code from TypeScript in your html

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.

How do I parse JSON with Ruby on Rails?

Ruby's bundled JSON is capable of exhibiting a bit of magic on its own.

If you have a string containing JSON serialized data that you want to parse:

JSON[string_to_parse]

JSON will look at the parameter, see it's a String and try decoding it.

Similarly, if you have a hash or array you want serialized, use:

JSON[array_of_values]

Or:

JSON[hash_of_values]

And JSON will serialize it. You can also use the to_json method if you want to avoid the visual similarity of the [] method.

Here are some examples:

hash_of_values = {'foo' => 1, 'bar' => 2}
array_of_values = [hash_of_values]

JSON[hash_of_values] 
# => "{\"foo\":1,\"bar\":2}"

JSON[array_of_values] 
# => "[{\"foo\":1,\"bar\":2}]"

string_to_parse = array_of_values.to_json
JSON[string_to_parse]
# => [{"foo"=>1, "bar"=>2}]

If you root around in JSON you might notice it's a subset of YAML, and, actually the YAML parser is what's handling JSON. You can do this too:

require 'yaml'

YAML.load(string_to_parse)
# => [{"foo"=>1, "bar"=>2}]

If your app is parsing both YAML and JSON, you can let YAML handle both flavors of serialized data.

List of all users that can connect via SSH

Read man sshd_config for more details, but you can use the AllowUsers directive in /etc/ssh/sshd_config to limit the set of users who can login.

e.g.

AllowUsers boris

would mean that only the boris user could login via ssh.

Fastest way(s) to move the cursor on a terminal command line?

Use Meta-b / Meta-f to move backward/forward by a word respectively.

In OSX, Meta translates as ESC, which sucks.

But alternatively, you can open terminal preferences -> settings -> profile -> keyboard and check "use option as meta key"

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

It is possible to rename a file and keep the history intact, although it causes the file to be renamed throughout the entire history of the repository. This is probably only for the obsessive git-log-lovers, and has some serious implications, including these:

  • You could be rewriting a shared history, which is the most important DON'T while using Git. If someone else has cloned the repository, you'll break it doing this. They will have to re-clone to avoid headaches. This might be OK if the rename is important enough, but you'll need to consider this carefully -- you might end up upsetting an entire opensource community!
  • If you've referenced the file using it's old name earlier in the repository history, you're effectively breaking earlier versions. To remedy this, you'll have to do a bit more hoop jumping. It's not impossible, just tedious and possibly not worth it.

Now, since you're still with me, you're a probably solo developer renaming a completely isolated file. Let's move a file using filter-tree!

Assume you're going to move a file old into a folder dir and give it the name new

This could be done with git mv old dir/new && git add -u dir/new, but that breaks history.

Instead:

git filter-branch --tree-filter 'if [ -f old ]; then mkdir dir && mv old dir/new; fi' HEAD

will redo every commit in the branch, executing the command in the ticks for each iteration. Plenty of stuff can go wrong when you do this. I normally test to see if the file is present (otherwise it's not there yet to move) and then perform the necessary steps to shoehorn the tree to my liking. Here you might sed through files to alter references to the file and so on. Knock yourself out! :)

When completed, the file is moved and the log is intact. You feel like a ninja pirate.

Also; The mkdir dir is only necessary if you move the file to a new folder, of course. The if will avoid the creation of this folder earlier in history than your file exists.

C++ Array of pointers: delete or delete []?

For new you should use delete. For new[] use delete[]. Your second variant is correct.

Where does the @Transactional annotation belong?

First of all let's define where we have to use transaction?

I think correct answer is - when we need to make sure that sequence of actions will be finished together as one atomic operation or no changes will be made even if one of the actions fails.

It is well known practice to put business logic into services. So service methods may contain different actions which must be performed as a single logical unit of work. If so - then such method must be marked as Transactional. Of course, not every method requires such limitation, so you don't need to mark whole service as transactional.

And even more - don't forget to take into account that @Transactional obviously, may reduce method performance. In order to see whole picture you have to know transaction isolation levels. Knowing that might help you avoid using @Transactional where it's not necessarily needed.

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

@viewChild not working - cannot read property nativeElement of undefined

Initializing the Canvas like below works for TypeScript/Angular solutions.

const canvas = <HTMLCanvasElement> document.getElementById("htmlElemId"); 

const context = canvas.getContext("2d"); 

How do you replace double quotes with a blank space in Java?

You don't need regex for this. Just a character-by-character replace is sufficient. You can use String#replace() for this.

String replaced = original.replace("\"", " ");

Note that you can also use an empty string "" instead to replace with. Else the spaces would double up.

String replaced = original.replace("\"", "");

What is the difference between 'git pull' and 'git fetch'?

This graphic could be of help. git pull is essentially equivalent to git fetch then git merge

This graphic could be of help. git pull is essentially equivalent to git fetch then git merge

Converting a Java Keystore into PEM Format

Converting a Java Keystore into PEM Format

The most precise answer of all must be that this is NOT possible.

A Java keystore is merely a storage facility for cryptographic keys and certificates while PEM is a file format for X.509 certificates only.

Deserializing JSON array into strongly typed .NET object

This worked for me for deserializing JSON into an array of objects:

List<TheUser> friends = JsonConvert.DeserializeObject<List<TheUser>>(response);

Missing .map resource?

I had similar expirience like yours. I have Denwer server. When I loaded my http://new.new local site without using via script src jquery.min.js file at index.php in Chrome I got error 500 jquery.min.map in console. I resolved this problem simply - I disabled extension Wunderlist in Chrome and voila - I never see this error more. Although, No, I found this error again - when Wunderlist have been on again. So, check your extensions and try to disable all of them or some of them or one by one. Good luck!

MVC controller : get JSON object from HTTP body?

you can get the json string as a param of your ActionResult and afterwards serialize it using JSON.Net

HERE an example is being shown


in order to receive it in the serialized form as a param of the controller action you must either write a custom model binder or a Action filter (OnActionExecuting) so that the json string is serialized into the model of your liking and is available inside the controller body for use.


HERE is an implementation using the dynamic object

Ruby: Can I write multi-line string with no concatenation?

To avoid closing the parentheses for each line you can simply use double quotes with a backslash to escape the newline:

"select attr1, attr2, attr3, attr4, attr5, attr6, attr7 \
from table1, table2, table3, etc, etc, etc, etc, etc, \
where etc etc etc etc etc etc etc etc etc etc etc etc etc"

how to configure config.inc.php to have a loginform in phpmyadmin

$cfg['Servers'][$i]['AllowNoPassword'] = false;

How to make a GridLayout fit screen size

Note: The information below the horizontal line is no longer accurate with the introduction of Android 'Lollipop' 5, as GridLayout does accommodate the principle of weights since API level 21.

Quoted from the Javadoc:

Excess Space Distribution

As of API 21, GridLayout's distribution of excess space accomodates the principle of weight. In the event that no weights are specified, the previous conventions are respected and columns and rows are taken as flexible if their views specify some form of alignment within their groups. The flexibility of a view is therefore influenced by its alignment which is, in turn, typically defined by setting the gravity property of the child's layout parameters. If either a weight or alignment were defined along a given axis then the component is taken as flexible in that direction. If no weight or alignment was set, the component is instead assumed to be inflexible.

Multiple components in the same row or column group are considered to act in parallel. Such a group is flexible only if all of the components within it are flexible. Row and column groups that sit either side of a common boundary are instead considered to act in series. The composite group made of these two elements is flexible if one of its elements is flexible.

To make a column stretch, make sure all of the components inside it define a weight or a gravity. To prevent a column from stretching, ensure that one of the components in the column does not define a weight or a gravity.

When the principle of flexibility does not provide complete disambiguation, GridLayout's algorithms favour rows and columns that are closer to its right and bottom edges. To be more precise, GridLayout treats each of its layout parameters as a constraint in the a set of variables that define the grid-lines along a given axis. During layout, GridLayout solves the constraints so as to return the unique solution to those constraints for which all variables are less-than-or-equal-to the corresponding value in any other valid solution.

It's also worth noting that android.support.v7.widget.GridLayout contains the same information. Unfortunately it doesn't mention which version of the support library it was introduced with, but the commit that adds the functionality can be tracked back to July 2014. In November 2014, improvements in weight calculation and a bug was fixed.

To be safe, make sure to import the latest version of the gridlayout-v7 library.


The principle of 'weights', as you're describing it, does not exist with GridLayout. This limitation is clearly mentioned in the documentation; excerpt below. That being said, there are some possibilities to use 'gravity' for excess space distribution. I suggest you have read through the linked documentation.

Limitations

GridLayout does not provide support for the principle of weight, as defined in weight. In general, it is not therefore possible to configure a GridLayout to distribute excess space in non-trivial proportions between multiple rows or columns. Some common use-cases may nevertheless be accommodated as follows. To place equal amounts of space around a component in a cell group; use CENTER alignment (or gravity). For complete control over excess space distribution in a row or column; use a LinearLayout subview to hold the components in the associated cell group. When using either of these techniques, bear in mind that cell groups may be defined to overlap.

For an example and some practical pointers, take a look at last year's blog post introducing the GridLayout widget.


Edit: I don't think there's an xml-based approach to scaling the tiles like in the Google Play app to 'squares' or 'rectangles' twice the length of those squares. However, it is certainly possible if you build your layout programmatically. All you really need to know in order two accomplish that is the device's screen dimensions.

Below a (very!) quick 'n dirty approximation of the tiled layout in the Google Play app.

Point size = new Point();
getWindowManager().getDefaultDisplay().getSize(size);
int screenWidth = size.x;
int screenHeight = size.y;
int halfScreenWidth = (int)(screenWidth *0.5);
int quarterScreenWidth = (int)(halfScreenWidth * 0.5);

Spec row1 = GridLayout.spec(0, 2);
Spec row2 = GridLayout.spec(2);
Spec row3 = GridLayout.spec(3);
Spec row4 = GridLayout.spec(4, 2);

Spec col0 = GridLayout.spec(0);
Spec col1 = GridLayout.spec(1); 
Spec colspan2 = GridLayout.spec(0, 2);

GridLayout gridLayout = new GridLayout(this);
gridLayout.setColumnCount(2);
gridLayout.setRowCount(15);

TextView twoByTwo1 = new TextView(this);
GridLayout.LayoutParams first = new GridLayout.LayoutParams(row1, colspan2);
first.width = screenWidth;
first.height = quarterScreenWidth * 2;
twoByTwo1.setLayoutParams(first);
twoByTwo1.setGravity(Gravity.CENTER);
twoByTwo1.setBackgroundColor(Color.RED);
twoByTwo1.setText("TOP");
twoByTwo1.setTextAppearance(this, android.R.style.TextAppearance_Large);
gridLayout.addView(twoByTwo1, first);

TextView twoByOne1 = new TextView(this);
GridLayout.LayoutParams second = new GridLayout.LayoutParams(row2, col0);
second.width = halfScreenWidth;
second.height = quarterScreenWidth;
twoByOne1.setLayoutParams(second);
twoByOne1.setBackgroundColor(Color.BLUE);
twoByOne1.setText("Staff Choices");
twoByOne1.setTextAppearance(this, android.R.style.TextAppearance_Large);
gridLayout.addView(twoByOne1, second);

TextView twoByOne2 = new TextView(this);
GridLayout.LayoutParams third = new GridLayout.LayoutParams(row2, col1);
third.width = halfScreenWidth;
third.height = quarterScreenWidth;
twoByOne2.setLayoutParams(third);
twoByOne2.setBackgroundColor(Color.GREEN);
twoByOne2.setText("Games");
twoByOne2.setTextAppearance(this, android.R.style.TextAppearance_Large);
gridLayout.addView(twoByOne2, third);

TextView twoByOne3 = new TextView(this);
GridLayout.LayoutParams fourth = new GridLayout.LayoutParams(row3, col0);
fourth.width = halfScreenWidth;
fourth.height = quarterScreenWidth;
twoByOne3.setLayoutParams(fourth);
twoByOne3.setBackgroundColor(Color.YELLOW);
twoByOne3.setText("Editor's Choices");
twoByOne3.setTextAppearance(this, android.R.style.TextAppearance_Large_Inverse);
gridLayout.addView(twoByOne3, fourth);

TextView twoByOne4 = new TextView(this);
GridLayout.LayoutParams fifth = new GridLayout.LayoutParams(row3, col1);
fifth.width = halfScreenWidth;
fifth.height = quarterScreenWidth;
twoByOne4.setLayoutParams(fifth);
twoByOne4.setBackgroundColor(Color.MAGENTA);
twoByOne4.setText("Something Else");
twoByOne4.setTextAppearance(this, android.R.style.TextAppearance_Large);
gridLayout.addView(twoByOne4, fifth);

TextView twoByTwo2 = new TextView(this);
GridLayout.LayoutParams sixth = new GridLayout.LayoutParams(row4, colspan2);
sixth.width = screenWidth;
sixth.height = quarterScreenWidth * 2;
twoByTwo2.setLayoutParams(sixth);
twoByTwo2.setGravity(Gravity.CENTER);
twoByTwo2.setBackgroundColor(Color.WHITE);
twoByTwo2.setText("BOTOM");
twoByTwo2.setTextAppearance(this, android.R.style.TextAppearance_Large_Inverse);
gridLayout.addView(twoByTwo2, sixth);

The result will look somewhat like this (on my Galaxy Nexus):

Tiled layout using GridLayout

How to get unique values in an array

I was just thinking if we can use linear search to eliminate the duplicates:

JavaScript:
function getUniqueRadios() {

var x=document.getElementById("QnA");
var ansArray = new Array();
var prev;


for (var i=0;i<x.length;i++)
  {
    // Check for unique radio button group
    if (x.elements[i].type == "radio")
    {
            // For the first element prev will be null, hence push it into array and set the prev var.
            if (prev == null)
            {
                prev = x.elements[i].name;
                ansArray.push(x.elements[i].name);
            } else {
                   // We will only push the next radio element if its not identical to previous.
                   if (prev != x.elements[i].name)
                   {
                       prev = x.elements[i].name;
                       ansArray.push(x.elements[i].name);
                   }
            }
    }

  }

   alert(ansArray);

}

HTML:

<body>

<form name="QnA" action="" method='post' ">

<input type="radio"  name="g1" value="ANSTYPE1"> good </input>
<input type="radio" name="g1" value="ANSTYPE2"> avg </input>

<input type="radio"  name="g2" value="ANSTYPE3"> Type1 </input>
<input type="radio" name="g2" value="ANSTYPE2"> Type2 </input>


<input type="submit" value='SUBMIT' onClick="javascript:getUniqueRadios()"></input>


</form>
</body>

How good is Java's UUID.randomUUID?

I'm not an expert, but I'd assume that enough smart people looked at Java's random number generator over the years. Hence, I'd also assume that random UUIDs are good. So you should really have the theoretical collision probability (which is about 1 : 3 × 10^38 for all possible UUIDs. Does anybody know how this changes for random UUIDs only? Is it 1/(16*4) of the above?)

From my practical experience, I've never seen any collisions so far. I'll probably have grown an astonishingly long beard the day I get my first one ;)

Get all attributes of an element using jQuery

with LoDash you could simply do this:

_.transform(this.attributes, function (result, item) {
  item.specified && (result[item.name] = item.value);
}, {});

Return datetime object of previous month

import datetime
date_str = '08/01/2018'
format_str = '%d/%m/%Y'
datetime_obj = datetime.datetime.strptime(date_str, format_str)   
datetime_obj.replace(month=datetime_obj.month-1)

Simple solution, no need for special libraries.

JSON, REST, SOAP, WSDL, and SOA: How do they all link together

Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.

You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.

Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.

So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".


That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.

SOAP:

SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.

REST:

REST is a design concept.

The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.

It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)

Flickr's REST API goes further and lets you return images as well.


JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.

How to do a SUM() inside a case statement in SQL server

If you're using SQL Server 2005 or above, you can use the windowing function SUM() OVER ().

case 
when test1.TotalType = 'Average' then Test2.avgscore
when test1.TotalType = 'PercentOfTot' then (cnt/SUM(test1.qrank) over ())
else cnt
end as displayscore

But it'll be better if you show your full query to get context of what you actually need.

Laravel redirect back to original destination after login

if you are using axios or other AJAX javascript library you may want to retrive the url and pass to the front end

you can do that with the code below

   $default = '/';

   $location = $request->session()->pull('url.intended', $default);

    return ['status' => 200, 'location' => $location];

This will return a json formatted string

Numpy first occurrence of value greater than existing value

In [34]: a=np.arange(-10,10)

In [35]: a
Out[35]:
array([-10,  -9,  -8,  -7,  -6,  -5,  -4,  -3,  -2,  -1,   0,   1,   2,
         3,   4,   5,   6,   7,   8,   9])

In [36]: np.where(a>5)
Out[36]: (array([16, 17, 18, 19]),)

In [37]: np.where(a>5)[0][0]
Out[37]: 16

How to generate sample XML documents from their DTD or XSD?

I think Oxygen (http://www.oxygenxml.com/) does it as well, but that's another commerical product. It's a nice one, though... I'd strongly recommend it for anyone doing a lot of XML work. It comes in a nice Eclipse plugin, too.

I do believe there is a free, fully-featured 30 day trial.

How can I use grep to show just filenames on Linux?

Your question How can I just get the file-names (with paths)

Your syntax example find . -iname "*php" -exec grep -H myString {} \;

My Command suggestion

sudo find /home -name *.php

The output from this command on my Linux OS:

compose-sample-3/html/mail/contact_me.php

As you require the filename with path, enjoy!

Excel VBA select range at last row and column

The simplest modification (to the code in your question) is this:

    Range("A" & Rows.Count).End(xlUp).Select
    Selection.EntireRow.Delete

Which can be simplified to:

    Range("A" & Rows.Count).End(xlUp).EntireRow.Delete

how do I strip white space when grabbing text with jQuery?

Actually, jQuery has a built in trim function:

 var emailAdd = jQuery.trim($(this).text());

See here for details.

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

MYSQL query between two timestamps

Try this its worked for me

SELECT * from bookedroom
    WHERE UNIX_TIMESTAMP('2020-8-07 5:31')
        between UNIX_TIMESTAMP('2020-8-07 5:30') and
        UNIX_TIMESTAMP('2020-8-09 5:30')

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

I have had to unpack a .ab-file, too and found this post while looking for an answer. My suggested solution is Android Backup Extractor, a free Java tool for Windows, Linux and Mac OS.

Make sure to take a look at the README, if you encounter a problem. You might have to download further files, if your .ab-file is password-protected.

Usage:
java -jar abe.jar [-debug] [-useenv=yourenv] unpack <backup.ab> <backup.tar> [password]

Example:

Let's say, you've got a file test.ab, which is not password-protected, you're using Windows and want the resulting .tar-Archive to be called test.tar. Then your command should be:

java.exe -jar abe.jar unpack test.ab test.tar ""

Use jQuery to change value of a label

.text is correct, the following code works for me:

$('#lb'+(n+1)).text(a[i].attributes[n].name+": "+ a[i].attributes[n].value);

How to backup a local Git repository?

You can backup the git repo with git-copy . git-copy saved new project as a bare repo, it means minimum storage cost.

git copy /path/to/project /backup/project.backup

Then you can restore your project with git clone

git clone /backup/project.backup project

Use of contains in Java ArrayList<String>

Right...with strings...the moment you deviate from primitives or strings things change and you need to implement hashcode/equals to get the desired effect.

EDIT: Initialize your ArrayList<String> then attempt to add an item.

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

SQL Server query to find all permissions/access for all users in a database

I just added the following to Jeremy's answer because I had a role assigned to the database db_datareader which wasn't showing the permissions that role had. I tried going through all of the answers in everyone's posts but couldn't find anything that would do this so I added my own query.

    SELECT 
    UserType='Role', 
    DatabaseUserName = '{Role Members}',
    LoginName = DP2.name,
    Role = DP1.name,
    'SELECT' AS [PermissionType] ,
    [PermissionState]  = 'GRANT',
    [ObjectType] = 'Table',
    [Schema] = 'dbo',
    [ObjectName] = 'All Tables',
    [ColumnName] = NULL
FROM sys.database_role_members AS DRM  
RIGHT OUTER JOIN sys.database_principals AS DP1  
    ON DRM.role_principal_id = DP1.principal_id  
LEFT OUTER JOIN sys.database_principals AS DP2  
    ON DRM.member_principal_id = DP2.principal_id  
WHERE DP1.type = 'R'
AND DP2.name IS NOT NULL

An object reference is required to access a non-static member

playSound is a static method in your class, but you are referring to members like audioSounds or minTime which are not declared static so they would require a SoundManager sm = new SoundManager(); to operate as sm.audioSounds or sm.minTime respectively

Solution:

public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;

Align image in center and middle within div

Just set parent div css property "text-align:center;"

 <div style="text-align:center; width:100%">
        <img src="img.png"> 
 </div>

git - Server host key not cached

Solution with Plink

Save this python script to known_hosts.py:

#! /usr/bin/env python

# $Id$
# Convert OpenSSH known_hosts and known_hosts2 files to "new format" PuTTY
# host keys.
#   usage:
#     kh2reg.py [ --win ] known_hosts1 2 3 4 ... > hosts.reg
#       Creates a Windows .REG file (double-click to install).
#     kh2reg.py --unix    known_hosts1 2 3 4 ... > sshhostkeys
#       Creates data suitable for storing in ~/.putty/sshhostkeys (Unix).
# Line endings are someone else's problem as is traditional.
# Developed for Python 1.5.2.

import fileinput
import base64
import struct
import string
import re
import sys
import getopt

def winmungestr(s):
    "Duplicate of PuTTY's mungestr() in winstore.c:1.10 for Registry keys"
    candot = 0
    r = ""
    for c in s:
        if c in ' \*?%~' or ord(c)<ord(' ') or (c == '.' and not candot):
            r = r + ("%%%02X" % ord(c))
        else:
            r = r + c
        candot = 1
    return r

def strtolong(s):
    "Convert arbitrary-length big-endian binary data to a Python long"
    bytes = struct.unpack(">%luB" % len(s), s)
    return reduce ((lambda a, b: (long(a) << 8) + long(b)), bytes)

def longtohex(n):
    """Convert long int to lower-case hex.

    Ick, Python (at least in 1.5.2) doesn't appear to have a way to
    turn a long int into an unadorned hex string -- % gets upset if the
    number is too big, and raw hex() uses uppercase (sometimes), and
    adds unwanted "0x...L" around it."""

    plain=string.lower(re.match(r"0x([0-9A-Fa-f]*)l?$", hex(n), re.I).group(1))
    return "0x" + plain

output_type = 'windows'

try:
    optlist, args = getopt.getopt(sys.argv[1:], '', [ 'win', 'unix' ])
    if filter(lambda x: x[0] == '--unix', optlist):
        output_type = 'unix'
except getopt.error, e:
    sys.stderr.write(str(e) + "\n")
    sys.exit(1)

if output_type == 'windows':
    # Output REG file header.
    sys.stdout.write("""REGEDIT4

[HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\SshHostKeys]
""")

# Now process all known_hosts input.
for line in fileinput.input(args):

    try:
        # Remove leading/trailing whitespace (should zap CR and LF)
        line = string.strip (line)

        # Skip blanks and comments
        if line == '' or line[0] == '#':
            raise "Skipping input line"

        # Split line on spaces.
        fields = string.split (line, ' ')

        # Common fields
        hostpat = fields[0]
        magicnumbers = []   # placeholder
        keytype = ""        # placeholder

        # Grotty heuristic to distinguish known_hosts from known_hosts2:
        # is second field entirely decimal digits?
        if re.match (r"\d*$", fields[1]):

            # Treat as SSH-1-type host key.
            # Format: hostpat bits10 exp10 mod10 comment...
            # (PuTTY doesn't store the number of bits.)
            magicnumbers = map (long, fields[2:4])
            keytype = "rsa"

        else:

            # Treat as SSH-2-type host key.
            # Format: hostpat keytype keyblob64 comment...
            sshkeytype, blob = fields[1], base64.decodestring (fields[2])

            # 'blob' consists of a number of
            #   uint32    N (big-endian)
            #   uint8[N]  field_data
            subfields = []
            while blob:
                sizefmt = ">L"
                (size,) = struct.unpack (sizefmt, blob[0:4])
                size = int(size)   # req'd for slicage
                (data,) = struct.unpack (">%lus" % size, blob[4:size+4])
                subfields.append(data)
                blob = blob [struct.calcsize(sizefmt) + size : ]

            # The first field is keytype again, and the rest we can treat as
            # an opaque list of bignums (same numbers and order as stored
            # by PuTTY). (currently embedded keytype is ignored entirely)
            magicnumbers = map (strtolong, subfields[1:])

            # Translate key type into something PuTTY can use.
            if   sshkeytype == "ssh-rsa":   keytype = "rsa2"
            elif sshkeytype == "ssh-dss":   keytype = "dss"
            else:
                raise "Unknown SSH key type", sshkeytype

        # Now print out one line per host pattern, discarding wildcards.
        for host in string.split (hostpat, ','):
            if re.search (r"[*?!]", host):
                sys.stderr.write("Skipping wildcard host pattern '%s'\n"
                                 % host)
                continue
            elif re.match (r"\|", host):
                sys.stderr.write("Skipping hashed hostname '%s'\n" % host)
                continue
            else:
                m = re.match (r"\[([^]]*)\]:(\d*)$", host)
                if m:
                    (host, port) = m.group(1,2)
                    port = int(port)
                else:
                    port = 22
                # Slightly bizarre output key format: 'type@port:hostname'
                # XXX: does PuTTY do anything useful with literal IP[v4]s?
                key = keytype + ("@%d:%s" % (port, host))
                value = string.join (map (longtohex, magicnumbers), ',')
                if output_type == 'unix':
                    # Unix format.
                    sys.stdout.write('%s %s\n' % (key, value))
                else:
                    # Windows format.
                    # XXX: worry about double quotes?
                    sys.stdout.write("\"%s\"=\"%s\"\n"
                                     % (winmungestr(key), value))

    except "Unknown SSH key type", k:
        sys.stderr.write("Unknown SSH key type '%s', skipping\n" % k)
    except "Skipping input line":
        pass

Tested on Win7x64 and Python 2.7.

Then run:

ssh-keyscan -t rsa bitbucket.org >>~/.ssh/known_hosts
python --win known_hosts.py >known_hosts.reg
start known_hosts.reg

And choose to import into the registry. The keyscan will retrieve the public key for the domain (I had my problems with bitbucket), and then the python script will convert it to Plink format.

Adding an onclick event to a div element

Its possible, we can specify onclick event in

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="thumb0" class="thumbs" onclick="fun1('rad1')" style="height:250px; width:100%; background-color:yellow;";></div>
<div id="rad1" style="height:250px; width:100%;background-color:red;" onclick="fun2('thumb0')">hello world</div>????????????????????????????????
<script>
function fun1(i) {
    document.getElementById(i).style.visibility='hidden';
}
function fun2(i) {
    document.getElementById(i).style.visibility='hidden';
}
</script>
</body>
</html>

How do you check if a string is not equal to an object or other string value in java?

Change your || to && so it will only exit if the answer is NEITHER "AM" nor "PM".

How to escape a single quote inside awk

awk 'BEGIN {FS=" "} {printf "\047%s\047 ", $1}'

Change the Value of h1 Element within a Form with JavaScript

Try:


document.getElementById("yourH1_element_Id").innerHTML = "yourTextHere";

How to convert an object to a byte array in C#

I found another way to convert an object to a byte[], here is my solution:

IEnumerable en = (IEnumerable) myObject;
byte[] myBytes = en.OfType<byte>().ToArray();

Regards

Create Directory if it doesn't exist with Ruby

Simple way:

directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)

2D array values C++

int iArray[2][2] = {{1, 2}, {3, 4}};

Think of a 2D array as an array of arrays.

How to roundup a number to the closest ten?

Use ROUND but with num_digits = -1

=ROUND(A1,-1)

Also applies to ROUNDUP and ROUNDDOWN

From Excel help:

  • If num_digits is greater than 0 (zero), then number is rounded to the specified number of decimal places.
  • If num_digits is 0, then number is rounded to the nearest integer.
  • If num_digits is less than 0, then number is rounded to the left of the decimal point.

EDIT: To get the numbers to always round up use =ROUNDUP(A1,-1)

Does Git Add have a verbose switch

You can use git add -i to get an interactive version of git add, although that's not exactly what you're after. The simplest thing to do is, after having git added, use git status to see what is staged or not.

Using git add . isn't really recommended unless it's your first commit. It's usually better to explicitly list the files you want staged, so that you don't start tracking unwanted files accidentally (temp files and such).

Passing Objects By Reference or Value in C#

In Pass By Reference You only add "ref" in the function parameters and one more thing you should be declaring function "static" because of main is static(#public void main(String[] args))!

namespace preparation
{
  public  class Program
    {
      public static void swap(ref int lhs,ref int rhs)
      {
          int temp = lhs;
          lhs = rhs;
          rhs = temp;
      }
          static void Main(string[] args)
        {
            int a = 10;
            int b = 80;

  Console.WriteLine("a is before sort " + a);
            Console.WriteLine("b is before sort " + b);
            swap(ref a, ref b);
            Console.WriteLine("");
            Console.WriteLine("a is after sort " + a);
            Console.WriteLine("b is after sort " + b);  
        }
    }
}

Double quotes within php script echo

if you need to access your variables for an echo statement within your quotes put your variable inside curly brackets

echo "i need to open my lock with its: {$array['key']}";

how to fix Cannot call sendRedirect() after the response has been committed?

you can't call sendRedirect(), after you have already used forward(). So, you get that exception.

Calculate days between two Dates in Java 8

Based on VGR's comments here is what you can use:

ChronoUnit.DAYS.between(firstDate, secondDate)

How to get the unique ID of an object which overrides hashCode()?

// looking for that last hex?
org.joda.DateTime@57110da6

If you're looking into the hashcode Java types when you do a .toString() on an object the underlying code is this:

Integer.toHexString(hashCode())

Lodash - difference between .extend() / .assign() and .merge()

It might be also helpful to consider what they do from a semantic point of view:

_.assign

   will assign the values of the properties of its second parameter and so on,
   as properties with the same name of the first parameter. (shallow copy & override)

_.merge

   merge is like assign but does not assign objects but replicates them instead.
  (deep copy)

_.defaults

   provides default values for missing values.
   so will assign only values for keys that do not exist yet in the source.

_.defaultsDeep

   works like _defaults but like merge will not simply copy objects
   and will use recursion instead.

I believe that learning to think of those methods from the semantic point of view would let you better "guess" what would be the behavior for all the different scenarios of existing and non existing values.

How to activate JMX on my JVM for access with jconsole?

Note, Java 6 in the latest incarnation allows for jconsole to attach itself to a running process even after it has been started without JMX incantations.

If that is available to you, also consider jvisualvm as it provides a wealth of information on running processes, including a profiler.

how to align all my li on one line?

Try putting white-space:nowrap; in your <ul> style

edit: and use 'inline' rather than 'inline-block' as other have pointed out (and I forgot)

Defining lists as global variables in Python

No, you can specify the list as a keyword argument to your function.

alist = []
def fn(alist=alist):
    alist.append(1)
fn()
print alist    # [1]

I'd say it's bad practice though. Kind of too hackish. If you really need to use a globally available singleton-like data structure, I'd use the module level variable approach, i.e. put 'alist' in a module and then in your other modules import that variable:

In file foomodule.py:

alist = []

In file barmodule.py:

import foomodule
def fn():
    foomodule.alist.append(1)
print foomodule.alist    # [1]

Difference between java HH:mm and hh:mm on SimpleDateFormat

h/H = 12/24 hours means you will write hh:mm = 12 hours format and HH:mm = 24 hours format

Change the location of the ~ directory in a Windows install of Git Bash

Instead of modifying the global profile you could create the .bash_profile in your default $HOME directory (e.g. C:\Users\WhateverUser\.bash_profile) with the following contents:

export HOME="C:\my\projects\dir"
cd "$HOME" # if you'd like it to be the starting dir of the git shell

Operation must use an updatable query. (Error 3073) Microsoft Access

The problem defintely relates to the use of (in this case) the max() function. Any aggregation function used during a join (e.g. to retrieve the max or min or avg value from a joined table) will cause the error. And the same applies to using subqueries instead of joins (as in the original code).

This is incredibly annoying (and unjustified!) as it is a reasonably common thing to want to do. I've also had to use temp tables to get around it (pull the aggregated value into a temp table with an insert statement, then join to this table with your update, then drop the temp table).

Glenn

What MySQL data type should be used for Latitude/Longitude with 8 decimal places?

Using migrate ruby on rails

class CreateNeighborhoods < ActiveRecord::Migration[5.0]
  def change
    create_table :neighborhoods do |t|
      t.string :name
      t.decimal :latitude, precision: 15, scale: 13
      t.decimal :longitude, precision: 15, scale: 13
      t.references :country, foreign_key: true
      t.references :state, foreign_key: true
      t.references :city, foreign_key: true

      t.timestamps
    end
  end
end

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

For this problem,

What i did is:

  • Delete the Pids folder which is located under app/tmp/
  • and then, close the terminal which we are running the current app and close the tab (in, browser window)

  • after that, again open the terminal by going inside the folder, and then do, rails s

  • Then, it opens the fresh tab which is running our application

Base64: java.lang.IllegalArgumentException: Illegal character

I got this error for my Linux Jenkins slave. I fixed it by changing from the node from "Known hosts file Verification Strategy" to "Non verifying Verification Strategy".

Property [title] does not exist on this collection instance

$about = DB::where('page', 'about-me')->first(); 

in stead of get().

It works on my project. Thanks.

How do I convert a float number to a whole number in JavaScript?

A double bitwise not operator can be used to truncate floats. The other operations you mentioned are available through Math.floor, Math.ceil, and Math.round.

> ~~2.5
2
> ~~(-1.4)
-1

More details courtesy of James Padolsey.

jQuery Form Validation before Ajax submit

> Required JS for jquery form validation
> ## jquery-1.7.1.min.js ##
> ## jquery.validate.min.js ##
> ## jquery.form.js ##

$("form#data").validate({
    rules: {
        first: {
                required: true,
            },
        middle: {
            required: true,
        },          
        image: {
            required: true,
        },
    },
    messages: {
        first: {
                required: "Please enter first",
            },
        middle: {
            required: "Please enter middle",
        },          
        image: {
            required: "Please Select logo",
        },
    },
    submitHandler: function(form) {
        var formData = new FormData($("#image")[0]);
        $(form).ajaxSubmit({
            url:"action.php",
            type:"post",
            success: function(data,status){
              alert(data);
            }
        });
    }
});

Adding a directory to PATH in Ubuntu

The file .bashrc is read when you start an interactive shell. This is the file that you should update. E.g:

export PATH=$PATH:/opt/ActiveTcl-8.5/bin

Restart the shell for the changes to take effect or source it, i.e.:

source .bashrc

xsl: how to split strings?

If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

Add a default value to a column through a migration

**Rails 4.X +**

As of Rails 4 you can't generate a migration to add a column to a table with a default value, The following steps add a new column to an existing table with default value true or false.

1. Run the migration from command line to add the new column

$ rails generate migration add_columnname_to_tablename columnname:boolean

The above command will add a new column in your table.

2. Set the new column value to TRUE/FALSE by editing the new migration file created.

class AddColumnnameToTablename < ActiveRecord::Migration
  def change
    add_column :table_name, :column_name, :boolean, default: false
  end
end

**3. To make the changes into your application database table, run the following command in terminal**

$ rake db:migrate

Undefined symbols for architecture armv7

I had a similar issue and I had to check "Build Active Architecture Only" on each of the Project configurations (Debug, Release and Deployment) and in the Build Settings of the Target.

Adding two Java 8 streams, or an extra element to a stream

How about writing your own concat method?

public static Stream<T> concat(Stream<? extends T> a, 
                               Stream<? extends T> b, 
                               Stream<? extends T> args)
{
    Stream<T> concatenated = Stream.concat(a, b);
    for (Stream<T> stream : args)
    {
        concatenated = Stream.concat(concatenated, stream);
    }
    return concatenated;
}

This at least makes your first example a lot more readable.

Phone number validation Android

Here is how you can do it succinctly in Kotlin:

fun String.isPhoneNumber() =
            length in 4..10 && all { it.isDigit() }

Add back button to action bar

Add

actionBar.setHomeButtonEnabled(true);

and then add the following

@Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{       
    switch (menuItem.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(menuItem);
    }
}

As suggested by naXa I've added a check on the itemId, to have it work correctly in case there are multiple buttons on the action bar.

Add a space (" ") after an element using :after

Explanation

It's worth noting that your code does insert a space

h2::after {
  content: " ";
}

However, it's immediately removed.

From Anonymous inline boxes,

White space content that would subsequently be collapsed away according to the 'white-space' property does not generate any anonymous inline boxes.

And from The 'white-space' processing model,

If a space (U+0020) at the end of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is also removed.

Solution

So if you don't want the space to be removed, set white-space to pre or pre-wrap.

_x000D_
_x000D_
h2 {_x000D_
  text-decoration: underline;_x000D_
}_x000D_
h2.space::after {_x000D_
  content: " ";_x000D_
  white-space: pre;_x000D_
}
_x000D_
<h2>I don't have space:</h2>_x000D_
<h2 class="space">I have space:</h2>
_x000D_
_x000D_
_x000D_

Do not use non-breaking spaces (U+00a0). They are supposed to prevent line breaks between words. They are not supposed to be used as non-collapsible space, that wouldn't be semantic.

Understanding events and event handlers in C#

//This delegate can be used to point to methods
//which return void and take a string.
public delegate void MyDelegate(string foo);

//This event can cause any method which conforms
//to MyEventHandler to be called.
public event MyDelegate MyEvent;

//Here is some code I want to be executed
//when SomethingHappened fires.
void MyEventHandler(string foo)
{
    //Do some stuff
}

//I am creating a delegate (pointer) to HandleSomethingHappened
//and adding it to SomethingHappened's list of "Event Handlers".
myObj.MyEvent += new MyDelegate (MyEventHandler);

How to set HTTP headers (for cache-control)?

OWASP recommends the following,

Whenever possible ensure the cache-control HTTP header is set with no-cache, no-store, must-revalidate, private; and that the pragma HTTP header is set with no-cache.

<IfModule mod_headers.c>
    Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
    Header set Pragma "no-cache"
</IfModule>

PHP fwrite new line

fwrite($handle, "<br>"."\r\n");

Add this under

$password = $_POST['password'].PHP_EOL;

this. .

How to see the values of a table variable at debug time in T-SQL?

This project https://github.com/FilipDeVos/sp_select has a stored procedure sp_select which allows for selecting from a temp table.

Usage:

exec sp_select 'tempDb..#myTempTable'

While debugging a stored procedure you can open a new tab and run this command to see the contents of the temp table.

MySQL root access from all hosts

if you have many networks attached to you OS, yo must especify one of this network in the bind-addres from my.conf file. an example:

[mysqld]
bind-address = 127.100.10.234

this ip is from a ethX configuration.

Angular JS - angular.forEach - How to get key of the object?

var obj = {name: 'Krishna', gender: 'male'};
angular.forEach(obj, function(value, key) {
    console.log(key + ': ' + value);
});

yields the attributes of obj with their respective values:

name: Krishna
gender: male

Common sources of unterminated string literal

I would vote for jamtoday's answer if I had the "reputation"

If your data is coming by way of PHP, this might help

$str = str_replace(array("\r", "\n"), '', $str);

Selecting pandas column by location

You could use label based using .loc or index based using .iloc method to do column-slicing including column ranges:

In [50]: import pandas as pd

In [51]: import numpy as np

In [52]: df = pd.DataFrame(np.random.rand(4,4), columns = list('abcd'))

In [53]: df
Out[53]: 
          a         b         c         d
0  0.806811  0.187630  0.978159  0.317261
1  0.738792  0.862661  0.580592  0.010177
2  0.224633  0.342579  0.214512  0.375147
3  0.875262  0.151867  0.071244  0.893735

In [54]: df.loc[:, ["a", "b", "d"]] ### Selective columns based slicing
Out[54]: 
          a         b         d
0  0.806811  0.187630  0.317261
1  0.738792  0.862661  0.010177
2  0.224633  0.342579  0.375147
3  0.875262  0.151867  0.893735

In [55]: df.loc[:, "a":"c"] ### Selective label based column ranges slicing
Out[55]: 
          a         b         c
0  0.806811  0.187630  0.978159
1  0.738792  0.862661  0.580592
2  0.224633  0.342579  0.214512
3  0.875262  0.151867  0.071244

In [56]: df.iloc[:, 0:3] ### Selective index based column ranges slicing
Out[56]: 
          a         b         c
0  0.806811  0.187630  0.978159
1  0.738792  0.862661  0.580592
2  0.224633  0.342579  0.214512
3  0.875262  0.151867  0.071244

How to use && in EL boolean expressions in Facelets?

In addition to the answer of BalusC, use the following Java RegExp to replace && with and:

Search:  (#\{[^\}]*)(&&)([^\}]*\})
Replace: $1and$3

You have run this regular expression replacement multiple times to find all occurences in case you are using >2 literals in your EL expressions. Mind to replace the leading # by $ if your EL expression syntax differs.

The easiest way to replace white spaces with (underscores) _ in bash

This is borderline programming, but look into using tr:

$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'

Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

By using synchronized on a static method lock you will synchronize the class methods and attributes ( as opposed to instance methods and attributes )

So your assumption is correct.

I am wondering if making the method synchronized is the right approach to ensure thread-safety.

Not really. You should let your RDBMS do that work instead. They are good at this kind of stuff.

The only thing you will get by synchronizing the access to the database is to make your application terribly slow. Further more, in the code you posted you're building a Session Factory each time, that way, your application will spend more time accessing the DB than performing the actual job.

Imagine the following scenario:

Client A and B attempt to insert different information into record X of table T.

With your approach the only thing you're getting is to make sure one is called after the other, when this would happen anyway in the DB, because the RDBMS will prevent them from inserting half information from A and half from B at the same time. The result will be the same but only 5 times ( or more ) slower.

Probably it could be better to take a look at the "Transactions and Concurrency" chapter in the Hibernate documentation. Most of the times the problems you're trying to solve, have been solved already and a much better way.

MSIE and addEventListener Problem in Javascript?

The problem is that IE does not have the standard addEventListener method. IE uses its own attachEvent which does pretty much the same.

Good explanation of the differences, and also about the 3rd parameter can be found at quirksmode.

Why doesn't Java support unsigned ints?

I once took a C++ course with someone on the C++ standards committee who implied that Java made the right decision to avoid having unsigned integers because (1) most programs that use unsigned integers can do just as well with signed integers and this is more natural in terms of how people think, and (2) using unsigned integers results in lots easy to create but difficult to debug issues such as integer arithmetic overflow and losing significant bits when converting between signed and unsigned types. If you mistakenly subtract 1 from 0 using signed integers it often more quickly causes your program to crash and makes it easier to find the bug than if it wraps around to 2^32 - 1, and compilers and static analysis tools and runtime checks have to assume you know what you're doing since you chose to use unsigned arithmetic. Also, negative numbers like -1 can often represent something useful, like a field being ignored/defaulted/unset while if you were using unsigned you'd have to reserve a special value like 2^32 - 1 or something similar.

Long ago, when memory was limited and processors did not automatically operate on 64 bits at once, every bit counted a lot more, so having signed vs unsigned bytes or shorts actually mattered a lot more often and was obviously the right design decision. Today just using a signed int is more than sufficient in almost all regular programming cases, and if your program really needs to use values bigger than 2^31 - 1, you often just want a long anyway. Once you're into the territory of using longs, it's even harder to come up with a reason why you really can't get by with 2^63 - 1 positive integers. Whenever we go to 128 bit processors it'll be even less of an issue.

How to find and return a duplicate value in array

each_with_object is your friend!

input = [:bla,:blubb,:bleh,:bla,:bleh,:bla,:blubb,:brrr]

# to get the counts of the elements in the array:
> input.each_with_object({}){|x,h| h[x] ||= 0; h[x] += 1}
=> {:bla=>3, :blubb=>2, :bleh=>2, :brrr=>1}

# to get only the counts of the non-unique elements in the array:
> input.each_with_object({}){|x,h| h[x] ||= 0; h[x] += 1}.reject{|k,v| v < 2}
=> {:bla=>3, :blubb=>2, :bleh=>2}

How do I get the calling method name and type using reflection?

You can use it by using the StackTrace and then you can get reflective types from that.

StackTrace stackTrace = new StackTrace();           // get call stack
StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

StackFrame callingFrame = stackFrames[1];
MethodInfo method = callingFrame.GetMethod();
Console.Write(method.Name);
Console.Write(method.DeclaringType.Name);

Parsing JSON using C

Json isn't a huge language to start with, so libraries for it are likely to be small(er than Xml libraries, at least).

There are a whole ton of C libraries linked at Json.org. Maybe one of them will work well for you.

How do I add a newline using printf?

To write a newline use \n not /n the latter is just a slash and a n

What are the differences between a pointer variable and a reference variable in C++?

While both references and pointers are used to indirectly access another value, there are two important differences between references and pointers. The first is that a reference always refers to an object: It is an error to define a reference without initializing it. The behavior of assignment is the second important difference: Assigning to a reference changes the object to which the reference is bound; it does not rebind the reference to another object. Once initialized, a reference always refers to the same underlying object.

Consider these two program fragments. In the first, we assign one pointer to another:

int ival = 1024, ival2 = 2048;
int *pi = &ival, *pi2 = &ival2;
pi = pi2;    // pi now points to ival2

After the assignment, ival, the object addressed by pi remains unchanged. The assignment changes the value of pi, making it point to a different object. Now consider a similar program that assigns two references:

int &ri = ival, &ri2 = ival2;
ri = ri2;    // assigns ival2 to ival

This assignment changes ival, the value referenced by ri, and not the reference itself. After the assignment, the two references still refer to their original objects, and the value of those objects is now the same as well.

Create component to specific module with Angular-CLI

According to Angular docs the way to create a component for specific module is,

ng g component <directory name>/<component name>

"directory name" = where the CLI generated the feature module

Example :-

ng generate component customer-dashboard/CustomerDashboard

This generates a folder for the new component within the customer-dashboard folder and updates the feature module with the CustomerDashboardComponent

Is there a regular expression to detect a valid regular expression?

Though it is perfectly possible to use a recursive regex as MizardX has posted, for this kind of things it is much more useful a parser. Regexes were originally intended to be used with regular languages, being recursive or having balancing groups is just a patch.

The language that defines valid regexes is actually a context free grammar, and you should use an appropriate parser for handling it. Here is an example for a university project for parsing simple regexes (without most constructs). It uses JavaCC. And yes, comments are in Spanish, though method names are pretty self-explanatory.

SKIP :
{
    " "
|   "\r"
|   "\t"
|   "\n"
}
TOKEN : 
{
    < DIGITO: ["0" - "9"] >
|   < MAYUSCULA: ["A" - "Z"] >
|   < MINUSCULA: ["a" - "z"] >
|   < LAMBDA: "LAMBDA" >
|   < VACIO: "VACIO" >
}

IRegularExpression Expression() :
{
    IRegularExpression r; 
}
{
    r=Alternation() { return r; }
}

// Matchea disyunciones: ER | ER
IRegularExpression Alternation() :
{
    IRegularExpression r1 = null, r2 = null; 
}
{
    r1=Concatenation() ( "|" r2=Alternation() )?
    { 
        if (r2 == null) {
            return r1;
        } else {
            return createAlternation(r1,r2);
        } 
    }
}

// Matchea concatenaciones: ER.ER
IRegularExpression Concatenation() :
{
    IRegularExpression r1 = null, r2 = null; 
}
{
    r1=Repetition() ( "." r2=Repetition() { r1 = createConcatenation(r1,r2); } )*
    { return r1; }
}

// Matchea repeticiones: ER*
IRegularExpression Repetition() :
{
    IRegularExpression r; 
}
{
    r=Atom() ( "*" { r = createRepetition(r); } )*
    { return r; }
}

// Matchea regex atomicas: (ER), Terminal, Vacio, Lambda
IRegularExpression Atom() :
{
    String t;
    IRegularExpression r;
}
{
    ( "(" r=Expression() ")" {return r;}) 
    | t=Terminal() { return createTerminal(t); }
    | <LAMBDA> { return createLambda(); }
    | <VACIO> { return createEmpty(); }
}

// Matchea un terminal (digito o minuscula) y devuelve su valor
String Terminal() :
{
    Token t;
}
{
    ( t=<DIGITO> | t=<MINUSCULA> ) { return t.image; }
}

How to remove all debug logging calls before building the release version of an Android app?

I know this is an old question, but why didn't you replace all your log calls with something like Boolean logCallWasHere=true; //---rest of your log here

This why you will know when you want to put them back, and they won't affect your if statement call :)

Check if a string contains a string in C++

In the event if the functionality is critical to your system, it is actually beneficial to use an old strstr method. The std::search method within algorithm is the slowest possible. My guess would be that it takes a lot of time to create those iterators.

The code that i used to time the whole thing is

#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <random>
#include <chrono>

std::string randomString( size_t len );

int main(int argc, char* argv[])
{
        using namespace std::chrono;

        const size_t haystacksCount = 200000;
        std::string haystacks[haystacksCount];
        std::string needle = "hello";

        bool sink = true;

        high_resolution_clock::time_point start, end;
        duration<double> timespan;

        int sizes[10] = { 10, 20, 40, 80, 160, 320, 640, 1280, 5120, 10240 };

        for(int s=0; s<10; ++s)
        {
                std::cout << std::endl << "Generating " << haystacksCount << " random haystacks of size " << sizes[s] << std::endl;
                for(size_t i=0; i<haystacksCount; ++i)
                {
                        haystacks[i] = randomString(sizes[s]);
                }

                std::cout << "Starting std::string.find approach" << std::endl;
                start = high_resolution_clock::now();
                for(size_t i=0; i<haystacksCount; ++i)
                {
                        if(haystacks[i].find(needle) != std::string::npos)
                        {
                                sink = !sink; // useless action
                        }
                }
                end = high_resolution_clock::now();
                timespan = duration_cast<duration<double>>(end-start);
                std::cout << "Processing of " << haystacksCount << " elements took " << timespan.count() << " seconds." << std::endl;

                std::cout << "Starting strstr approach" << std::endl;
                start = high_resolution_clock::now();
                for(size_t i=0; i<haystacksCount; ++i)
                {
                        if(strstr(haystacks[i].c_str(), needle.c_str()))
                        {
                                sink = !sink; // useless action
                        }
                }
                end = high_resolution_clock::now();
                timespan = duration_cast<duration<double>>(end-start);
                std::cout << "Processing of " << haystacksCount << " elements took " << timespan.count() << " seconds." << std::endl;

                std::cout << "Starting std::search approach" << std::endl;
                start = high_resolution_clock::now();
                for(size_t i=0; i<haystacksCount; ++i)
                {
                        if(std::search(haystacks[i].begin(), haystacks[i].end(), needle.begin(), needle.end()) != haystacks[i].end())
                        {
                                sink = !sink; // useless action
                        }
                }
                end = high_resolution_clock::now();
                timespan = duration_cast<duration<double>>(end-start);
                std::cout << "Processing of " << haystacksCount << " elements took " << timespan.count() << " seconds." << std::endl;
        }

        return 0;
}

std::string randomString( size_t len)
{
        static const char charset[] = "abcdefghijklmnopqrstuvwxyz";
        static const int charsetLen = sizeof(charset) - 1;
        static std::default_random_engine rng(std::random_device{}());
        static std::uniform_int_distribution<> dist(0, charsetLen);
        auto randChar = [charset, &dist, &rng]() -> char
        {
                return charset[ dist(rng) ];
        };

        std::string result(len, 0);
        std::generate_n(result.begin(), len, randChar);
        return result;
}

Here i generate random haystacks and search in them the needle. The haystack count is set, but the length of strings within each haystack is increased from 10 in the beginning to 10240 in the end. Most of the time the program spends actually generating random strings, but that is to be expected.

The output is:

Generating 200000 random haystacks of size 10
Starting std::string.find approach
Processing of 200000 elements took 0.00358503 seconds.
Starting strstr approach
Processing of 200000 elements took 0.0022727 seconds.
Starting std::search approach
Processing of 200000 elements took 0.0346258 seconds.

Generating 200000 random haystacks of size 20
Starting std::string.find approach
Processing of 200000 elements took 0.00480959 seconds.
Starting strstr approach
Processing of 200000 elements took 0.00236199 seconds.
Starting std::search approach
Processing of 200000 elements took 0.0586416 seconds.

Generating 200000 random haystacks of size 40
Starting std::string.find approach
Processing of 200000 elements took 0.0082571 seconds.
Starting strstr approach
Processing of 200000 elements took 0.00341435 seconds.
Starting std::search approach
Processing of 200000 elements took 0.0952996 seconds.

Generating 200000 random haystacks of size 80
Starting std::string.find approach
Processing of 200000 elements took 0.0148288 seconds.
Starting strstr approach
Processing of 200000 elements took 0.00399263 seconds.
Starting std::search approach
Processing of 200000 elements took 0.175945 seconds.

Generating 200000 random haystacks of size 160
Starting std::string.find approach
Processing of 200000 elements took 0.0293496 seconds.
Starting strstr approach
Processing of 200000 elements took 0.00504251 seconds.
Starting std::search approach
Processing of 200000 elements took 0.343452 seconds.

Generating 200000 random haystacks of size 320
Starting std::string.find approach
Processing of 200000 elements took 0.0522893 seconds.
Starting strstr approach
Processing of 200000 elements took 0.00850485 seconds.
Starting std::search approach
Processing of 200000 elements took 0.64133 seconds.

Generating 200000 random haystacks of size 640
Starting std::string.find approach
Processing of 200000 elements took 0.102082 seconds.
Starting strstr approach
Processing of 200000 elements took 0.00925799 seconds.
Starting std::search approach
Processing of 200000 elements took 1.26321 seconds.

Generating 200000 random haystacks of size 1280
Starting std::string.find approach
Processing of 200000 elements took 0.208057 seconds.
Starting strstr approach
Processing of 200000 elements took 0.0105039 seconds.
Starting std::search approach
Processing of 200000 elements took 2.57404 seconds.

Generating 200000 random haystacks of size 5120
Starting std::string.find approach
Processing of 200000 elements took 0.798496 seconds.
Starting strstr approach
Processing of 200000 elements took 0.0137969 seconds.
Starting std::search approach
Processing of 200000 elements took 10.3573 seconds.

Generating 200000 random haystacks of size 10240
Starting std::string.find approach
Processing of 200000 elements took 1.58171 seconds.
Starting strstr approach
Processing of 200000 elements took 0.0143111 seconds.
Starting std::search approach
Processing of 200000 elements took 20.4163 seconds.

Python 2.7.10 error "from urllib.request import urlopen" no module named request

You can program defensively, and do your import as:

try:
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen

and then in the code, just use:

data = urlopen(MIRRORS).read(AMOUNT2READ)

How to return 2 values from a Java method?

Java does not support multi-value returns. Return an array of values.

// Function code
public static int[] something(){
    int number1 = 1;
    int number2 = 2;
    return new int[] {number1, number2};
}

// Main class code
public static void main(String[] args) {
  int result[] = something();
  System.out.println(result[0] + result[1]);
}

Efficient way to update all rows in a table

As Marcelo suggests:

UPDATE mytable
SET new_column = <expr containing old_column>;

If this takes too long and fails due to "snapshot too old" errors (e.g. if the expression queries another highly-active table), and if the new value for the column is always NOT NULL, you could update the table in batches:

UPDATE mytable
SET new_column = <expr containing old_column>
WHERE new_column IS NULL
AND ROWNUM <= 100000;

Just run this statement, COMMIT, then run it again; rinse, repeat until it reports "0 rows updated". It'll take longer but each update is less likely to fail.

EDIT:

A better alternative that should be more efficient is to use the DBMS_PARALLEL_EXECUTE API.

Sample code (from Oracle docs):

DECLARE
  l_sql_stmt VARCHAR2(1000);
  l_try NUMBER;
  l_status NUMBER;
BEGIN

  -- Create the TASK
  DBMS_PARALLEL_EXECUTE.CREATE_TASK ('mytask');

  -- Chunk the table by ROWID
  DBMS_PARALLEL_EXECUTE.CREATE_CHUNKS_BY_ROWID('mytask', 'HR', 'EMPLOYEES', true, 100);

  -- Execute the DML in parallel
  l_sql_stmt := 'update EMPLOYEES e 
      SET e.salary = e.salary + 10
      WHERE rowid BETWEEN :start_id AND :end_id';
  DBMS_PARALLEL_EXECUTE.RUN_TASK('mytask', l_sql_stmt, DBMS_SQL.NATIVE,
                                 parallel_level => 10);

  -- If there is an error, RESUME it for at most 2 times.
  l_try := 0;
  l_status := DBMS_PARALLEL_EXECUTE.TASK_STATUS('mytask');
  WHILE(l_try < 2 and l_status != DBMS_PARALLEL_EXECUTE.FINISHED) 
  LOOP
    l_try := l_try + 1;
    DBMS_PARALLEL_EXECUTE.RESUME_TASK('mytask');
    l_status := DBMS_PARALLEL_EXECUTE.TASK_STATUS('mytask');
  END LOOP;

  -- Done with processing; drop the task
  DBMS_PARALLEL_EXECUTE.DROP_TASK('mytask');

END;
/

Oracle Docs: https://docs.oracle.com/database/121/ARPLS/d_parallel_ex.htm#ARPLS67333

How to toggle boolean state of react component?

You should use this.state.check instead of check.value here:

this.setState({check: !this.state.check})

But anyway it is bad practice to do it this way. Much better to move it to separate method and don't write callbacks directly in markup.

How do I "commit" changes in a git submodule?

Before you can commit and push, you need to init a working repository tree for a submodule. I am using tortoise and do following things:

First check if there exist .git file (not a directory)

  • if there is such file it contains path to supermodule git directory
  • delete this file
  • do git init
  • do git add remote path the one used for submodule
  • follow instructions below

If there was .git file, there surly was .git directory which tracks local tree. You still need to a branch (you can create one) or switch to master (which sometimes does not work). Best to do is - git fetch - git pull. Do not omit fetch.

Now your commits and pulls will be synchronized with your origin/master

How can I install a package with go get?

First, we need GOPATH

The $GOPATH is a folder (or set of folders) specified by its environment variable. We must notice that this is not the $GOROOT directory where Go is installed.

export GOPATH=$HOME/gocode
export PATH=$PATH:$GOPATH/bin

We used ~/gocode path in our computer to store the source of our application and its dependencies. The GOPATH directory will also store the binaries of their packages.

Then check Go env

You system must have $GOPATH and $GOROOT, below is my Env:

GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/elpsstu/gocode"
GORACE=""
GOROOT="/home/pravin/go"
GOTOOLDIR="/home/pravin/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"

Now, you run download go package:

go get [-d] [-f] [-fix] [-t] [-u] [build flags] [packages]

Get downloads and installs the packages named by the import paths, along with their dependencies. For more details you can look here.

How to retrieve an Oracle directory path?

select directory_path from dba_directories where upper(directory_name) = 'CSVDIR'

Adding a splash screen to Flutter apps

In case you want a secondary splash screen (after the native one), here is a simple example that works:

class SplashPage extends StatelessWidget {
  SplashPage(BuildContext context) {
    Future.delayed(const Duration(seconds: 3), () {
      // Navigate here to next screen
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text('Splash screen here');
  }
}

How to horizontally center an unordered list of unknown width?

It depends on if you mean the list items are below the previous or to the right of the previous, ie:

Home
About
Contact

or

Home | About | Contact

The first one you can do simply with:

#wrapper { width:600px; background: yellow; margin: 0 auto; }
#footer ul { text-align: center; list-style-type: none; }

The second could be done like this:

#wrapper { width:600px; background: yellow; margin: 0 auto; }
#footer ul { text-align: center; list-style-type: none; }
#footer li { display: inline; }
#footer a { padding: 2px 12px; background: orange; text-decoration: none; }
#footer a:hover { background: green; color: yellow; }

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

I had this same error but it was because I had recently changed from using v4 to v13. So all I had to do was clean the project.

Java - Search for files in a directory

you can try something like this:

import java.io.*;
import java.util.*;
class FindFile 
{
    public void findFile(String name,File file)
    {
        File[] list = file.listFiles();
        if(list!=null)
        for (File fil : list)
        {
            if (fil.isDirectory())
            {
                findFile(name,fil);
            }
            else if (name.equalsIgnoreCase(fil.getName()))
            {
                System.out.println(fil.getParentFile());
            }
        }
    }
    public static void main(String[] args) 
    {
        FindFile ff = new FindFile();
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the file to be searched.. " );
        String name = scan.next();
        System.out.println("Enter the directory where to search ");
        String directory = scan.next();
        ff.findFile(name,new File(directory));
    }
}

Here is the output:

J:\Java\misc\load>java FindFile
Enter the file to be searched..
FindFile.java
Enter the directory where to search
j:\java\
FindFile.java Found in->j:\java\misc\load

How to SUM and SUBTRACT using SQL?

An example for subtraction is given below:

Select value1 - (select value2 from AnyTable1) from AnyTable2

value1 & value2 can be count,sum,average output etc. But the values should be comapatible

How can I prevent a window from being resized with tkinter?

This code makes a window with the conditions that the user cannot change the dimensions of the Tk() window, and also disables the maximise button.

import tkinter as tk

root = tk.Tk()
root.resizable(width=False, height=False)
root.mainloop()

Within the program you can change the window dimensions with @Carpetsmoker's answer, or by doing this:

root.geometry('{}x{}'.format(<widthpixels>, <heightpixels>))

It should be fairly easy for you to implement that into your code. :)

Removing App ID from Developer Connection

Delete application IDs is allowed. Make sure you deleted all certificates, APNS certs and provisioning profiles associated with your application. Then go to Identitifies --> App IDs, select the application ID, Edit and Delete button should be enabled.

Better naming in Tuple classes than "Item1", "Item2"

Up to C# 7.0, there was no way to do this short of defining your own type.

CSS @media print issues with background-color;

tr.group-title {
  padding-top: .5rem;
  border-top: 2rem solid lightgray;
}

tr.group-title > td h5 {
  margin-top: -1.9rem;
}

          <tbody>
            <tr class="group-title">
              <td colspan="6">
                <h5 align="center">{{ group.title }}</h5>
              </td>
            </tr>

Works in Chrome and Edge

Decimal separator comma (',') with numberDecimal inputType in EditText

You could do the following:

DecimalFormatSymbols d = DecimalFormatSymbols.getInstance(Locale.getDefault());
input.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(5, 2) });
input.setKeyListener(DigitsKeyListener.getInstance("0123456789" + d.getDecimalSeparator()));

And then you could use an input filter:

    public class DecimalDigitsInputFilter implements InputFilter {

Pattern mPattern;

public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
    DecimalFormatSymbols d = new DecimalFormatSymbols(Locale.getDefault());
    String s = "\\" + d.getDecimalSeparator();
    mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((" + s + "[0-9]{0," + (digitsAfterZero - 1) + "})?)||(" + s + ")?");
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

    Matcher matcher = mPattern.matcher(dest);
    if (!matcher.matches())
        return "";
    return null;
}

}

CSS: how to position element in lower right?

Set the CSS position: relative; on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:

position: absolute;
bottom: 0;
right: 0;

If you need to space the text farther away from the edge, you could change 0 to 2px or similar.

Test if remote TCP port is open from a shell script

I'm guessing that it's too late for an answer, and this might not be a good one, but here you go...

What about putting it inside of a while loop with a timer on it of some sort. I'm more of a Perl guy than Solaris, but depending on the shell you're using, you should be able to do something like:

TIME = 'date +%s' + 15
while TIME != `date +%s'
do whatever

And then just add a flag in the while loop, so that if it times out before completing, you can cite the timeout as reason for failure.

I suspect that the telnet has a timeout switch as well, but just off the top of my head, I think the above will work.

how to query child objects in mongodb

Assuming your "states" collection is like:

{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }

The query to find states with null cities would be:

db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});

It is a common mistake to query for nulls as:

db.states.find({"cities.name" : null});

because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.

JavaScript - cannot set property of undefined

The object stored at d[a] has not been set to anything. Thus, d[a] evaluates to undefined. You can't assign a property to undefined :). You need to assign an object or array to d[a]:

d[a] = [];
d[a]["greeting"] = b;

console.debug(d);

React - changing an uncontrolled input

An update for this. For React Hooks use const [name, setName] = useState(" ")

Javascript return number of days,hours,minutes,seconds between two dates

function calculateExamRemainingTime(exam_end_at) {

$(function(){

    const calcNewYear = setInterval(function(){

        const exam_ending_at    = new Date(exam_end_at);
        const current_time      = new Date();
       
        const totalSeconds     = Math.floor((exam_ending_at - (current_time))/1000);;
        const totalMinutes     = Math.floor(totalSeconds/60);
        const totalHours       = Math.floor(totalMinutes/60);
        const totalDays        = Math.floor(totalHours/24);

        const hours   = totalHours - ( totalDays * 24 );
        const minutes = totalMinutes - ( totalDays * 24 * 60 ) - ( hours * 60 );
        const seconds = totalSeconds - ( totalDays * 24 * 60 * 60 ) - ( hours * 60 * 60 ) - ( minutes * 60 );

        const examRemainingHoursSection = document.querySelector('#remainingHours');
        const examRemainingMinutesSection = document.querySelector('#remainingMinutes');
        const examRemainingSecondsSection = document.querySelector('#remainingSeconds');

        examRemainingHoursSection.innerHTML = hours.toString();
        examRemainingMinutesSection.innerHTML = minutes.toString();
        examRemainingSecondsSection.innerHTML = seconds.toString();

    },1000);
});
}

calculateExamRemainingTime('2025-06-03 20:20:20');

How do I turn off Unicode in a VC++ project?

For whatever reason, I noticed that setting to unicode for "All Configurations" did not actually apply to all configurations.

Picture: Setting Configuragion In IDE

To confirm this, I would open the .vcxproj and confirm the correct token is in all 4 locations. In this photo, I am using unicode. So the string I am looking for is "Unicode". For you, you likely want it to say "MultiByte".

Picture: Confirming changes in configuration file

What does "yield break;" do in C#?

Tells the iterator that it's reached the end.

As an example:

public interface INode
{
    IEnumerable<Node> GetChildren();
}

public class NodeWithTenChildren : INode
{
    private Node[] m_children = new Node[10];

    public IEnumerable<Node> GetChildren()
    {
        for( int n = 0; n < 10; ++n )
        {
            yield return m_children[ n ];
        }
    }
}

public class NodeWithNoChildren : INode
{
    public IEnumerable<Node> GetChildren()
    {
        yield break;
    }
}

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

I guess it doesn't mean anything to you now. But just for reference for people stopping by

Performance Test - SortedList vs. SortedDictionary vs. Dictionary vs. Hashtable

Memory allocation:

Memory usage performance test

Time used for inserting:

Time used for inserting

Time for searching an item:

Time for searching an item

Interface type check with Typescript

Based on Fenton's answer, here's my implementation of a function to verify if a given object has the keys an interface has, both fully or partially.

Depending on your use case, you may also need to check the types of each of the interface's properties. The code below doesn't do that.

function implementsTKeys<T>(obj: any, keys: (keyof T)[]): obj is T {
    if (!obj || !Array.isArray(keys)) {
        return false;
    }

    const implementKeys = keys.reduce((impl, key) => impl && key in obj, true);

    return implementKeys;
}

Example of usage:

interface A {
    propOfA: string;
    methodOfA: Function;
}

let objectA: any = { propOfA: '' };

// Check if objectA partially implements A
let implementsA = implementsTKeys<A>(objectA, ['propOfA']);

console.log(implementsA); // true

objectA.methodOfA = () => true;

// Check if objectA fully implements A
implementsA = implementsTKeys<A>(objectA, ['propOfA', 'methodOfA']);

console.log(implementsA); // true

objectA = {};

// Check again if objectA fully implements A
implementsA = implementsTKeys<A>(objectA, ['propOfA', 'methodOfA']);

console.log(implementsA); // false, as objectA now is an empty object

PHPExcel - creating multiple sheets by iteration

You can write different sheets as follows

$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("creater");
$objPHPExcel->getProperties()->setLastModifiedBy("Middle field");
$objPHPExcel->getProperties()->setSubject("Subject");
$objWorkSheet = $objPHPExcel->createSheet();
$work_sheet_count=3;//number of sheets you want to create
$work_sheet=0;
while($work_sheet<=$work_sheet_count){ 
     if($work_sheet==0){
         $objWorkSheet->setTitle("Worksheet$work_sheet");
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 1')->getStyle('A1')->getFont()->setBold(true);
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
     }
     if($work_sheet==1){
         $objWorkSheet->setTitle("Worksheet$work_sheet");
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 2')->getStyle('A1')->getFont()->setBold(true);
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
     }
     if($work_sheet==2){
         $objWorkSheet = $objPHPExcel->createSheet($work_sheet_count);
         $objWorkSheet->setTitle("Worksheet$work_sheet");
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 3')->getStyle('A1')->getFont()->setBold(true);
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
     }
     $work_sheet++;
}

$filename='file-name'.'.xls'; //save our workbook as this file name
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cach

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

How can I give the Intellij compiler more heap space?

I was facing "java.lang.OutOfMemoryError: Java heap space" error while building my project using maven install command.

I was able to get rid of it by changing maven runner settings.

Settings | Build, Execution, Deployment | Build Tools | Maven | Runner | VM options to -Xmx512m

Why maven settings.xml file is not there?

Installation of Maven doesn't create the settings.xml file. You have to create it on your own. Just put it in your .m2 directory where you expected it, see http://maven.apache.org/settings.html for reference. The m2eclipse plugin will use the same settings file as the command line.

How do I load an HTTP URL with App Transport Security enabled in iOS 9?

See Apple’s Info.plist reference for full details (thanks @gnasher729).

You can add exceptions for specific domains in your Info.plist:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>testdomain.com</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <true/>
            <key>NSExceptionMinimumTLSVersion</key>
            <string>TLSv1.2</string>
            <key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
            <false/>
            <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
            <true/>
            <key>NSThirdPartyExceptionMinimumTLSVersion</key>
            <string>TLSv1.2</string>
            <key>NSRequiresCertificateTransparency</key>
            <false/>
        </dict>
    </dict>
</dict>

All the keys for each excepted domain are optional. The speaker did not elaborate on any of the keys, but I think they’re all reasonably obvious.

(Source: WWDC 2015 session 703, “Privacy and Your App”, 30:18)

You can also ignore all app transport security restrictions with a single key, if your app has a good reason to do so:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

If your app does not have a good reason, you may risk rejection:

Setting NSAllowsArbitraryLoads to true will allow it to work, but Apple was very clear in that they intend to reject apps who use this flag without a specific reason. The main reason to use NSAllowsArbitraryLoads I can think of would be user created content (link sharing, custom web browser, etc). And in this case, Apple still expects you to include exceptions that enforce the ATS for the URLs you are in control of.

If you do need access to specific URLs that are not served over TLS 1.2, you need to write specific exceptions for those domains, not use NSAllowsArbitraryLoads set to yes. You can find more info in the NSURLSesssion WWDC session.

Please be careful in sharing the NSAllowsArbitraryLoads solution. It is not the recommended fix from Apple.

kcharwood (thanks @marco-tolman)

How can I delay a :hover effect in CSS?

div {
     background: #dbdbdb;
    -webkit-transition: .5s all;   
    -webkit-transition-delay: 5s; 
    -moz-transition: .5s all;   
    -moz-transition-delay: 5s; 
    -ms-transition: .5s all;   
    -ms-transition-delay: 5s; 
    -o-transition: .5s all;   
    -o-transition-delay: 5s; 
    transition: .5s all;   
    transition-delay: 5s; 
}

div:hover {
    background:#5AC900;
    -webkit-transition-delay: 0s;
    -moz-transition-delay: 0s;
    -ms-transition-delay: 0s;
    -o-transition-delay: 0s;
    transition-delay: 0s;
}

This will add a transition delay, which will be applicable to almost every browser..

Start HTML5 video at a particular position when loading?

adjust video start and end time when using the video tag in html5;

http://www.yoursite.com/yourfolder/yourfile.mp4#t=5,15

where left of comma is start time in seconds, right of comma is end time in seconds. drop the comma and end time to effect the start time only.

Git Pull While Ignoring Local Changes?

This will fetch the current branch and attempt to do a fast forward to master:

git fetch && git merge --ff-only origin/master

Clicking at coordinates without identifying element

In Selenium Java, you can try it using Javascript:

_x000D_
_x000D_
WebDriver driver = new ChromeDriver();_x000D_
_x000D_
if (driver instanceof JavascriptExecutor) {_x000D_
 ((JavascriptExecutor) driver).executeScript("el = document.elementFromPoint(x-cordinate, y-cordinate); el.click();");_x000D_
}
_x000D_
_x000D_
_x000D_

How can I correctly format currency using jquery?

Try regexp currency with jQuery (no plugin):

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $('#test').click(function() {_x000D_
    TESTCURRENCY = $('#value').val().toString().match(/(?=[\s\d])(?:\s\.|\d+(?:[.]\d+)*)/gmi);_x000D_
    if (TESTCURRENCY.length <= 1) {_x000D_
      $('#valueshow').val(_x000D_
        parseFloat(TESTCURRENCY.toString().match(/^\d+(?:\.\d{0,2})?/))_x000D_
      );_x000D_
    } else {_x000D_
      $('#valueshow').val('Invalid a value!');_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="text" value="12345.67890" id="value">_x000D_
<input type="button" id="test" value="CLICK">_x000D_
<input type="text" value="" id="valueshow">
_x000D_
_x000D_
_x000D_

Edit: New check a value to valid/invalid

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

The Qt documentations has an Image Viewer example which demonstrates handling resizing images inside a QLabel. The basic idea is to use QScrollArea as a container for the QLabel and if needed use label.setScaledContents(bool) and scrollarea.setWidgetResizable(bool) to fill available space and/or ensure QLabel inside is resizable. Additionally, to resize QLabel while honoring aspect ratio use:

label.setPixmap(pixmap.scaled(width, height, Qt::KeepAspectRatio, Qt::FastTransformation));

The width and height can be set based on scrollarea.width() and scrollarea.height(). In this way there is no need to subclass QLabel.

HTML5 validation when the input type is not "submit"

The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.

However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method. If you would like to display the same error messages as the browser would do in HTML5 form validation, I’m afraid you would need to check all the constrained fields, since the validityMessage property is a property of fields (controls), not the form. In the case of a single constrained field, as in the case presented, this is trivial of course:

function submitform() {
  var f = document.getElementsByTagName('form')[0];
  if(f.checkValidity()) {
    f.submit();
  } else {
    alert(document.getElementById('example').validationMessage);
  }
}

WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"

Just recently experienced this:

System.ServiceModel.CommunicationException:

An error occurred while making the HTTP request to http://example.com/WebServices/SomeService.svc. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server.

---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send.

---> System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.

Our license of the bluecoat proxy was expired! so it was not possible to to reach the external party (internet).

requestFeature() must be called before adding content

In my case I showed DialogFragment in Activity. In this dialog fragment I wrote as in DialogFragment remove black border:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setStyle(STYLE_NO_FRAME, 0)
}

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    super.onCreateDialog(savedInstanceState)

    val dialog = Dialog(context!!, R.style.ErrorDialogTheme)
    val inflater = LayoutInflater.from(context)
    val view = inflater.inflate(R.layout.fragment_error_dialog, null, false)
    dialog.setTitle(null)
    dialog.setCancelable(true)
    dialog.setContentView(view)
    return dialog
}

Either remove setStyle(STYLE_NO_FRAME, 0) in onCreate() or chande/remove onCreateDialog. Because dialog settings have changed after the dialog has been created.

How can I parse a CSV string with JavaScript, which contains comma in data?

No regexp, readable, and according to https://en.wikipedia.org/wiki/Comma-separated_values#Basic_rules:

function csv2arr(str: string) {
    let line = ["",];
    const ret = [line,];
    let quote = false;

    for (let i = 0; i < str.length; i++) {
        const cur = str[i];
        const next = str[i + 1];

        if (!quote) {
            const cellIsEmpty = line[line.length - 1].length === 0;
            if (cur === '"' && cellIsEmpty) quote = true;
            else if (cur === ",") line.push("");
            else if (cur === "\r" && next === "\n") { line = ["",]; ret.push(line); i++; }
            else if (cur === "\n" || cur === "\r") { line = ["",]; ret.push(line); }
            else line[line.length - 1] += cur;
        } else {
            if (cur === '"' && next === '"') { line[line.length - 1] += cur; i++; }
            else if (cur === '"') quote = false;
            else line[line.length - 1] += cur;
        }
    }
    return ret;
}

Git - How to close commit editor?

Better yet, configure the editor to something you are comfortable with (gedit as an example):

git config --global core.editor "gedit"

You can read the current configuration like this:

git config core.editor

You can also add the commit message from the command line.

git commit -m "blablabla"

and the editor will not be opened in the first place.

JavaScript: set dropdown selected item based on option text

You can loop through the select_obj.options. There's a #text method in each of the option object, which you can use to compare to what you want and set the selectedIndex of the select_obj.

What does value & 0xff do in Java?

It sets result to the (unsigned) value resulting from putting the 8 bits of value in the lowest 8 bits of result.

The reason something like this is necessary is that byte is a signed type in Java. If you just wrote:

int result = value;

then result would end up with the value ff ff ff fe instead of 00 00 00 fe. A further subtlety is that the & is defined to operate only on int values1, so what happens is:

  1. value is promoted to an int (ff ff ff fe).
  2. 0xff is an int literal (00 00 00 ff).
  3. The & is applied to yield the desired value for result.

(The point is that conversion to int happens before the & operator is applied.)

1Well, not quite. The & operator works on long values as well, if either operand is a long. But not on byte. See the Java Language Specification, sections 15.22.1 and 5.6.2.

Form Submit Execute JavaScript Best Practice?

Use the onsubmit event to execute JavaScript code when the form is submitted. You can then return false or call the passed event's preventDefault method to disable the form submission.

For example:

<script>
function doSomething() {
    alert('Form submitted!');
    return false;
}
</script>

<form onsubmit="return doSomething();" class="my-form">
    <input type="submit" value="Submit">
</form>

This works, but it's best not to litter your HTML with JavaScript, just as you shouldn't write lots of inline CSS rules. Many Javascript frameworks facilitate this separation of concerns. In jQuery you bind an event using JavaScript code like so:

<script>
$('.my-form').on('submit', function () {
    alert('Form submitted!');
    return false;
});
</script>

<form class="my-form">
    <input type="submit" value="Submit">
</form>

jQuery's .on() method combined with the submit event

I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.

For example:

 $("#id_form").on("submit", function(){
   //Code: Action (like ajax...)
   return false;
 })

How to implement a lock in JavaScript

Locks are a concept required in a multi-threaded system. Even with worker threads, messages are sent by value between workers so that locking is unnecessary.

I suspect you need to just set a semaphore (flagging system) between your buttons.

How to use a findBy method with comparative criteria

$criteria = new \Doctrine\Common\Collections\Criteria();
    $criteria->where($criteria->expr()->gt('id', 'id'))
        ->setMaxResults(1)
        ->orderBy(array("id" => $criteria::DESC));

$results = $articlesRepo->matching($criteria);

What is the easiest way to parse an INI file in Java?

As simple as 80 lines:

package windows.prefs;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IniFile {

   private Pattern  _section  = Pattern.compile( "\\s*\\[([^]]*)\\]\\s*" );
   private Pattern  _keyValue = Pattern.compile( "\\s*([^=]*)=(.*)" );
   private Map< String,
      Map< String,
         String >>  _entries  = new HashMap<>();

   public IniFile( String path ) throws IOException {
      load( path );
   }

   public void load( String path ) throws IOException {
      try( BufferedReader br = new BufferedReader( new FileReader( path ))) {
         String line;
         String section = null;
         while(( line = br.readLine()) != null ) {
            Matcher m = _section.matcher( line );
            if( m.matches()) {
               section = m.group( 1 ).trim();
            }
            else if( section != null ) {
               m = _keyValue.matcher( line );
               if( m.matches()) {
                  String key   = m.group( 1 ).trim();
                  String value = m.group( 2 ).trim();
                  Map< String, String > kv = _entries.get( section );
                  if( kv == null ) {
                     _entries.put( section, kv = new HashMap<>());   
                  }
                  kv.put( key, value );
               }
            }
         }
      }
   }

   public String getString( String section, String key, String defaultvalue ) {
      Map< String, String > kv = _entries.get( section );
      if( kv == null ) {
         return defaultvalue;
      }
      return kv.get( key );
   }

   public int getInt( String section, String key, int defaultvalue ) {
      Map< String, String > kv = _entries.get( section );
      if( kv == null ) {
         return defaultvalue;
      }
      return Integer.parseInt( kv.get( key ));
   }

   public float getFloat( String section, String key, float defaultvalue ) {
      Map< String, String > kv = _entries.get( section );
      if( kv == null ) {
         return defaultvalue;
      }
      return Float.parseFloat( kv.get( key ));
   }

   public double getDouble( String section, String key, double defaultvalue ) {
      Map< String, String > kv = _entries.get( section );
      if( kv == null ) {
         return defaultvalue;
      }
      return Double.parseDouble( kv.get( key ));
   }
}

How to use Typescript with native ES6 Promises

Using native ES6 Promises with Typescript in Visual Studio 2015 + Node.js tools 1.2

No npm install required as ES6 Promises is native.

Node.js project -> Properties -> Typescript Build tab ECMAScript version = ECMAScript6

import http = require('http');
import fs = require('fs');

function findFolderAsync(directory : string): Promise<string> {

    let p = new Promise<string>(function (resolve, reject) {

        fs.stat(directory, function (err, stats) {

            //Check if error defined and the error code is "not exists"
            if (err && err.code === "ENOENT") {
                reject("Directory does not exist");
            }
            else {
                resolve("Directory exists");
            }
        });

    });
    return p;
}

findFolderAsync("myFolder").then(

    function (msg : string) {
        console.log("Promise resolved as " + msg); 
    },
    function (msg : string) {
        console.log("Promise rejected as " + msg); 
    }
);

DateTime.ToString() format that can be used in a filename or extension?

You can try with

var result = DateTime.Now.ToString("yyyy-MM-d--HH-mm-ss");

Django request get parameters

You may also use:

request.POST.get('section','') # => [39]
request.POST.get('MAINS','') # => [137] 
request.GET.get('section','') # => [39]
request.GET.get('MAINS','') # => [137]

Using this ensures that you don't get an error. If the POST/GET data with any key is not defined then instead of raising an exception the fallback value (second argument of .get() will be used).

Is there a way to remove the separator line from a UITableView?

In interface Builder set table view separator "None"

enter image description here and those separator lines which are shown after the last cell can be remove by following approach. Best approach is to assign Empty View to tableView FooterView in viewDidLoad

self.tableView.tableFooterView = UIView()