Programs & Examples On #Touchesbegan

Swift addsubview and remove it

Thanks for help. This is the solution: I created the subview and i add a gesture to remove it

@IBAction func infoView(sender: UIButton) {
    var testView: UIView = UIView(frame: CGRectMake(0, 0, 320, 568))
    testView.backgroundColor = UIColor.blueColor()
    testView.alpha = 0.5
    testView.tag = 100
    testView.userInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = "removeSubview"
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

func removeSubview(){
    println("Start remove sibview")
    if let viewWithTag = self.view.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        println("No!")
    }
}

Update:

Swift 3+

@IBAction func infoView(sender: UIButton) {
    let testView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568))
    testView.backgroundColor = .blue
    testView.alpha = 0.5
    testView.tag = 100
    testView.isUserInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = #selector(GasMapViewController.removeSubview)
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

func removeSubview(){
    print("Start remove sibview")
    if let viewWithTag = self.view.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        print("No!")
    }
}

Using isKindOfClass with Swift

I would use:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    super.touchesBegan(touches, withEvent: event)
    let touch : UITouch = touches.anyObject() as UITouch

    if let touchView = touch.view as? UIPickerView
    {

    }
}

How to dismiss keyboard iOS programmatically when pressing return

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view.subviews enumerateObjectsUsingBlock:^(UIView* obj, NSUInteger idx, BOOL *stop) {
    if ([obj isKindOfClass:[UITextField class]]) {
        [obj resignFirstResponder];
    }
}];
}

when you using more then one textfield in screen With this method you doesn't need to mention textfield every time like

[textField1 resignFirstResponder];
[textField2 resignFirstResponder];

UITapGestureRecognizer - single tap and double tap

You need to use the requireGestureRecognizerToFail: method. Something like this:

[singleTapRecognizer requireGestureRecognizerToFail:doubleTapRecognizer];

How to add a touch event to a UIView?

Swift 3 & Swift 4

import UIKit

extension UIView {
  func addTapGesture(tapNumber: Int, target: Any, action: Selector) {
    let tap = UITapGestureRecognizer(target: target, action: action)
    tap.numberOfTapsRequired = tapNumber
    addGestureRecognizer(tap)
    isUserInteractionEnabled = true
  }
}

Use

yourView.addTapGesture(tapNumber: 1, target: self, action: #selector(yourMethod))

std::enable_if to conditionally compile a member function

I made this short example which also works.

#include <iostream>
#include <type_traits>

class foo;
class bar;

template<class T>
struct is_bar
{
    template<class Q = T>
    typename std::enable_if<std::is_same<Q, bar>::value, bool>::type check()
    {
        return true;
    }

    template<class Q = T>
    typename std::enable_if<!std::is_same<Q, bar>::value, bool>::type check()
    {
        return false;
    }
};

int main()
{
    is_bar<foo> foo_is_bar;
    is_bar<bar> bar_is_bar;
    if (!foo_is_bar.check() && bar_is_bar.check())
        std::cout << "It works!" << std::endl;

    return 0;
}

Comment if you want me to elaborate. I think the code is more or less self-explanatory, but then again I made it so I might be wrong :)

You can see it in action here.

.NET String.Format() to add commas in thousands place for a number

int number = 1000000000;
string whatYouWant = number.ToString("#,##0");
//You get: 1,000,000,000

Bootstrap change carousel height

Thank you! This post is Very Helpful. You may also want to add

object-fit:cover;

To preserve the aspect ration for different window sizes

.carousel .item {
  height: 500px;
}

.item img {
    position: absolute;
    object-fit:cover;
    top: 0;
    left: 0;
    min-height: 500px;
}

For bootstrap 4 and above replace .item with .carousel-item

.carousel .carousel-item {
  height: 500px;
}

.carousel-item img {
    position: absolute;
    object-fit:cover;
    top: 0;
    left: 0;
    min-height: 500px;
}

How do I perform an IF...THEN in an SQL SELECT?

Use pure bit logic:

DECLARE @Product TABLE (
    id INT PRIMARY KEY IDENTITY NOT NULL
   ,Obsolote CHAR(1)
   ,Instock CHAR(1)
)

INSERT INTO @Product ([Obsolote], [Instock])
    VALUES ('N', 'N'), ('N', 'Y'), ('Y', 'Y'), ('Y', 'N')

;
WITH cte
AS
(
    SELECT
        'CheckIfInstock' = CAST(ISNULL(NULLIF(ISNULL(NULLIF(p.[Instock], 'Y'), 1), 'N'), 0) AS BIT)
       ,'CheckIfObsolote' = CAST(ISNULL(NULLIF(ISNULL(NULLIF(p.[Obsolote], 'N'), 0), 'Y'), 1) AS BIT)
       ,*
    FROM
        @Product AS p
)
SELECT
    'Salable' = c.[CheckIfInstock] & ~c.[CheckIfObsolote]
   ,*
FROM
    [cte] c

See working demo: if then without case in SQL Server.

For start, you need to work out the value of true and false for selected conditions. Here comes two NULLIF:

for true: ISNULL(NULLIF(p.[Instock], 'Y'), 1)
for false: ISNULL(NULLIF(p.[Instock], 'N'), 0)

combined together gives 1 or 0. Next use bitwise operators.

It's the most WYSIWYG method.

malloc an array of struct pointers

array is a slightly misleading name. For a dynamically allocated array of pointers, malloc will return a pointer to a block of memory. You need to use Chess* and not Chess[] to hold the pointer to your array.

Chess *array = malloc(size * sizeof(Chess));
array[i] = NULL;

and perhaps later:

/* create new struct chess */
array[i] = malloc(sizeof(struct chess));

/* set up its members */
array[i]->size = 0;
/* etc. */

How can I set my Cygwin PATH to find javac?

To bring more prominence to the useful comment by @johanvdw:

If you want to ensure your your javac file path is always know when cygwin starts, you may edit your .bash_profile file. In this example you would add export PATH=$PATH:"/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/" somewhere in the file.

When Cygwin starts, it'll search directories in PATH and this one for executable files to run.

How can I create an observable with a delay

Using the following imports:

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/delay';

Try this:

let fakeResponse = [1,2,3];
let delayedObservable = Observable.of(fakeResponse).delay(5000);
delayedObservable.subscribe(data => console.log(data));

UPDATE: RXJS 6

The above solution doesn't really work anymore in newer versions of RXJS (and of angular for example).

So the scenario is that I have an array of items to check with an API with. The API only accepts a single item, and I do not want to kill the API by sending all requests at once. So I need a timed release of items on the Observable stream with a small delay in between.

Use the following imports:

import { from, of } from 'rxjs';
import { delay } from 'rxjs/internal/operators';
import { concatMap } from 'rxjs/internal/operators';

Then use the following code:

const myArray = [1,2,3,4];

from(myArray).pipe(
        concatMap( item => of(item).pipe ( delay( 1000 ) ))
    ).subscribe ( timedItem => {
        console.log(timedItem)
    });

It basically creates a new 'delayed' Observable for every item in your array. There are probably many other ways of doing it, but this worked fine for me, and complies with the 'new' RXJS format.

How do I calculate r-squared using Python and Numpy?

Here's a very simple python function to compute R^2 from the actual and predicted values assuming y and y_hat are pandas series:

def r_squared(y, y_hat):
    y_bar = y.mean()
    ss_tot = ((y-y_bar)**2).sum()
    ss_res = ((y-y_hat)**2).sum()
    return 1 - (ss_res/ss_tot)

How to open the command prompt and insert commands using Java?

If you are running two commands at once just to change the directory the command prompt runs in, there is an overload for the Runtime.exec method that lets you specify the current working directory. Like,

Runtime rt = Runtime.getRuntime();
rt.exec("cmd.exe /c start command", null, new File(newDir));

This will open command prompt in the directory at newDir. I think your solution works as well, but this keeps your command string or array a little cleaner.

There is an overload for having the command as a string and having the command as a String array.

You may find it even easier, though, to use the ProcessBuilder, which has a directory method to set your current working directory.

Hope this helps.

sql try/catch rollback/commit - preventing erroneous commit after rollback

In your first example, you are correct. The batch will hit the commit transaction, regardless of whether the try block fires.

In your second example, I agree with other commenters. Using the success flag is unnecessary.

I consider the following approach to be, essentially, a light weight best practice approach.

If you want to see how it handles an exception, change the value on the second insert from 255 to 256.

CREATE TABLE #TEMP ( ID TINYINT NOT NULL );
INSERT  INTO #TEMP( ID ) VALUES  ( 1 )

BEGIN TRY
    BEGIN TRANSACTION

    INSERT  INTO #TEMP( ID ) VALUES  ( 2 )
    INSERT  INTO #TEMP( ID ) VALUES  ( 255 )

    COMMIT TRANSACTION
END TRY
BEGIN CATCH
    DECLARE 
        @ErrorMessage NVARCHAR(4000),
        @ErrorSeverity INT,
        @ErrorState INT;
    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();
    RAISERROR (
        @ErrorMessage,
        @ErrorSeverity,
        @ErrorState    
        );
    ROLLBACK TRANSACTION
END CATCH

SET NOCOUNT ON

SELECT ID
FROM #TEMP

DROP TABLE #TEMP

jquery $.each() for objects

Basically you need to do two loops here. The one you are doing already is iterating each element in the 0th array element.

You have programs: [ {...}, {...} ] so programs[0] is { "name":"zonealarm", "price":"500" } So your loop is just going over that.

You could do an outer loop over the array

$.each(data.programs, function(index) {

    // then loop over the object elements
    $.each(data.programs[index], function(key, value) {
        console.log(key + ": " + value);
    }

}

using scp in terminal

You can download in the current directory with a . :

cd # by default, goes to $HOME
scp me@host:/path/to/file .

or in you HOME directly with :

scp me@host:/path/to/file ~

Getting last month's date in php

Simply get last month.

Example:

Today is: 2020-09-02

Code:

echo date('Y-m-d', strtotime(date('Y-m-d')." -1 month"));

Result:

2020-08-02

How can I remove an element from a list?

Here is how the remove the last element of a list in R:

x <- list("a", "b", "c", "d", "e")
x[length(x)] <- NULL

If x might be a vector then you would need to create a new object:

x <- c("a", "b", "c", "d", "e")
x <- x[-length(x)]
  • Work for lists and vectors

How to perform a for-each loop over all the files under a specified path?

More compact version working with spaces and newlines in the file name:

find . -iname '*.txt' -exec sh -c 'echo "{}" ; ls -l "{}"' \;

Can you use @Autowired with static fields?

Create a bean which you can autowire which will initialize the static variable as a side effect.

symfony2 : failed to write cache directory

if symfony version less than 2.8

_x000D_
_x000D_
sudo chmod -R 777 app/cache/*
_x000D_
_x000D_
_x000D_

if symfony version great than or equal 3.0

_x000D_
_x000D_
sudo chmod -R 777 var/cache/*
_x000D_
_x000D_
_x000D_

Why won't my PHP app send a 404 error?

If you want the server’s default error page to be displayed, you have to handle this in the server.

HTML5 - mp4 video does not play in IE9

If any of these answers above don't work, and you're on an apache server, adding the following to your .htaccess file:

//most of the common formats, add any that apply
AddType video/mp4 .mp4 
AddType audio/mp4 .m4a
AddType video/mp4 .m4v
AddType video/ogg .ogv 
AddType video/ogg .ogg
AddType video/webm .webm

I had a similar problem and adding this solved all my playback issues.

What does the regex \S mean in JavaScript?

The \s metacharacter matches whitespace characters.

Get ID from URL with jQuery

var url = "http://www.site.com/234234234"
var stuff = url.split('/');
var id = stuff[stuff.length-1];
//id = 234234234

Matplotlib tight_layout() doesn't take into account figure suptitle

I had a similar issue that cropped up when using tight_layout for a very large grid of plots (more than 200 subplots) and rendering in a jupyter notebook. I made a quick solution that always places your suptitle at a certain distance above your top subplot:

import matplotlib.pyplot as plt

n_rows = 50
n_col = 4
fig, axs = plt.subplots(n_rows, n_cols)

#make plots ...

# define y position of suptitle to be ~20% of a row above the top row
y_title_pos = axs[0][0].get_position().get_points()[1][1]+(1/n_rows)*0.2
fig.suptitle('My Sup Title', y=y_title_pos)

For variably-sized subplots, you can still use this method to get the top of the topmost subplot, then manually define an additional amount to add to the suptitle.

How can I develop for iPhone using a Windows development machine?

You may try to develop web apps for iPhone using HTML, JavaScript, CSS. Check the getting started info at Apple's site.

How to find if div with specific id exists in jQuery?

Try to check the length of the selector, if it returns you something then the element must exists else not.

if( $('#selector').length )         // use this if you are using id to check
{
     // it exists
}


if( $('.selector').length )         // use this if you are using class to check
{
     // it exists
}

Use the first if condition for id and the 2nd one for class.

What is the difference between a symbolic link and a hard link?

I would point you to Wikipedia:

A few points:

  • Symlinks, unlike hard links, can cross filesystems (most of the time).
  • Symlinks can point to directories.
  • Hard links point to a file and enable you to refer to the same file with more than one name.
  • As long as there is at least one link, the data is still available.

Type datetime for input parameter in procedure

You should use the ISO-8601 format for string representations of dates - anything else is dependent on the SQL Server language and dateformat settings.

The ISO-8601 format for a DATETIME when using only the date is: YYYYMMDD (no dashes or antyhing!)

For a DATETIME with the time portion, it's YYYY-MM-DDTHH:MM:SS (with dashes, and a T in the middle to separate date and time portions).

If you want to convert a string to a DATE for SQL Server 2008 or newer, you can use YYYY-MM-DD (with the dashes) to achieve the same result. And don't ask me why this is so inconsistent and confusing - it just is, and you'll have to work with that for now.

So in your case, you should try:

declare @a datetime
declare @b datetime 

set @a = '2012-04-06T12:23:45'   -- 6th of April, 2012
set @b = '2012-08-06T21:10:12'   -- 6th of August, 2012

exec LogProcedure 'AccountLog', N'test', @a, @b

Furthermore - your stored proc has problem, since you're concatenating together datetime and string into a string, but you're not converting the datetime to string first, and also, you're forgetting the close quotes in your statement after both dates.

So change this line here to this:

IF @DateFirst <> '' and @DateLast <> ''
   SET @FinalSQL  = @FinalSQL + '  OR CONVERT(Date, DateLog) >= ''' + 
                    CONVERT(VARCHAR(50), @DateFirst, 126) +   -- convert @DateFirst to string for concatenation!
                    ''' AND CONVERT(Date, DateLog) <=''' +  -- you need closing quotes after @DateFirst!
                    CONVERT(VARCHAR(50), @DateLast, 126) + ''''      -- convert @DateLast to string and also: closing tags after that missing!

With these settings, and once you've fixed your stored procedure which contains problems right now, it will work.

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

You add them as libraries to your module.

I usually have a /lib directory in my source. I put all the JARs I need there, add /lib as a library, and make it part of my module dependencies.

2018 update: I'm using IntelliJ 2017/2018 now.

I'm fully committed to Maven and Nexus for dependency management.

This is the way the world has gone. Every open source Java project that I know of uses Maven or Gradle. You should, too.

jQuery - Uncaught RangeError: Maximum call stack size exceeded

your fadeIn() function calls the fadeOut() function, which calls the fadeIn() function again. the recursion is in the JS.

How to run specific test cases in GoogleTest

Summarising @Rasmi Ranjan Nayak and @nogard answers and adding another option:

On the console

You should use the flag --gtest_filter, like

--gtest_filter=Test_Cases1*

(You can also do this in Properties|Configuration Properties|Debugging|Command Arguments)

On the environment

You should set the variable GTEST_FILTER like

export GTEST_FILTER = "Test_Cases1*"

On the code

You should set a flag filter, like

::testing::GTEST_FLAG(filter) = "Test_Cases1*";

such that your main function becomes something like

int main(int argc, char **argv) {
    ::testing::InitGoogleTest(&argc, argv);
    ::testing::GTEST_FLAG(filter) = "Test_Cases1*";
    return RUN_ALL_TESTS();
}

See section Running a Subset of the Tests for more info on the syntax of the string you can use.

Bootstrap Dropdown with Hover

The easiest solution would be in CSS. Add something like...

.dropdown:hover .dropdown-menu {
    display: block;
    margin-top: 0; // remove the gap so it doesn't close
 }

Working Fiddle

How to maintain page scroll position after a jquery event is carried out?

Something to note, when setting the scroll position, make sure you do it in the correct scope. For example, if you're using the scroll position in multiple functions, you would want to set it outside of these functions.

$(document).ready(function() {
    var tempScrollTop = $(window).scrollTop();
    function example() {
        console.log(tempScrollTop);
    };

});

How to clone ArrayList and also clone its contents?

You will need to iterate on the items, and clone them one by one, putting the clones in your result array as you go.

public static List<Dog> cloneList(List<Dog> list) {
    List<Dog> clone = new ArrayList<Dog>(list.size());
    for (Dog item : list) clone.add(item.clone());
    return clone;
}

For that to work, obviously, you will have to get your Dog class to implement the Cloneable interface and override the clone() method.

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

#to get controller name:
<%= controller.controller_name %>
#=> 'users'

#to get action name, it is the method:
<%= controller.action_name %>
#=> 'show'


#to get id information:
<%= ActionController::Routing::Routes.recognize_path(request.url)[:id] %>
#=> '23'

# or display nicely
<%= debug Rails.application.routes.recognize_path(request.url) %>

reference

Messages Using Command prompt in Windows 7

You can use the net send command to send a message over a network.

example:

net send * How Are You

you can use the above statement to send a message to all members of your domain.But if you want to send a message to a single user named Mike, you can use

 net send mike hello!

this will send hello! to the user named Mike.

Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate

For me it was that I was passing a function result as 2-way binding input '=' to a directive that was creating a new object every time.

so I had something like that:

<my-dir>
   <div ng-repeat="entity in entities">
      <some-other-dir entity="myDirCtrl.convertToSomeOtherObject(entity)"></some-other-dir>
   </div>
</my-dir>

and the controller method on my-dir was

this.convertToSomeOtherObject(entity) {
   var obj = new Object();
   obj.id = entity.Id;
   obj.value = entity.Value;
   [..]
   return obj;
}

which when I made to

this.convertToSomeOtherObject(entity) {
   var converted = entity;
   converted.id = entity.Id;
   converted.value = entity.Value;
   [...]
   return converted;
}

solved the problem!

Hopefully this will help someone :)

Change background colour for Visual Studio

Its really simple to customize the background of Visual Studio 2013. Here is it :

  • Tools
  • Options
  • Environment -> General

P.S : Works in Visual Studio 2012 & 2013

enter image description here

Best practices to test protected methods with PHPUnit

I suggest following workaround for "Henrik Paul"'s workaround/idea :)

You know names of private methods of your class. For example they are like _add(), _edit(), _delete() etc.

Hence when you want to test it from aspect of unit-testing, just call private methods by prefixing and/or suffixing some common word (for example _addPhpunit) so that when __call() method is called (since method _addPhpunit() doesn't exist) of owner class, you just put necessary code in __call() method to remove prefixed/suffixed word/s (Phpunit) and then to call that deduced private method from there. This is another good use of magic methods.

Try it out.

How to get current date & time in MySQL?

If you make change default value to CURRENT_TIMESTAMP it is more effiency,

ALTER TABLE servers MODIFY COLUMN network_shares datetime NOT NULL DEFAULT CURRENT_TIMESTAMP;

Call An Asynchronous Javascript Function Synchronously

There is one nice workaround at http://taskjs.org/

It uses generators which are new to javascript. So it's currently not implemented by most browsers. I tested it in firefox, and for me it is nice way to wrap asynchronous function.

Here is example code from project GitHub

var { Deferred } = task;

spawn(function() {
    out.innerHTML = "reading...\n";
    try {
        var d = yield read("read.html");
        alert(d.responseText.length);
    } catch (e) {
        e.stack.split(/\n/).forEach(function(line) { console.log(line) });
        console.log("");
        out.innerHTML = "error: " + e;
    }

});

function read(url, method) {
    method = method || "GET";
    var xhr = new XMLHttpRequest();
    var deferred = new Deferred();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status >= 400) {
                var e = new Error(xhr.statusText);
                e.status = xhr.status;
                deferred.reject(e);
            } else {
                deferred.resolve({
                    responseText: xhr.responseText
                });
            }
        }
    };
    xhr.open(method, url, true);
    xhr.send();
    return deferred.promise;
}

How do you clear a stringstream variable?

You can clear the error state and empty the stringstream all in one line

std::stringstream().swap(m); // swap m with a default constructed stringstream

This effectively resets m to a default constructed state

SQL query question: SELECT ... NOT IN

SELECT MIN(A.maxsal) secondhigh
FROM (
      SELECT TOP 2 MAX(EmployeeBasic) maxsal
      FROM M_Salary
      GROUP BY EmployeeBasic
      ORDER BY EmployeeBasic DESC
     ) A

How do I get my C# program to sleep for 50 msec?

Thread.Sleep(50);

The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.

This method does not perform standard COM and SendMessage pumping. If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.

Thread.Join

How to cherry-pick multiple commits

Another variant worth mentioning is that if you want the last n commits from a branch, the ~ syntax can be useful:

git cherry-pick some-branch~4..some-branch

In this case, the above command would pick the last 4 commits from a branch called some-branch (though you could also use a commit hash in place of a branch name)

How to install and run Typescript locally in npm?

Note if you are using typings do the following:

rm -r typings
typings install

If your doing the angular 2 tutorial use this:

rm -r typings
npm run postinstall
npm start

if the postinstall command dosen't work, try installing typings globally like so:

npm install -g typings

you can also try the following as opposed to postinstall:

typings install

and you should have this issue fixed!

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

If you're open to a PHP solution:

<td><img src='<?PHP
  $path1 = "path/to/your/image.jpg";
  $path2 = "alternate/path/to/another/image.jpg";

  echo file_exists($path1) ? $path1 : $path2; 
  ?>' alt='' />
</td>

////EDIT OK, here's a JS version:

<table><tr>
<td><img src='' id='myImage' /></td>
</tr></table>

<script type='text/javascript'>
  document.getElementById('myImage').src = "newImage.png";

  document.getElementById('myImage').onload = function() { 
    alert("done"); 
  }

  document.getElementById('myImage').onerror = function() { 
    alert("Inserting alternate");
    document.getElementById('myImage').src = "alternate.png"; 
  }
</script>

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

hm.. Did you check replace() ?

Your code will look like this

var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);

How do I get a Date without time in Java?

Here is what I used to get today's date with time set to 00:00:00:

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

Date today = new Date();

Date todayWithZeroTime = formatter.parse(formatter.format(today));

How can I get a precise time, for example in milliseconds in Objective-C?

mach_absolute_time() can be used to get precise measurements.

See http://developer.apple.com/qa/qa2004/qa1398.html

Also available is CACurrentMediaTime(), which is essentially the same thing but with an easier-to-use interface.

(Note: This answer was written in 2009. See Pavel Alexeev's answer for the simpler POSIX clock_gettime() interfaces available in newer versions of macOS and iOS.)

Redirecting to URL in Flask

From the Flask API Documentation (v. 0.10):

flask.redirect(location, code=302, Response=None)

Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers.

New in version 0.6: The location can now be a unicode string that is encoded using the iri_to_uri() function.

Parameters:

  • location – the location the response should redirect to.
  • code – the redirect status code. defaults to 302.
  • Response (class) – a Response class to use when instantiating a response. The default is werkzeug.wrappers.Response if unspecified.

How to insert a value that contains an apostrophe (single quote)?

Another way of escaping the apostrophe is to write a string literal:

insert into Person (First, Last) values (q'[Joe]', q'[O'Brien]')

This is a better approach, because:

  1. Imagine you have an Excel list with 1000's of names you want to upload to your database. You may simply create a formula to generate 1000's of INSERT statements with your cell contents instead of looking manually for apostrophes.

  2. It works for other escape characters too. For example loading a Regex pattern value, i.e. ^( *)(P|N)?( *)|( *)((<|>)\d\d?)?( *)|( )(((?i)(in|not in)(?-i) ?(('[^']+')(, ?'[^']+'))))?( *)$ into a table.

Error - trustAnchors parameter must be non-empty

I got the same error when sending emails, but NOT always. In my case I've changed one line of code to get a new Session object every time:

MimeMessage message = new MimeMessage(Session.getDefaultInstance(props, authenticator));

to

MimeMessage message = new MimeMessage(Session.getInstance(props, authenticator));

Since then sending e-mails works every time.

The error I got:

javax.mail.MessagingException: Could not convert socket to TLS;
nested exception is: javax.net.ssl.SSLException:
java.lang.RuntimeException: Unexpected error:
java.security.InvalidAlgorithmParameterException: the trustAnchors
parameter must be non-empty at
com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:1907) at
com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:666)
at javax.mail.Service.connect(Service.java:317) at
javax.mail.Service.connect(Service.java:176) at
javax.mail.Service.connect(Service.java:125) at
javax.mail.Transport.send0(Transport.java:194) at
javax.mail.Transport.send(Transport.java:124)

Free space in a CMD shell

Is cscript a 3rd party app? I suggest trying Microsoft Scripting, where you can use a programming language (JScript, VBS) to check on things like List Available Disk Space.

The scripting infrastructure is present on all current Windows versions (including 2008).

Swift apply .uppercaseString to only the first letter of a string

If your string is all caps then below method will work

labelTitle.text = remarks?.lowercased().firstUppercased

This extension will helps you

extension StringProtocol {
    var firstUppercased: String {
        guard let first = first else { return "" }
        return String(first).uppercased() + dropFirst()
    }
}

Mock HttpContext.Current in Test Init Method

I know this is an older subject, however Mocking a MVC application for unit tests is something we do on very regular basis.

I just wanted to add my experiences Mocking a MVC 3 application using Moq 4 after upgrading to Visual Studio 2013. None of the unit tests were working in debug mode and the HttpContext was showing "could not evaluate expression" when trying to peek at the variables.

Turns out visual studio 2013 has issues evaluating some objects. To get debugging mocked web applications working again, I had to check the "Use Managed Compatibility Mode" in Tools=>Options=>Debugging=>General settings.

I generally do something like this:

public static class FakeHttpContext
{
    public static void SetFakeContext(this Controller controller)
    {

        var httpContext = MakeFakeContext();
        ControllerContext context =
        new ControllerContext(
        new RequestContext(httpContext,
        new RouteData()), controller);
        controller.ControllerContext = context;
    }


    private static HttpContextBase MakeFakeContext()
    {
        var context = new Mock<HttpContextBase>();
        var request = new Mock<HttpRequestBase>();
        var response = new Mock<HttpResponseBase>();
        var session = new Mock<HttpSessionStateBase>();
        var server = new Mock<HttpServerUtilityBase>();
        var user = new Mock<IPrincipal>();
        var identity = new Mock<IIdentity>();

        context.Setup(c=> c.Request).Returns(request.Object);
        context.Setup(c=> c.Response).Returns(response.Object);
        context.Setup(c=> c.Session).Returns(session.Object);
        context.Setup(c=> c.Server).Returns(server.Object);
        context.Setup(c=> c.User).Returns(user.Object);
        user.Setup(c=> c.Identity).Returns(identity.Object);
        identity.Setup(i => i.IsAuthenticated).Returns(true);
        identity.Setup(i => i.Name).Returns("admin");

        return context.Object;
    }


}

And initiating the context like this

FakeHttpContext.SetFakeContext(moController);

And calling the Method in the controller straight forward

long lReportStatusID = -1;
var result = moController.CancelReport(lReportStatusID);

Read file from resources folder in Spring Boot

if you have for example config folder under Resources folder I tried this Class working perfectly hope be useful

File file = ResourceUtils.getFile("classpath:config/sample.txt")

//Read File Content
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);

Having links relative to root?

To give a URL to an image tag which locates images/ directory in the root like

`logo.png`

you should give src URL starting with / as follows:

<img src="/images/logo.png"/>

This code works in any directories without any troubles even if you are in branches/europe/about.php still the logo can be seen right there.

How to pass a parameter like title, summary and image in a Facebook sharer URL

On the Developers bugs Facebook site, the last answer about that (parameters with sharer.php), makes me believe it was a bug that was going to be resolved. Am I right?

https://developers.facebook.com/x/bugs/357750474364812/

Ibrahim Faour · · Facebook Platform Team

Apologies for the inconvenience. We aim to update our external reports as soon as we get a resolution on issues. I do understand that sometimes the answer provided may not be satisfying, but we are eager to keep our platform as stable and efficient as possible. Thanks!

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

Display QImage with QtGui

Simple, but complete example showing how to display QImage might look like this:

#include <QtGui/QApplication>
#include <QLabel>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QImage myImage;
    myImage.load("test.png");

    QLabel myLabel;
    myLabel.setPixmap(QPixmap::fromImage(myImage));

    myLabel.show();

    return a.exec();
}

Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies

I got this after downgrading a project from .net 4.5 to .net 3.5.

To resolve I had to go in to the project - properties - settings window and delete all my settings, save the project, exit and restart visual studio, go back into project - properties -settings window and re-enter all my settings and their default values

delete map[key] in go?

From Effective Go:

To delete a map entry, use the delete built-in function, whose arguments are the map and the key to be deleted. It's safe to do this even if the key is already absent from the map.

delete(timeZone, "PDT")  // Now on Standard Time

Remove scroll bar track from ScrollView in Android

I'm a little confused why you are putting a WebView into a ScrollView in the first place. A WebView has it's own built-in scrolling system.

Regarding your actual question, if you want the Scrollbar to show up on top, you can use

view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY) or   
android:scrollbarStyle="insideOverlay"

Java Set retain order?

Here is a quick summary of the order characteristics of the standard Set implementations available in Java:

  1. keep the insertion order: LinkedHashSet and CopyOnWriteArraySet (thread-safe)
  2. keep the items sorted within the set: TreeSet, EnumSet (specific to enums) and ConcurrentSkipListSet (thread-safe)
  3. does not keep the items in any specific order: HashSet (the one you tried)

For your specific case, you can either sort the items first and then use any of 1 or 2 (most likely LinkedHashSet or TreeSet). Or alternatively and more efficiently, you can just add unsorted data to a TreeSet which will take care of the sorting automatically for you.

How to append a date in batch files

Building on Joe's idea, here is a version which will build its own (.js) helper and supporting time as well:

@echo off

set _TMP=%TEMP%\_datetime.tmp

echo var date = new Date(), string, tmp;> "%_TMP%"
echo tmp = ^"000^" + date.getFullYear(); string = tmp.substr(tmp.length - 4);>> "%_TMP%"
echo tmp = ^"0^" + (date.getMonth() + 1); string += tmp.substr(tmp.length - 2);>> "%_TMP%"
echo tmp = ^"0^" + date.getDate(); string += tmp.substr(tmp.length - 2);>> "%_TMP%"
echo tmp = ^"0^" + date.getHours(); string += tmp.substr(tmp.length - 2);>> "%_TMP%"
echo tmp = ^"0^" + date.getMinutes(); string += tmp.substr(tmp.length - 2);>> "%_TMP%"
echo tmp = ^"0^" + date.getSeconds(); string += tmp.substr(tmp.length - 2);>> "%_TMP%"
echo WScript.Echo(string);>> "%_TMP%"

for /f %%i in ('cscript //nologo /e:jscript "%_TMP%"') do set _DATETIME=%%i

del "%_TMP%"

echo YYYYMMDDhhmmss: %_DATETIME%
echo YYYY: %_DATETIME:~0,4%
echo YYYYMM: %_DATETIME:~0,6%
echo YYYYMMDD: %_DATETIME:~0,8%
echo hhmm: %_DATETIME:~8,4%
echo hhmmss: %_DATETIME:~8,6%

How can I disable ARC for a single file in a project?

Disable ARC on MULTIPLE files:

  1. Select desired files at Target/Build Phases/Compile Sources in Xcode
  2. PRESS ENTER
  3. Type -fno-objc-arc
  4. Press Enter or Done

;)

enter image description here

How to post SOAP Request from PHP

In my experience, it's not quite that simple. The built-in PHP SOAP client didn't work with the .NET-based SOAP server we had to use. It complained about an invalid schema definition. Even though .NET client worked with that server just fine. By the way, let me claim that SOAP interoperability is a myth.

The next step was NuSOAP. This worked for quite a while. By the way, for God's sake, don't forget to cache WSDL! But even with WSDL cached users complained the damn thing is slow.

Then, we decided to go bare HTTP, assembling the requests and reading the responses with SimpleXMLElemnt, like this:

$request_info = array();

$full_response = @http_post_data(
    'http://example.com/OTA_WS.asmx',
    $REQUEST_BODY,
    array(
        'headers' => array(
            'Content-Type' => 'text/xml; charset=UTF-8',
            'SOAPAction'   => 'HotelAvail',
        ),
        'timeout' => 60,

    ),
    $request_info
);

$response_xml = new SimpleXMLElement(strstr($full_response, '<?xml'));

foreach ($response_xml->xpath('//@HotelName') as $HotelName) {
    echo strval($HotelName) . "\n";
}

Note that in PHP 5.2 you'll need pecl_http, as far as (surprise-surpise!) there's no HTTP client built in.

Going to bare HTTP gained us over 30% in SOAP request times. And from then on we redirect all the performance complains to the server guys.

In the end, I'd recommend this latter approach, and not because of the performance. I think that, in general, in a dynamic language like PHP there's no benefit from all that WSDL/type-control. You don't need a fancy library to read and write XML, with all that stubs generation and dynamic proxies. Your language is already dynamic, and SimpleXMLElement works just fine, and is so easy to use. Also, you'll have less code, which is always good.

Fit image to table cell [Pure HTML]

if you want to do it with pure HTML solution ,you can delete the border in the table if you want...or you can add align="center" attribute to your img tag like this:

<img align="center" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />

see the fiddle : http://jsfiddle.net/Lk2Rh/27/

but still it better to handling this with CSS, i suggest you that.

  • I hope this help.

Adb Devices can't find my phone

I have a Fascinate as well, and had to change the phone's USB communication mode from MODEM to PDA. Use:

  • enter **USBUI (**87284)

to change both USB and UART to PDA mode. I also had to disconnect and reconnect the USB cable. Once Windows re-recognized the device again, "adb devices" started returning my device.

BTW if you use CDMA workshop or the equivalent, you will need to switch the setting back to MODEM.

Maintaining href "open in new tab" with an onClick handler in React

The answer from @gunn is correct, target="_blank makes the link open in a new tab.

But this can be a security risk for you page; you can read about it here. There is a simple solution for that: adding rel="noopener noreferrer".

<a style={{display: "table-cell"}} href = "someLink" target = "_blank" 
rel = "noopener noreferrer">text</a>

jQuery Event : Detect changes to the html/text of a div

Try the MutationObserver:

browser support: http://caniuse.com/#feat=mutationobserver

_x000D_
_x000D_
<html>_x000D_
  <!-- example from Microsoft https://developer.microsoft.com/en-us/microsoft-edge/platform/documentation/dev-guide/dom/mutation-observers/ -->_x000D_
_x000D_
  <head>_x000D_
    </head>_x000D_
  <body>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <script type="text/javascript">_x000D_
      // Inspect the array of MutationRecord objects to identify the nature of the change_x000D_
function mutationObjectCallback(mutationRecordsList) {_x000D_
  console.log("mutationObjectCallback invoked.");_x000D_
_x000D_
  mutationRecordsList.forEach(function(mutationRecord) {_x000D_
    console.log("Type of mutation: " + mutationRecord.type);_x000D_
    if ("attributes" === mutationRecord.type) {_x000D_
      console.log("Old attribute value: " + mutationRecord.oldValue);_x000D_
    }_x000D_
  });_x000D_
}_x000D_
      _x000D_
// Create an observer object and assign a callback function_x000D_
var observerObject = new MutationObserver(mutationObjectCallback);_x000D_
_x000D_
      // the target to watch, this could be #yourUniqueDiv _x000D_
      // we use the body to watch for changes_x000D_
var targetObject = document.body; _x000D_
      _x000D_
// Register the target node to observe and specify which DOM changes to watch_x000D_
      _x000D_
      _x000D_
observerObject.observe(targetObject, { _x000D_
  attributes: true,_x000D_
  attributeFilter: ["id", "dir"],_x000D_
  attributeOldValue: true,_x000D_
  childList: true_x000D_
});_x000D_
_x000D_
// This will invoke the mutationObjectCallback function (but only after all script in this_x000D_
// scope has run). For now, it simply queues a MutationRecord object with the change information_x000D_
targetObject.appendChild(document.createElement('div'));_x000D_
_x000D_
// Now a second MutationRecord object will be added, this time for an attribute change_x000D_
targetObject.dir = 'rtl';_x000D_
_x000D_
_x000D_
      </script>_x000D_
    </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

REST response code for invalid data

If the request could not be correctly parsed (including the request entity/body) the appropriate response is 400 Bad Request [1].

RFC 4918 states that 422 Unprocessable Entity is applicable when the request entity is syntactically well-formed, but semantically erroneous. So if the request entity is garbled (like a bad email format) use 400; but if it just doesn't make sense (like @example.com) use 422.

If the issue is that, as stated in the question, user name/email already exists, you could use 409 Conflict [2] with a description of the conflict, and a hint about how to fix it (in this case, "pick a different user name/email"). However in the spec as written, 403 Forbidden [3] can also be used in this case, arguments about HTTP Authorization notwithstanding.

412 Precondition Failed [4] is used when a precondition request header (e.g. If-Match) that was supplied by the client evaluates to false. That is, the client requested something and supplied preconditions, knowing full well that those preconditions might fail. 412 should never be sprung on the client out of the blue, and shouldn't be related to the request entity per se.

How to Get a Layout Inflater Given a Context?

You can use the static from() method from the LayoutInflater class:

 LayoutInflater li = LayoutInflater.from(context);

Create a circular button in BS3

I had the same problem and came up with a very simple solution working for all (xs, sm, normal and lg) buttons more or less:

.btn-circle {
    border-radius: 50%;
    padding: 0.1em;
    width:1.8em;
}

The difference between the btn-xs and -sm are only their padding. And this is not covered with this snippet. This snippet calculates the sizes based on the font-size only.

Remove rows not .isin('X')

You can use numpy.logical_not to invert the boolean array returned by isin:

In [63]: s = pd.Series(np.arange(10.0))

In [64]: x = range(4, 8)

In [65]: mask = np.logical_not(s.isin(x))

In [66]: s[mask]
Out[66]: 
0    0
1    1
2    2
3    3
8    8
9    9

As given in the comment by Wes McKinney you can also use

s[~s.isin(x)]

How to call a asp:Button OnClick event using JavaScript?

Set style= "display:none;". By setting visible=false, it will not render button in the browser. Thus,client side script wont execute.

<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />

html markup should be

<button id="btnsave" onclick="fncsave()">Save</button>

Change javascript to

<script type="text/javascript">
     function fncsave()
     {
        document.getElementById('<%= savebtn.ClientID %>').click();
     }
</script>

How to vertically align text with icon font?

Add this to your CSS:

.menu i.large.icon,
.menu i.large.basic.icon {
    vertical-align:baseline;
}

DEMO

Difference between `npm start` & `node app.js`, when starting app?

The documentation has been updated. My answer has substantial changes vs the accepted answer: I wanted to reflect documentation is up-to-date, and accepted answer has a few broken links.

Also, I didn't understand when the accepted answer said "it defaults to node server.js". I think the documentation clarifies the default behavior:

npm-start

Start a package

Synopsis

npm start [-- <args>]

Description

This runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.

In summary, running npm start could do one of two things:

  1. npm start {command_name}: Run an arbitrary command (i.e. if such command is specified in the start property of package.json's scripts object)
  2. npm start: Else if no start property exists (or no command_name is passed): Run node server.js, (which may not be appropriate, for example the OP doesn't have server.js; the OP runs nodeapp.js )
  3. I said I would list only 2 items, but are other possibilities (i.e. error cases). For example, if there is no package.json in the directory where you run npm start, you may see an error: npm ERR! enoent ENOENT: no such file or directory, open '.\package.json'

How to shift a column in Pandas DataFrame

Lets define the dataframe from your example by

>>> df = pd.DataFrame([[206, 214], [226, 234], [245, 253], [265, 272], [283, 291]], 
    columns=[1, 2])
>>> df
     1    2
0  206  214
1  226  234
2  245  253
3  265  272
4  283  291

Then you could manipulate the index of the second column by

>>> df[2].index = df[2].index+1

and finally re-combine the single columns

>>> pd.concat([df[1], df[2]], axis=1)
       1      2
0  206.0    NaN
1  226.0  214.0
2  245.0  234.0
3  265.0  253.0
4  283.0  272.0
5    NaN  291.0

Perhaps not fast but simple to read. Consider setting variables for the column names and the actual shift required.

Edit: Generally shifting is possible by df[2].shift(1) as already posted however would that cut-off the carryover.

Java integer to byte array

How about:

public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

The idea is not mine. I've taken it from some post on dzone.com.

How to export data from Spark SQL to CSV

The simplest way is to map over the DataFrame's RDD and use mkString:

  df.rdd.map(x=>x.mkString(","))

As of Spark 1.5 (or even before that) df.map(r=>r.mkString(",")) would do the same if you want CSV escaping you can use apache commons lang for that. e.g. here's the code we're using

 def DfToTextFile(path: String,
                   df: DataFrame,
                   delimiter: String = ",",
                   csvEscape: Boolean = true,
                   partitions: Int = 1,
                   compress: Boolean = true,
                   header: Option[String] = None,
                   maxColumnLength: Option[Int] = None) = {

    def trimColumnLength(c: String) = {
      val col = maxColumnLength match {
        case None => c
        case Some(len: Int) => c.take(len)
      }
      if (csvEscape) StringEscapeUtils.escapeCsv(col) else col
    }
    def rowToString(r: Row) = {
      val st = r.mkString("~-~").replaceAll("[\\p{C}|\\uFFFD]", "") //remove control characters
      st.split("~-~").map(trimColumnLength).mkString(delimiter)
    }

    def addHeader(r: RDD[String]) = {
      val rdd = for (h <- header;
                     if partitions == 1; //headers only supported for single partitions
                     tmpRdd = sc.parallelize(Array(h))) yield tmpRdd.union(r).coalesce(1)
      rdd.getOrElse(r)
    }

    val rdd = df.map(rowToString).repartition(partitions)
    val headerRdd = addHeader(rdd)

    if (compress)
      headerRdd.saveAsTextFile(path, classOf[GzipCodec])
    else
      headerRdd.saveAsTextFile(path)
  }

Which port(s) does XMPP use?

The ports required will be different for your XMPP Server and any XMPP Clients. Most "modern" XMPP Servers follow the defined IANA Ports for Server-to-Server 5269 and for Client-to-Server 5222. Any additional ports depends on what features you enable on the Server, i.e. if you offer BOSH then you may need to open port 80.

File Transfer is highly dependent on both the Clients you use and the Server as to what port it will use, but most of them also negotiate the connect via your existing XMPP Client-to-Server link so the required port opening will be client side (or proxied via port 80.)

AJAX post error : Refused to set unsafe header "Connection"

Remove these two lines:

xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

Assigning variables with dynamic names in Java

You should use List or array instead

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);

Or

int[] arr  = new int[10];
arr[0]=1;
arr[1]=2;

Or even better

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("n1", 1);
map.put("n2", 2);

//conditionally get 
map.get("n1");

How to make HTML input tag only accept numerical values?

One way could be to have an array of allowed character codes and then use the Array.includes function to see if entered character is allowed.

Example:

<input type="text" onkeypress="return [45, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57].includes(event.charCode);"/>

Giving multiple conditions in for loop in Java

You can also replace complicated condition with single method call to make it less evil in maintain.

How can I include css files using node, express, and ejs?

Its simple if you are using express.static(__dirname + 'public') then don't forget to put a forward slash before public that is express.static(__dirname + '/public') or use express.static('public') its also going to work; and don't change anything in CSS linking.

An invalid XML character (Unicode: 0xc) was found

Whenever invalid xml character comes xml, it gives such error. When u open it in notepad++ it look like VT, SOH,FF like these are invalid xml chars. I m using xml version 1.0 and i validate text data before entering it in database by pattern

Pattern p = Pattern.compile("[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD\u10000-\u10FFF]+"); 
retunContent = p.matcher(retunContent).replaceAll("");

It will ensure that no invalid special char will enter in xml

How to make an "alias" for a long path?

First off, you need to remove the quotes:

bashboy@host:~$ myFolder=~/Files/Scripts/Main

The quotes prevent the shell from expanding the tilde to its special meaning of being your $HOME directory.

You could then use $myFolder an environment a shell variable:

bashboy@host:~$ cd $myFolder
bashboy@host:~/Files/Scripts/Main$

To make an alias, you need to define the alias:

alias myfolder="cd $myFolder"

You can then treat this sort of like a command:

bashboy@host:~$ myFolder
bashboy@host:~/Files/Scripts/Main$

How to get the first word of a sentence in PHP?

public function getStringFirstAlphabet($string){
    $data='';
    $string=explode(' ', $string);
    $i=0;
    foreach ($string as $key => $value) {
        $data.=$value[$i];
    }
    return $data;
}

Sum rows in data.frame or matrix

you can use rowSums

rowSums(data) should give you what you want.

How to filter an array/object by checking multiple values

You can use .filter() with boolean operators ie &&:

     var find = my_array.filter(function(result) {
       return result.param1 === "srting1" && result.param2 === 'string2';
     });
     
     return find[0];

What does map(&:name) mean in Ruby?

First, &:name is a shortcut for &:name.to_proc, where :name.to_proc returns a Proc (something that is similar, but not identical to a lambda) that when called with an object as (first) argument, calls the name method on that object.

Second, while & in def foo(&block) ... end converts a block passed to foo to a Proc, it does the opposite when applied to a Proc.

Thus, &:name.to_proc is a block that takes an object as argument and calls the name method on it, i. e. { |o| o.name }.

String to object in JS

Your string looks like a JSON string without the curly braces.

This should work then:

obj = eval('({' + str + '})');

With ng-bind-html-unsafe removed, how do I inject HTML?

For me, the simplest and most flexible solution is:

<div ng-bind-html="to_trusted(preview_data.preview.embed.html)"></div>

And add function to your controller:

$scope.to_trusted = function(html_code) {
    return $sce.trustAsHtml(html_code);
}

Don't forget add $sce to your controller's initialization.

What is the backslash character (\\)?

If double backslash looks weird to you, C# also allows verbatim string literals where the escaping is not required.

Console.WriteLine(@"Mango \ Nightangle");

Don't you just wish Java had something like this ;-)

Nesting CSS classes

Not with pure CSS. The closest equivalent is this:

.class1, .class2 {
    some stuff
}

.class2 {
    some more stuff
}

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

In bash, we use

declare -A name_of_dictonary_variable

so that Bash understands it is a dictionary.

For e.g. you want to create sounds dictionary then,

declare -A sounds

sounds[dog]="Bark"

sounds[wolf]="Howl"

where dog and wolf are "keys", and Bark and Howl are "values".

You can access all values using : echo ${sounds[@]} OR echo ${sounds[*]}

You can access all keys only using: echo ${!sounds[@]}

And if you want any value for a particular key, you can use:

${sounds[dog]}

this will give you value (Bark) for key (Dog).

How can I show and hide elements based on selected option with jQuery?

You're running the code before the DOM is loaded.

Try this:

Live example:

http://jsfiddle.net/FvMYz/

$(function() {    // Makes sure the code contained doesn't run until
                  //     all the DOM elements have loaded

    $('#colorselector').change(function(){
        $('.colors').hide();
        $('#' + $(this).val()).show();
    });

});

Skipping Incompatible Libraries at compile

Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.

So, you need to look to see whether /dvlpmnt/libPI-Http.a is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32 option. Then you need to establish whether there is an alternative libPI-Http.a or libPI-Http.so file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.

To establish what is in that library, you may need to do:

mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk

The 'file' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.

python pandas dataframe to dictionary

Another (slightly shorter) solution for not losing duplicate entries:

>>> ptest = pd.DataFrame([['a',1],['a',2],['b',3]], columns=['id','value'])
>>> ptest
  id  value
0  a      1
1  a      2
2  b      3

>>> pdict = dict()
>>> for i in ptest['id'].unique().tolist():
...     ptest_slice = ptest[ptest['id'] == i]
...     pdict[i] = ptest_slice['value'].tolist()
...

>>> pdict
{'b': [3], 'a': [1, 2]}

Meaning of ${project.basedir} in pom.xml

${project.basedir} is the root directory of your project.

${project.build.directory} is equivalent to ${project.basedir}/target

as it is defined here: https://github.com/apache/maven/blob/trunk/maven-model-builder/src/main/resources/org/apache/maven/model/pom-4.0.0.xml#L53

Download all stock symbol list of a market

Exchanges will usually publish an up-to-date list of securities on their web pages. For example, these pages offer CSV downloads:

NASDAQ Updated their site, so you will have to modify the URLS:

NASDAQ

AMEX

NYSE

Depending on your requirement, you could create the map of these URLs by exchange in your own code.

How to send a stacktrace to log4j?

This answer may be not related to the question asked but related to title of the question.

public class ThrowableTest {

    public static void main(String[] args) {

        Throwable createdBy = new Throwable("Created at main()");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PrintWriter pw = new PrintWriter(os);
        createdBy.printStackTrace(pw);
        try {
            pw.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.debug(os.toString());
    }
}

OR

public static String getStackTrace (Throwable t)
{
    StringWriter stringWriter = new StringWriter();
    PrintWriter  printWriter  = new PrintWriter(stringWriter);
    t.printStackTrace(printWriter);
    printWriter.close();    //surprise no IO exception here
    try {
        stringWriter.close();
    }
    catch (IOException e) {
    }
    return stringWriter.toString();
}

OR

StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
for(StackTraceElement stackTrace: stackTraceElements){
    logger.debug(stackTrace.getClassName()+ "  "+ stackTrace.getMethodName()+" "+stackTrace.getLineNumber());
}

how to align all my li on one line?

Other than white-space:nowrap; also add the following CSS

ul li{
  display: inline;
}

How do I indent multiple lines at once in Notepad++?

in Notepad++v6.1.8 (Unicode) it works after removing the QuickText plugin.

Finding height in Binary Search Tree

class Solution{
    public static int getHeight(Node root) {
        int height = -1;

        if (root == null) {
            return height;
        } else {
            height = 1 + Math.max(getHeight(root.left), getHeight(root.right));
        }

        return height;
    }

How do you force a CIFS connection to unmount

I use lazy unmount: umount -l (that's a lowercase L)

Lazy unmount. Detach the filesystem from the filesystem hierarchy now, and cleanup all references to the filesystem as soon as it is not busy anymore. (Requires kernel 2.4.11 or later.)

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

I have added dataType: 'jsonp' and it works!

$.ajax({
   type: 'POST',
   crossDomain: true,
   dataType: 'jsonp',
   url: '',
   success: function(jsondata){

   }
})

JSONP is a method for sending JSON data without worrying about cross-domain issues. Read More

Add and remove attribute with jquery

First you to add a class then remove id

<script type="text/javascript">
$(document).ready(function(){   
 $("#page_navigation1").addClass("page_navigation");        

 $("#add").click(function(){
        $(".page_navigation").attr("id","page_navigation1");
    });     
    $("#remove").click(function(){
        $(".page_navigation").removeAttr("id");
    });     
  });
</script>

Python: Convert timedelta to int in a dataframe

The Series class has a pandas.Series.dt accessor object with several useful datetime attributes, including dt.days. Access this attribute via:

timedelta_series.dt.days

You can also get the seconds and microseconds attributes in the same way.

Why does GitHub recommend HTTPS over SSH?

Enabling SSH connections over HTTPS if it is blocked by firewall

Test if SSH over the HTTPS port is possible, run this SSH command:

$ ssh -T -p 443 [email protected]
Hi username! You've successfully authenticated, but GitHub does not
provide shell access.

If that worked, great! If not, you may need to follow our troubleshooting guide.

If you are able to SSH into [email protected] over port 443, you can override your SSH settings to force any connection to GitHub to run though that server and port.

To set this in your ssh config, edit the file at ~/.ssh/config, and add this section:

Host github.com
  Hostname ssh.github.com
  Port 443

You can test that this works by connecting once more to GitHub:

$ ssh -T [email protected]
Hi username! You've successfully authenticated, but GitHub does not
provide shell access.

From Authenticating to GitHub / Using SSH over the HTTPS port

Draw horizontal rule in React Native

import {Dimensions} from 'react-native'

const { width, height } = Dimensions.get('window')

<View
  style={{
         borderBottomColor: '#1D3E5E',
         borderBottomWidth: 1,
         width : width , 
  }}
/>

Proper way to rename solution (and directories) in Visual Studio

Using the "Find in Files" function of Notepad++ worked fine for me (ctrl + H, Find in Files).

http://notepad-plus-plus.org/download/v6.2.2.html

Executing JavaScript after X seconds

I believe you are looking for the setTimeout function.

To make your code a little neater, define a separate function for onclick in a <script> block:

function myClick() {
  setTimeout(
    function() {
      document.getElementById('div1').style.display='none';
      document.getElementById('div2').style.display='none';
    }, 5000);
}

then call your function from onclick

onclick="myClick();"

C# equivalent of C++ map<string,double>

Roughly:-

var accounts = new Dictionary<string, double>();

// Initialise to zero...

accounts["Fred"] = 0;
accounts["George"] = 0;
accounts["Fred"] = 0;

// Add cash.
accounts["Fred"] += 4.56;
accounts["George"] += 1.00;
accounts["Fred"] += 1.00;

Console.WriteLine("Fred owes me ${0}", accounts["Fred"]);

How can I call a function using a function pointer?

I usually use typedef to do it, but it may be overkill, if you do not have to use the function pointer too often..

//assuming bool is available (where I come from it is an enum)

typedef bool (*pmyfun_t)();

pmyfun_t pMyFun;

pMyFun=A; //pMyFun=&A is actually same

pMyFun();

Authenticate with GitHub using a token

Automation / Git automation with OAuth tokens

$ git clone https://github.com/username/repo.git
  Username: your_token
  Password:

It also works in the git push command.

Reference: https://help.github.com/articles/git-automation-with-oauth-tokens/

Haskell: Converting Int to String

An example based on Chuck's answer:

myIntToStr :: Int -> String
myIntToStr x
    | x < 3     = show x ++ " is less than three"
    | otherwise = "normal"

Note that without the show the third line will not compile.

How do I pass a string into subprocess.Popen (using the stdin argument)?

p = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)    
p.stdin.write('one\n')
time.sleep(0.5)
p.stdin.write('two\n')
time.sleep(0.5)
p.stdin.write('three\n')
time.sleep(0.5)
testresult = p.communicate()[0]
time.sleep(0.5)
print(testresult)

How to run Visual Studio post-build events for debug build only

This works for me in Visual Studio 2015.

I copy all DLL files from a folder located in a library folder on the same level as my solution folder into the targetdirectory of the project being built.

Using a relative path from my project directory and going up the folder structure two steps with..\..\lib

MySolutionFolder
....MyProject
Lib

if $(ConfigurationName) == Debug (
xcopy /Y "$(ProjectDir)..\..\lib\*.dll" "$(TargetDir)"
) ELSE (echo "Not Debug mode, no file copy from lib")

Calling a user defined function in jQuery

The following is the right method

$(document).ready(function() {
    $('#btnSun').click(function(){
        $(this).myFunction();
     });
     $.fn.myFunction = function() { 
        alert('hi'); 
     }
});

Implement a simple factory pattern with Spring 3 annotations

Based on solution by Pavel Cerný here we can make an universal typed implementation of this pattern. To to it, we need to introduce NamedService interface:

    public interface NamedService {
       String name();
    }

and add abstract class:

public abstract class AbstractFactory<T extends NamedService> {

    private final Map<String, T> map;

    protected AbstractFactory(List<T> list) {
        this.map = list
                .stream()
                .collect(Collectors.toMap(NamedService::name, Function.identity()));
    }

    /**
     * Factory method for getting an appropriate implementation of a service
     * @param name name of service impl.
     * @return concrete service impl.

     */
    public T getInstance(@NonNull final String name) {
        T t = map.get(name);
        if(t == null)
            throw new RuntimeException("Unknown service name: " + name);
        return t;
    }
}

Then we create a concrete factory of specific objects like MyService:

 public interface MyService extends NamedService {
           String name();
           void doJob();
 }

@Component
public class MyServiceFactory extends AbstractFactory<MyService> {

    @Autowired
    protected MyServiceFactory(List<MyService> list) {
        super(list);
    }
}

where List the list of implementations of MyService interface at compile time.

This approach works fine if you have multiple similar factories across app that produce objects by name (if producing objects by a name suffice you business logic of course). Here map works good with String as a key, and holds all the existing implementations of your services.

if you have different logic for producing objects, this additional logic can be moved to some another place and work in combination with these factories (that get objects by name).

How to run Java program in terminal with external library JAR

  1. you can set your classpath in the in the environment variabl CLASSPATH. in linux, you can add like CLASSPATH=.:/full/path/to/the/Jars, for example ..........src/external and just run in side ......src/Report/

Javac Reporter.java

java Reporter

Similarily, you can set it in windows environment variables. for example, in Win7

Right click Start-->Computer then Properties-->Advanced System Setting --> Advanced -->Environment Variables in the user variables, click classPath, and Edit and add the full path of jars at the end. voila

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

I ran into the same situation where when I copied the formula to another cell the formula was still referencing the cell used in the first formula. To correct this when you set up the rules, select the option "use a formula to determine which cells to format. Then type in the box your formula, for example H23*.25. When you copy the cells down the formulas will change to H24*.25, H25*.25 and so on. Hope this helps.

How to run a .jar in mac?

You don't need JDK to run Java based programs. JDK is for development which stands for Java Development Kit.

You need JRE which should be there in Mac.

Try: java -jar Myjar_file.jar

EDIT: According to this article, for Mac OS 10

The Java runtime is no longer installed automatically as part of the OS installation.

Then, you need to install JRE to your machine.

show all tags in git log

git log --no-walk --tags --pretty="%h %d %s" --decorate=full

This version will print the commit message as well:

 $ git log --no-walk --tags --pretty="%h %d %s" --decorate=full
3713f3f  (tag: refs/tags/1.0.0, tag: refs/tags/0.6.0, refs/remotes/origin/master, refs/heads/master) SP-144/ISP-177: Updating the package.json with 0.6.0 version and the README.md.
00a3762  (tag: refs/tags/0.5.0) ISP-144/ISP-205: Update logger to save files with optional port number if defined/passed: Version 0.5.0
d8db998  (tag: refs/tags/0.4.2) ISP-141/ISP-184/ISP-187: Fixing the bug when loading the app with Gulp and Grunt for 0.4.2
3652484  (tag: refs/tags/0.4.1) ISP-141/ISP-184: Missing the package.json and README.md updates with the 0.4.1 version
c55eee7  (tag: refs/tags/0.4.0) ISP-141/ISP-184/ISP-187: Updating the README.md file with the latest 1.3.0 version.
6963d0b  (tag: refs/tags/0.3.0) ISP-141/ISP-184: Add support for custom serializers: README update
4afdbbe  (tag: refs/tags/0.2.0) ISP-141/ISP-143/ISP-144: Fixing a bug with the creation of the logs
e1513f1  (tag: refs/tags/0.1.0) ISP-141/ISP-143: Betterr refactoring of the Loggers, no dependencies, self-configuration for missing settings.

Display calendar to pick a date in java

I found JXDatePicker as a better solution to this. It gives what you need and very easy to use.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jdesktop.swingx.JXDatePicker;

public class DatePickerExample extends JPanel {

    public static void main(String[] args) {
        JFrame frame = new JFrame("JXPicker Example");
        JPanel panel = new JPanel();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(400, 400, 250, 100);

        JXDatePicker picker = new JXDatePicker();
        picker.setDate(Calendar.getInstance().getTime());
        picker.setFormats(new SimpleDateFormat("dd.MM.yyyy"));

        panel.add(picker);
        frame.getContentPane().add(panel);

        frame.setVisible(true);
    }
}

Windows task scheduler error 101 launch failure code 2147943785

I have the same today on Win7.x64, this solve it.

Right Click MyComputer > Manage > Local Users and Groups > Groups > Administrators double click > your name should be there, if not press add...

How to check not in array element

I prefer this

if(in_array($id,$user_access_arr) == false)

respective

if (in_array(search_value, array) == false) 
// value is not in array 

How to Update/Drop a Hive Partition?

You can update a Hive partition by, for example:

ALTER TABLE logs PARTITION(year = 2012, month = 12, day = 18) 
SET LOCATION 'hdfs://user/darcy/logs/2012/12/18';

This command does not move the old data, nor does it delete the old data. It simply sets the partition to the new location.

To drop a partition, you can do

ALTER TABLE logs DROP IF EXISTS PARTITION(year = 2012, month = 12, day = 18);

Hope it helps!

Count how many rows have the same value

SELECT SUM(IF(your_column=3,1,0)) FROM your_table WHERE your_where_contion='something';

e.g. for you query:-

SELECT SUM(IF(num=1,1,0)) FROM your_table_name;

FB OpenGraph og:image not pulling images (possibly https?)

From what I observed, I see that when your website is public and even though the image url is https, it just works fine.

C-like structures in Python

dF: that's pretty cool... I didn't know that I could access the fields in a class using dict.

Mark: the situations that I wish I had this are precisely when I want a tuple but nothing as "heavy" as a dictionary.

You can access the fields of a class using a dictionary because the fields of a class, its methods and all its properties are stored internally using dicts (at least in CPython).

...Which leads us to your second comment. Believing that Python dicts are "heavy" is an extremely non-pythonistic concept. And reading such comments kills my Python Zen. That's not good.

You see, when you declare a class you are actually creating a pretty complex wrapper around a dictionary - so, if anything, you are adding more overhead than by using a simple dictionary. An overhead which, by the way, is meaningless in any case. If you are working on performance critical applications, use C or something.

Service located in another namespace

To access services in two different namespaces you can use url like this:

HTTP://<your-service-name>.<namespace-with-that-service>.svc.cluster.local

To list out all your namespaces you can use:

kubectl get namespace

And for service in that namespace you can simply use:

kubectl get services -n <namespace-name>

this will help you.

Set focus to field in dynamically loaded DIV

$("#header").attr('tabindex', -1).focus();

How can I print message in Makefile?

$(info your_text) : Information. This doesn't stop the execution.

$(warning your_text) : Warning. This shows the text as a warning.

$(error your_text) : Fatal Error. This will stop the execution.

HTTP POST using JSON in Java

For Java 11 you can use new HTTP client:

 HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://localhost/api"))
        .header("Content-Type", "application/json")
        .POST(ofInputStream(() -> getClass().getResourceAsStream(
            "/some-data.json")))
        .build();

    client.sendAsync(request, BodyHandlers.ofString())
        .thenApply(HttpResponse::body)
        .thenAccept(System.out::println)
        .join();

You can use publisher from InputStream, String, File. Converting JSON to the String or IS you can with Jackson.

Attaching a Sass/SCSS to HTML docs

You can not "attach" a SASS/SCSS file to an HTML document.

SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.

There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.

It's as simple as adding 2 lines of code to your HTML file.

<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>

When should I use h:outputLink instead of h:commandLink?

I also see that the page loading (performance) takes a long time on using h:commandLink than h:link. h:link is faster compared to h:commandLink

How to iterate over each string in a list of strings and operate on it's elements

The following code outputs the number of words whose first and last letters are equal. Tested and verified using a python online compiler:

words = ['aba', 'xyz', 'xgx', 'dssd', 'sdjh']  
count = 0  
for i in words:  
     if i[0]==i[-1]:
        count = count + 1  
print(count)  

Output:

$python main.py
3

How to declare global variables in Android?

Like there was discussed above OS could kill the APPLICATION without any notification (there is no onDestroy event) so there is no way to save these global variables.

SharedPreferences could be a solution EXCEPT you have COMPLEX STRUCTURED variables (in my case I had integer array to store the IDs that the user has already handled). The problem with the SharedPreferences is that it is hard to store and retrieve these structures each time the values needed.

In my case I had a background SERVICE so I could move this variables to there and because the service has onDestroy event, I could save those values easily.

how to implement Interfaces in C++?

C++ has no built-in concepts of interfaces. You can implement it using abstract classes which contains only pure virtual functions. Since it allows multiple inheritance, you can inherit this class to create another class which will then contain this interface (I mean, object interface :) ) in it.

An example would be something like this -

class Interface
{
public:
    Interface(){}
    virtual ~Interface(){}
    virtual void method1() = 0;    // "= 0" part makes this method pure virtual, and
                                   // also makes this class abstract.
    virtual void method2() = 0;
};

class Concrete : public Interface
{
private:
    int myMember;

public:
    Concrete(){}
    ~Concrete(){}
    void method1();
    void method2();
};

// Provide implementation for the first method
void Concrete::method1()
{
    // Your implementation
}

// Provide implementation for the second method
void Concrete::method2()
{
    // Your implementation
}

int main(void)
{
    Interface *f = new Concrete();

    f->method1();
    f->method2();

    delete f;

    return 0;
}

VBA copy cells value and format

Following on from jpw it might be good to encapsulate his solution in a small subroutine to save on having lots of lines of code:

Private Sub CommandButton1_Click()
Dim i As Integer
Dim a As Integer
a = 15
For i = 11 To 32
  If Worksheets(1).Cells(i, 3) <> "" Then
    call copValuesAndFormat(i,3,a,15)        
    call copValuesAndFormat(i,5,a,17) 
    call copValuesAndFormat(i,6,a,18) 
    call copValuesAndFormat(i,7,a,19) 
    call copValuesAndFormat(i,8,a,20) 
    call copValuesAndFormat(i,9,a,21) 
    a = a + 1
  End If
Next i
end sub

sub copValuesAndFormat(x1 as integer, y1 as integer, x2 as integer, y2 as integer)
  Worksheets(1).Cells(x1, y1).Copy
  Worksheets(2).Cells(x2, y2).PasteSpecial Paste:=xlPasteFormats
  Worksheets(2).Cells(x2, y2).PasteSpecial Paste:=xlPasteValues
end sub

(I do not have Excel in current location so please excuse bugs as not tested)

How to create loading dialogs in Android?

Today things have changed a little.

Now we avoid use ProgressDialog to show spinning progress:

enter image description here

If you want to put in your app a spinning progress you should use an Activity indicators:

http://developer.android.com/design/building-blocks/progress.html#activity

How can I account for period (AM/PM) using strftime?

The Python time.strftime docs say:

When used with the strptime() function, the %p directive only affects the output hour field if the %I directive is used to parse the hour.

Sure enough, changing your %H to %I makes it work.

Bootstrap - dropdown menu not working?

If you are using electron or other chromium frame, you have to include jquery within window explicitly by:

<script language="javascript" type="text/javascript" src="local_path/jquery.js" onload="window.$ = window.jQuery = module.exports;"></script>

Difference between @Mock and @InjectMocks

@InjectMocks annotation can be used to inject mock fields into a test object automatically.

In below example @InjectMocks has used to inject the mock dataMap into the dataLibrary .

@Mock
Map<String, String> dataMap ;

@InjectMocks
DataLibrary dataLibrary = new DataLibrary();


    @Test
    public void whenUseInjectMocksAnnotation_() {
        Mockito.when(dataMap .get("aData")).thenReturn("aMeaning");

        assertEquals("aMeaning", dataLibrary .getMeaning("aData"));
    }

How to make a boolean variable switch between true and false every time a method is invoked?

Without looking at it, set it to not itself. I don't know how to code it in Java, but in Objective-C I would say

booleanVariable = !booleanVariable;

This flips the variable.

How to use pip on windows behind an authenticating proxy

It took me a couple hours to figure this out but I finally got it to work using CNTLM and afterwards got it to work with just a pip config file. Here is how I got it work with the pip config file...

Solution:

1. In Windows navigate to your user profile directory (Ex. C:\Users\Sync) and create a folder named "pip"

2. Create a file named "pip.ini" in this directory (Ex. C:\Users\Sync\pip\pip.ini) and enter the following into it:

    [global]
    trusted-host = pypi.python.org
                   pypi.org
                   files.pythonhosted.org
    proxy = http://[domain name]%5C[username]:[password]@[proxy address]:[proxy port]

Replace [domain name], [username], [password], [proxy address] and [proxy port] with your own information.

Note, if your [domain name], [username] or [password] has special characters, you have to percent-encode | encode them.

3. At this point I was able to run "pip install" without any issues.

Hopefully this works for others too!

P.S.: This may pose a security concern because of having your password stored in plain text. If this is an issue, consider setting up CNTLM using this article (allows using hashed password instead of plain text). Afterwards set proxy = 127.0.0.1:3128in the "pip.ini" file mentioned above.

How do you tell if a checkbox is selected in Selenium for Java?

For the event where there are multiple check-boxes from which you'd like to select/deselect only a few, the following work with the Chrome Driver (somehow failed for IE Driver):

NOTE: My check-boxes didn't have an ID associated with them, which would be the best way to identify them according to the Documentation. Note the ! sign at the beginning of the statement.

if(!driver.findElement(By.xpath("//input[@type='checkbox' and @name='<name>']")).isSelected()) 
{
  driver.findElement(By.xpath("//input[@type='checkbox' and @name= '<name>']")).click();
}

Wait 5 seconds before executing next line

Here's a solution using the new async/await syntax.

Be sure to check browser support as this is a language feature introduced with ECMAScript 6.

Utility function:

const delay = ms => new Promise(res => setTimeout(res, ms));

Usage:

const yourFunction = async () => {
  await delay(5000);
  console.log("Waited 5s");

  await delay(5000);
  console.log("Waited an additional 5s");
};

The advantage of this approach is that it makes your code look and behave like synchronous code.

Rename file with Git

You can rename a file using git's mv command:

$ git mv file_from file_to

Example:

$ git mv helo.txt hello.txt

$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   renamed:    helo.txt -> hello.txt
#

$ git commit -m "renamed helo.txt to hello.txt"
[master 14c8c4f] renamed helo.txt to hello.txt
 1 files changed, 0 insertions(+), 0 deletions(-)
 rename helo.txt => hello.txt (100%)

Relative path in HTML

The easiest way to solve this in pure HTML is to use the <base href="…"> element like so:

<base href="http://localhost/mywebsite/" />

Then all of the URLs in your HTML can just be this:

<a href="images/example.png">Link To Image</a>

Just change the <base href="…"> to match your server. The rest of the HTML paths will just fall in line and will be appended to that.

git visual diff between branches

If you're using github you can use the website for this:

github.com/url/to/your/repo/compare/SHA_of_tip_of_one_branch...SHA_of_tip_of_another_branch

That will show you a compare of the two.

Why powershell does not run Angular commands?

I solved my problem by running below command

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

How to convert DateTime? to DateTime

Try this:

DateTime UpdatedTime = (DateTime)_objHotelPackageOrder.UpdatedDate == null ? DateTime.Now : _objHotelPackageOrder.UpdatedDate.Value;

SQL Server: convert ((int)year,(int)month,(int)day) to Datetime

SELECT CAST(CAST(year AS varchar) + '/' + CAST(month AS varchar) + '/' + CAST(day as varchar) AS datetime) AS MyDateTime
FROM table

What is the difference between decodeURIComponent and decodeURI?

As I had the same question, but didn't find the answer here, I made some tests in order to figure out what the difference actually is. I did this, since I need the encoding for something, which is not URL/URI related.

  • encodeURIComponent("A") returns "A", it does not encode "A" to "%41"
  • decodeURIComponent("%41") returns "A".
  • encodeURI("A") returns "A", it does not encode "A" to "%41"
  • decodeURI("%41") returns "A".

-That means both can decode alphanumeric characters, even though they did not encode them. However...

  • encodeURIComponent("&") returns "%26".
  • decodeURIComponent("%26") returns "&".
  • encodeURI("&") returns "&".
  • decodeURI("%26") returns "%26".

Even though encodeURIComponent does not encode all characters, decodeURIComponent can decode any value between %00 and %7F.

Note: It appears that if you try to decode a value above %7F (unless it's a unicode value), then your script will fail with an "URI error".

Remove Item from ArrayList

String[] mString = new String[] {"B", "D", "F"};

for (int j = 0; j < mString.length-1; j++) {
        List_Of_Array.remove(mString[j]);
}

How can I create download link in HTML?

i know i am late but this is what i got after 1 hour of search

 <?php 
      $file = 'file.pdf';

    if (! file) {
        die('file not found'); //Or do something 
    } else {
       if(isset($_GET['file'])){  
        // Set headers
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$file");
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: binary");
        // Read the file from disk
        readfile($file); }
    }

    ?>

and for downloadable link i did this

<a href="index.php?file=file.pdf">Download PDF</a>

Docker - Container is not running

For anyone attempting something similar using a Dockerfile...

Running in detached mode won't help. The container will always exit (stop running) if the command is non-blocking, this is the case with bash.

In this case, a workaround would be: 1. Commit the resulting image: (container_name = the name of the container you want to base the image off of, image_name = the name of the image to be created docker commit container_name image_name 2. Use docker run to create a new container using the new image, specifying the command you want to run. Here, I will run "bash": docker run -it image_name bash

This would get you the interactive login you're looking for.

How to ALTER multiple columns at once in SQL Server

This is not possible. You will need to do this one by one. You could:

  1. Create a Temporary Table with your modified columns in
  2. Copy the data across
  3. Drop your original table (Double check before!)
  4. Rename your Temporary Table to your original name

reStructuredText tool support

Salvaging (and extending) the list from an old version of the Wikipedia page:

Documentation

Implementations

Although the reference implementation of reStructuredText is written in Python, there are reStructuredText parsers in other languages too.

Python - Docutils

The main distribution of reStructuredText is the Python Docutils package. It contains several conversion tools:

  • rst2html - from reStructuredText to HTML
  • rst2xml - from reStructuredText to XML
  • rst2latex - from reStructuredText to LaTeX
  • rst2odt - from reStructuredText to ODF Text (word processor) document.
  • rst2s5 - from reStructuredText to S5, a Simple Standards-based Slide Show System
  • rst2man - from reStructuredText to Man page

Haskell - Pandoc

Pandoc is a Haskell library for converting from one markup format to another, and a command-line tool that uses this library. It can read Markdown and (subsets of) reStructuredText, HTML, and LaTeX, and it can write Markdown, reStructuredText, HTML, LaTeX, ConTeXt, PDF, RTF, DocBook XML, OpenDocument XML, ODT, GNU Texinfo, MediaWiki markup, groff man pages, and S5 HTML slide shows.

There is an Pandoc online tool (POT) to try this library. Unfortunately, compared to the reStructuredText online renderer (ROR),

  • POT truncates input rather more shortly. The POT user must render input in chunks that could be rendered whole by the ROR.
  • POT output lacks the helpful error messages displayed by the ROR (and generated by docutils)

Java - JRst

JRst is a Java reStructuredText parser. It can currently output HTML, XHTML, DocBook xdoc and PDF, BUT seems to have serious problems: neither PDF or (X)HTML generation works using the current full download, result pages in (X)HTML are empty and PDF generation fails on IO problems with XSL files (not bundled??). Note that the original JRst has been removed from the website; a fork is found on GitHub.

Scala - Laika

Laika is a new library for transforming markup languages to other output formats. Currently it supports input from Markdown and reStructuredText and produce HTML output. The library is written in Scala but should be also usable from Java.

Perl

PHP

C#/.NET

Nim/C

The Nim compiler features the commands rst2htmland rst2tex which transform reStructuredText files to HTML and TeX files. The standard library provides the following modules (used by the compiler) to handle reStructuredText files programmatically:

  • rst - implements a reStructuredText parser
  • rstast - implements an AST for the reStructuredText parser
  • rstgen - implements a generator of HTML/Latex from reStructuredText

Other 3rd party converters

Most (but not all) of these tools are based on Docutils (see above) and provide conversion to or from formats that might not be supported by the main distribution.

From reStructuredText

  • restview - This pip-installable python package requires docutils, which does the actual rendering. restview's major ease-of-use feature is that, when you save changes to your document(s), it automagically re-renders and re-displays them. restview
    1. starts a small web server
    2. calls docutils to render your document(s) to HTML
    3. calls your device's browser to display the output HTML.
  • rst2pdf - from reStructuredText to PDF
  • rst2odp - from reStructuredText to ODF Presentation
  • rst2beamer - from reStructuredText to LaTeX beamer Presentation class
  • Wikir - from reStructuredText to a Google (and possibly other) Wiki formats
  • rst2qhc - Convert a collection of reStructuredText files into a Qt (toolkit) Help file and (optional) a Qt Help Project file

To reStructuredText

  • xml2rst is an XSLT script to convert Docutils internal XML representation (back) to reStructuredText
  • Pandoc (see above) can also convert from Markdown, HTML and LaTeX to reStructuredText
  • db2rst is a simple and limited DocBook to reStructuredText translator
  • pod2rst - convert .pod files to reStructuredText files

Extensions

Some projects use reStructuredText as a baseline to build on, or provide extra functionality extending the utility of the reStructuredText tools.

Sphinx

The Sphinx documentation generator translates a set of reStructuredText source files into various output formats, automatically producing cross-references, indices etc.

rest2web

rest2web is a simple tool that lets you build your website from a single template (or as many as you want), and keep the contents in reStructuredText.

Pygments

Pygments is a generic syntax highlighter for general use in all kinds of software such as forum systems, Wikis or other applications that need to prettify source code. See Using Pygments in reStructuredText documents.

Free Editors

While any plain text editor is suitable to write reStructuredText documents, some editors have better support than others.

Emacs

The Emacs support via rst-mode comes as part of the Docutils package under /docutils/tools/editors/emacs/rst.el

Vim

The vim-common package for that comes with most GNU/Linux distributions has reStructuredText syntax highlight and indentation support of reStructuredText out of the box:

Jed

There is a rst mode for the Jed programmers editor.

gedit

gedit, the official text editor of the GNOME desktop environment. There is a gedit reStructuredText plugin.

Geany

Geany, a small and lightweight Integrated Development Environment include support for reStructuredText from version 0.12 (October 10, 2007).

Leo

Leo, an outlining editor for programmers, supports reStructuredText via rst-plugin or via "@auto-rst" nodes (it's not well-documented, but @auto-rst nodes allow editing rst files directly, parsing the structure into the Leo outline).

It also provides a way to preview the resulting HTML, in a "viewrendered" pane.

FTE

The FTE Folding Text Editor - a free (licensed under the GNU GPL) text editor for developers. FTE has a mode for reStructuredText support. It provides color highlighting of basic RSTX elements and special menu that provide easy way to insert most popular RSTX elements to a document.

PyK

PyK is a successor of PyEdit and reStInPeace, written in Python with the help of the Qt4 toolkit.

Eclipse

The Eclipse IDE with the ReST Editor plug-in provides support for editing reStructuredText files.

NoTex

NoTex is a browser based (general purpose) text editor, with integrated project management and syntax highlighting. Plus it enables to write books, reports, articles etc. using rST and convert them to LaTex, PDF or HTML. The PDF files are of high publication quality and are produced via Sphinx with the Texlive LaTex suite.

Notepad++

Notepad++ is a general purpose text editor for Windows. It has syntax highlighting for many languages built-in and support for reStructuredText via a user defined language for reStructuredText.

Visual Studio Code

Visual Studio Code is a general purpose text editor for Windows/macOS/Linux. It has syntax highlighting for many languages built-in and supports reStructuredText via an extension from LeXtudio.

Dedicated reStructuredText Editors

Proprietary editors

Sublime Text

Sublime Text is a completely customizable and extensible source code editor available for Windows, OS X, and Linux. Registration is required for long-term use, but all functions are available in the unregistered version, with occasional reminders to purchase a license. Versions 2 and 3 (currently in beta) support reStructuredText syntax highlighting by default, and several plugins are available through the package manager Package Control to provide snippets and code completion, additional syntax highlighting, conversion to/from RST and other formats, and HTML preview in the browser.

BBEdit / TextWrangler

BBEdit (and its free variant TextWrangler) for Mac can syntax-highlight reStructuredText using this codeless language module.

TextMate

TextMate, a proprietary general-purpose GUI text editor for Mac OS X, has a bundle for reStructuredText.

Intype

Intype is a proprietary text editor for Windows, that support reStructuredText out of the box.

E Text Editor

E is a proprietary Text Editor licensed under the "Open Company License". It supports TextMate's bundles, so it should support reStructuredText the same way TextMate does.

PyCharm

PyCharm (and other IntelliJ platform IDEs?) has ReST/Sphinx support (syntax highlighting, autocomplete and preview).instant preview)

Wiki

here are some Wiki programs that support the reStructuredText markup as the native markup syntax, or as an add-on:

MediaWiki

MediaWiki reStructuredText extension allows for reStructuredText markup in MediaWiki surrounded by <rst> and </rst>.

MoinMoin

MoinMoin is an advanced, easy to use and extensible WikiEngine with a large community of users. Said in a few words, it is about collaboration on easily editable web pages.

There is a reStructuredText Parser for MoinMoin.

Trac

Trac is an enhanced wiki and issue tracking system for software development projects. There is a reStructuredText Support in Trac.

This Wiki

This Wiki is a Webware for Python Wiki written by Ian Bicking. This wiki uses ReStructuredText for its markup.

rstiki

rstiki is a minimalist single-file personal wiki using reStructuredText syntax (via docutils) inspired by pwyky. It does not support authorship indication, versioning, hierarchy, chrome/framing/templating or styling. It leverages docutils/reStructuredText as the wiki syntax. As such, it's under 200 lines of code, and in a single file. You put it in a directory and it runs.

ikiwiki

Ikiwiki is a wiki compiler. It converts wiki pages into HTML pages suitable for publishing on a website. Ikiwiki stores pages and history in a revision control system such as Subversion or Git. There are many other features, including support for blogging, as well as a large array of plugins. It's reStructuredText plugin, however is somewhat limited and is not recommended as its' main markup language at this time.

Web Services

Sandbox

An Online reStructuredText editor can be used to play with the markup and see the results immediately.

Blogging frameworks

WordPress

WordPreSt reStructuredText plugin for WordPress. (PHP)

Zine

reStructuredText parser plugin for Zine (will become obsolete in version 0.2 when Zine is scheduled to get a native reStructuredText support). Zine is discontinued. (Python)

pelican

Pelican is a static blog generator that supports writing articles in ReST. (Python)

hyde

Hyde is a static website generator that supports ReST. (Python)

Acrylamid

Acrylamid is a static blog generator that supports writing articles in ReST. (Python)

Nikola

Nikola is a Static Site and Blog Generator that supports ReST. (Python)

ipsum genera

Ipsum genera is a static blog generator written in Nim.

Yozuch

Yozuch is a static blog generator written in Python.

More

Select by partial string from a pandas DataFrame

A more generalised example - if looking for parts of a word OR specific words in a string:

df = pd.DataFrame([('cat andhat', 1000.0), ('hat', 2000000.0), ('the small dog', 1000.0), ('fog', 330000.0),('pet', 330000.0)], columns=['col1', 'col2'])

Specific parts of sentence or word:

searchfor = '.*cat.*hat.*|.*the.*dog.*'

Creat column showing the affected rows (can always filter out as necessary)

df["TrueFalse"]=df['col1'].str.contains(searchfor, regex=True)

    col1             col2           TrueFalse
0   cat andhat       1000.0         True
1   hat              2000000.0      False
2   the small dog    1000.0         True
3   fog              330000.0       False
4   pet 3            30000.0        False

How to check if an element is off-screen

There's a jQuery plugin here which allows users to test whether an element falls within the visible viewport of the browser, taking the browsers scroll position into account.

$('#element').visible();

You can also check for partial visibility:

$('#element').visible( true);

One drawback is that it only works with vertical positioning / scrolling, although it should be easy enough to add horizontal positioning into the mix.

How to iterate a loop with index and element in Swift

Using .enumerate() works, but it does not provide the true index of the element; it only provides an Int beginning with 0 and incrementing by 1 for each successive element. This is usually irrelevant, but there is the potential for unexpected behavior when used with the ArraySlice type. Take the following code:

let a = ["a", "b", "c", "d", "e"]
a.indices //=> 0..<5

let aSlice = a[1..<4] //=> ArraySlice with ["b", "c", "d"]
aSlice.indices //=> 1..<4

var test = [Int: String]()
for (index, element) in aSlice.enumerate() {
    test[index] = element
}
test //=> [0: "b", 1: "c", 2: "d"] // indices presented as 0..<3, but they are actually 1..<4
test[0] == aSlice[0] // ERROR: out of bounds

It's a somewhat contrived example, and it's not a common issue in practice but still I think it's worth knowing this can happen.

What is the 'realtime' process priority setting for?

Real-time is the highest priority class available to a process. Therefore, it is different from 'High' in that it's one step greater, and 'Above Normal' in that it's two steps greater.

Similarly, real-time is also a thread priority level.

The process priority class raises or lowers all effective thread priorities in the process and is therefore considered the 'base priority'.

So, a process has a:

  1. Base process priority class.
  2. Individual thread priorities, offsets of the base priority class.

Since real-time is supposed to be reserved for applications that absolutely must pre-empt other running processes, there is a special security privilege to protect against haphazard use of it. This is defined by the security policy.

In NT6+ (Vista+), use of the Vista Multimedia Class Scheduler is the proper way to achieve real-time operations in what is not a real-time OS. It works, for the most part, though is not perfect since the OS isn't designed for real-time operations.

Microsoft considers this priority very dangerous, rightly so. No application should use it except in very specialized circumstances, and even then try to limit its use to temporary needs.

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

After doing some reading and taking into account the (many..) different ways of splitting the data to train and test, I decided to timeit!

I used 4 different methods (non of them are using the library sklearn, which I'm sure will give the best results, giving that it is well designed and tested code):

  1. shuffle the whole matrix arr and then split the data to train and test
  2. shuffle the indices and then assign it x and y to split the data
  3. same as method 2, but in a more efficient way to do it
  4. using pandas dataframe to split

method 3 won by far with the shortest time, after that method 1, and method 2 and 4 discovered to be really inefficient.

The code for the 4 different methods I timed:

import numpy as np
arr = np.random.rand(100, 3)
X = arr[:,:2]
Y = arr[:,2]
spl = 0.7
N = len(arr)
sample = int(spl*N)

#%% Method 1:  shuffle the whole matrix arr and then split
np.random.shuffle(arr)
x_train, x_test, y_train, y_test = X[:sample,:], X[sample:, :], Y[:sample, ], Y[sample:,]

#%% Method 2: shuffle the indecies and then shuffle and apply to X and Y
train_idx = np.random.choice(N, sample)
Xtrain = X[train_idx]
Ytrain = Y[train_idx]

test_idx = [idx for idx in range(N) if idx not in train_idx]
Xtest = X[test_idx]
Ytest = Y[test_idx]

#%% Method 3: shuffle indicies without a for loop
idx = np.random.permutation(arr.shape[0])  # can also use random.shuffle
train_idx, test_idx = idx[:sample], idx[sample:]
x_train, x_test, y_train, y_test = X[train_idx,:], X[test_idx,:], Y[train_idx,], Y[test_idx,]

#%% Method 4: using pandas dataframe to split
import pandas as pd
df = pd.read_csv(file_path, header=None) # Some csv file (I used some file with 3 columns)

train = df.sample(frac=0.7, random_state=200)
test = df.drop(train.index)

And for the times, the minimum time to execute out of 3 repetitions of 1000 loops is:

  • Method 1: 0.35883826200006297 seconds
  • Method 2: 1.7157016959999964 seconds
  • Method 3: 1.7876616719995582 seconds
  • Method 4: 0.07562861499991413 seconds

I hope that's helpful!

How to remove .html from URL?

You will need to make sure you have Options -MultiViews as well.

None of the above worked for me on a standard cPanel host.

This worked:

Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]

How can I merge properties of two JavaScript objects dynamically?

I've used Object.create() to keep the default settings (utilising __proto__ or Object.getPrototypeOf() ).

function myPlugin( settings ){
    var defaults = {
        "keyName": [ "string 1", "string 2" ]
    }
    var options = Object.create( defaults );
    for (var key in settings) { options[key] = settings[key]; }
}
myPlugin( { "keyName": ["string 3", "string 4" ] } );

This way I can always 'concat()' or 'push()' later.

var newArray = options['keyName'].concat( options.__proto__['keyName'] );

Note: You'll need to do a hasOwnProperty check before concatenation to avoid duplication.

How to prevent sticky hover effects for buttons on touch devices

With Modernizr you can target your hovers specifically for no-touch devices:

(Note: this doesn't run on StackOverflow's snippet system, check the jsfiddle instead)

/* this one is sticky */
#regular:hover, #regular:active {
  opacity: 0.5;
}

/* this one isn't */
html.no-touch #no-touch:hover, #no-touch:active {
  opacity: 0.5;
}

Note that :active doesn't need to be targeted with .no-touch because it works as expected on both mobile and desktop.

How to show row number in Access query like ROW_NUMBER in SQL

by VB function:

Dim m_RowNr(3) as Variant
'
Function RowNr(ByVal strQName As String, ByVal vUniqValue) As Long
' m_RowNr(3)
' 0 - Nr
' 1 - Query Name
' 2 - last date_time
' 3 - UniqValue

If Not m_RowNr(1) = strQName Then
  m_RowNr(0) = 1
  m_RowNr(1) = strQName
ElseIf DateDiff("s", m_RowNr(2), Now) > 9 Then
  m_RowNr(0) = 1
ElseIf Not m_RowNr(3) = vUniqValue Then
  m_RowNr(0) = m_RowNr(0) + 1
End If

m_RowNr(2) = Now
m_RowNr(3) = vUniqValue
RowNr = m_RowNr(0)

End Function

Usage(without sorting option):

SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
From table A
Order By A.id

if sorting required or multiple tables join then create intermediate table:

 SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
 INTO table_with_Nr
 From table A
 Order By A.id

How to add "on delete cascade" constraints?

Usage:

select replace_foreign_key('user_rates_posts', 'post_id', 'ON DELETE CASCADE');

Function:

CREATE OR REPLACE FUNCTION 
    replace_foreign_key(f_table VARCHAR, f_column VARCHAR, new_options VARCHAR) 
RETURNS VARCHAR
AS $$
DECLARE constraint_name varchar;
DECLARE reftable varchar;
DECLARE refcolumn varchar;
BEGIN

SELECT tc.constraint_name, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' 
   AND tc.table_name= f_table AND kcu.column_name= f_column
INTO constraint_name, reftable, refcolumn;

EXECUTE 'alter table ' || f_table || ' drop constraint ' || constraint_name || 
', ADD CONSTRAINT ' || constraint_name || ' FOREIGN KEY (' || f_column || ') ' ||
' REFERENCES ' || reftable || '(' || refcolumn || ') ' || new_options || ';';

RETURN 'Constraint replaced: ' || constraint_name || ' (' || f_table || '.' || f_column ||
 ' -> ' || reftable || '.' || refcolumn || '); New options: ' || new_options;

END;
$$ LANGUAGE plpgsql;

Be aware: this function won't copy attributes of initial foreign key. It only takes foreign table name / column name, drops current key and replaces with new one.

Class name does not name a type in C++

error 'Class' does not name a type

Just in case someone does the same idiotic thing I did ... I was creating a small test program from scratch and I typed Class instead of class (with a small C). I didn't take any notice of the quotes in the error message and spent a little too long not understanding my problem.

My search for a solution brought me here so I guess the same could happen to someone else.

How to use opencv in using Gradle?

Since the integration of OpenCV is such an effort, we pre-packaged it and published it via JCenter here: https://github.com/quickbirdstudios/opencv-android

Just include this in your module's build.gradle dependencies section

dependencies {
  implementation 'com.quickbirdstudios:opencv:3.4.1'
}

and this in your project's build.gradle repositories section

repositories {
  jcenter()
}

You won't get lint error after gradle import but don't forget to initialize the OpenCV library like this in MainActivity

public class MainActivity extends Activity {
    static {
        if (!OpenCVLoader.initDebug())
            Log.d("ERROR", "Unable to load OpenCV");
        else
            Log.d("SUCCESS", "OpenCV loaded");
    }
...
...
...
...

Disable click outside of bootstrap modal area to close modal

You can Disallow closing of #signUp (This should be the id of the modal) modal when clicking outside of modal.
As well as on ESC button.
jQuery('#signUp').on('shown.bs.modal', function() {
    jQuery(this).data('bs.modal').options.backdrop = 'static';// For outside click of modal.
    jQuery(this).data('bs.modal').options.keyboard = false;// For ESC button.
})

Upload file to SFTP using PowerShell

There isn't currently a built-in PowerShell method for doing the SFTP part. You'll have to use something like psftp.exe or a PowerShell module like Posh-SSH.

Here is an example using Posh-SSH:

# Set the credentials
$Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('root', $Password)

# Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\FileDump\test.txt"
$SftpPath = '/Outbox'
$SmbPath = '\\filer01\Backup'

# Set the IP of the SFTP server
$SftpIp = '10.209.26.105'

# Load the Posh-SSH module
Import-Module C:\Temp\Posh-SSH

# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential

# Upload the file to the SFTP path
Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath

#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }

# Copy the file to the SMB location
Copy-Item -Path $FilePath -Destination $SmbPath

Some additional notes:

  • You'll have to download the Posh-SSH module which you can install to your user module directory (e.g. C:\Users\jon_dechiro\Documents\WindowsPowerShell\Modules) and just load using the name or put it anywhere and load it like I have in the code above.
  • If having the credentials in the script is not acceptable you'll have to use a credential file. If you need help with that I can update with some details or point you to some links.
  • Change the paths, IPs, etc. as needed.

That should give you a decent starting point.

SQL DELETE with INNER JOIN

Add .* to s in your first line.

Try:

DELETE s.* FROM spawnlist s
INNER JOIN npc n ON s.npc_templateid = n.idTemplate
WHERE (n.type = "monster");

How to delete specific rows and columns from a matrix in a smarter way?

You can use

t1<- t1[-4:-6,-7:-9]  

or

t1 <- t1[-(4:6), -(7:9)]

or

t1 <- t1[-c(4, 5, 6), -c(7, 8, 9)]

You can pass vectors to select rows/columns to be deleted. First two methods are useful if you are trying to delete contiguous rows/columns. Third method is useful if You are trying to delete discrete rows/columns.

> t1 <- array(1:20, dim=c(10,10));

> t1[-c(1, 4, 6, 7, 9), -c(2, 3, 8, 9)]

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    2   12    2   12    2   12
[2,]    3   13    3   13    3   13
[3,]    5   15    5   15    5   15
[4,]    8   18    8   18    8   18
[5,]   10   20   10   20   10   20

How to check if two words are anagrams

Some other solution without sorting.

public static boolean isAnagram(String s1, String s2){
    //case insensitive anagram

    StringBuffer sb = new StringBuffer(s2.toLowerCase());
    for (char c: s1.toLowerCase().toCharArray()){
        if (Character.isLetter(c)){

            int index = sb.indexOf(String.valueOf(c));
            if (index == -1){
                //char does not exist in other s2
                return false;
            }
            sb.deleteCharAt(index);
        }
    }
    for (char c: sb.toString().toCharArray()){
        //only allow whitespace as left overs
        if (!Character.isWhitespace(c)){
            return false;
        }
    }
    return true;
}

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

ROWS UNBOUNDED PRECEDING is no Teradata-specific syntax, it's Standard SQL. Together with the ORDER BY it defines the window on which the result is calculated.

Logically a Windowed Aggregate Function is newly calculated for each row within the PARTITION based on all ROWS between a starting row and an ending row.

Starting and ending rows might be fixed or relative to the current row based on the following keywords:

  • CURRENT ROW, the current row
  • UNBOUNDED PRECEDING, all rows before the current row -> fixed
  • UNBOUNDED FOLLOWING, all rows after the current row -> fixed
  • x PRECEDING, x rows before the current row -> relative
  • y FOLLOWING, y rows after the current row -> relative

Possible kinds of calculation include:

  • Both starting and ending row are fixed, the window consists of all rows of a partition, e.g. a Group Sum, i.e. aggregate plus detail rows
  • One end is fixed, the other relative to current row, the number of rows increases or decreases, e.g. a Running Total, Remaining Sum
  • Starting and ending row are relative to current row, the number of rows within a window is fixed, e.g. a Moving Average over n rows

So SUM(x) OVER (ORDER BY col ROWS UNBOUNDED PRECEDING) results in a Cumulative Sum or Running Total

11 -> 11
 2 -> 11 +  2                = 13
 3 -> 13 +  3 (or 11+2+3)    = 16
44 -> 16 + 44 (or 11+2+3+44) = 60

How to convert a column of DataTable to a List

var list = dataTable.Rows.OfType<DataRow>()
    .Select(dr => dr.Field<string>(columnName)).ToList();

[Edit: Add a reference to System.Data.DataSetExtensions to your project if this does not compile]

Difference between web reference and service reference?

Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)

They are designed to work with WCF.

If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP

"No backupset selected to be restored" SQL Server 2012

I had the same issue with SQL Server 2014 (Management Studio could not see the folder in which the backup file resided, when attempting to locate it for a Restore operation). This thread held the answer that solved my problem. Quote:

The SQL Server service account can be found by Start->Control Panel->Administrative Tools->Services. Double-click on the SQL Server service->Log On tab. You'll either be using the "Local System account" or "This account" to define a specific account. If you are using the Local System account, you won't be able to reference backups that are not local to the server. If, instead, you have defined the account to use, this is the account that needs to have access to the backup file location. Your ability to access the backups using your personal logon is irrelevant; it is the SQL Server account that is used, even though you are initiating the backup. Your IT people should be able to determine what rights are granted to each account.

Hope that helps someone.

How to hide only the Close (x) button?

Well you can hide the close button by changing the FormBorderStyle from the properties section or programmatically in the constructor using:

public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
}

then you create a menu strip item to exit the application.

cheers

Dependent DLL is not getting copied to the build output folder in Visual Studio

Not sure if this helps but for me, many times I reference a DLL (which automatically adds it to the bin folder of course). However that DLL might need additional DLLs (depending on what functions I'm using). I do NOT want to reference those in my Project because they just simply need to end up in the same folder as the DLL I am actually using.

I accomplish this in Visual Studio by "Adding an existing file". You should be able to add it anywhere except the Add_data folder. personally I just add it to the root.

Then change the properties of that file to ...

Build Action = None (having this set to something like Content actually copies the "root" version to the root, plus a copy in the Bin).

Copy to output folder = Copy if Newer (Basically puts it in the BIN folder only if it is missing, but doesn't do it after that)

When I publish.. my added DLL's only exists in the BIN folder and nowhere else in the Publish location (which is what I want).

Get File Path (ends with folder)

Use the Application.FileDialog object

Sub SelectFolder()
    Dim diaFolder As FileDialog
    Dim selected As Boolean

    ' Open the file dialog
    Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
    diaFolder.AllowMultiSelect = False
    selected = diaFolder.Show

    If selected Then
        MsgBox diaFolder.SelectedItems(1)
    End If

    Set diaFolder = Nothing
End Sub

Determine if an element has a CSS class with jQuery

from the FAQ

elem = $("#elemid");
if (elem.is (".class")) {
   // whatever
}

or:

elem = $("#elemid");
if (elem.hasClass ("class")) {
   // whatever
}

working with negative numbers in python

The abs() in the while condition is needed, since, well, it controls the number of iterations (how would you define a negative number of iterations?). You can correct it by inverting the sign of the result if numb is negative.

So this is the modified version of your code. Note I replaced the while loop with a cleaner for loop.

#get user input of numbers as variables
numa, numb = input("please give 2 numbers to multiply seperated with a comma:")

#standing variables
total = 0

#output the total
for count in range(abs(numb)):
    total += numa

if numb < 0:
    total = -total

print total

Upgrade to python 3.8 using conda

Update for 2020/07

Finally, Anaconda3-2020.07 is out and its core is Python 3.8!

You can now download Anaconda packed with Python 3.8 goodness at:

Which encoding opens CSV files correctly with Excel on both Mac and Windows?

instead of csv, trying outputting html with an XLS extension and "application/excel" mime-type. I know this will work in Windows, but can't speak for MacOS

Set position / size of UI element as percentage of screen size

The above problem can also be solved using ConstraintLayout through Guidelines.

Below is the snippet.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.constraint.Guideline
    android:id="@+id/upperGuideLine"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.68" />

<Gallery
    android:id="@+id/gallery"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@+id/lowerGuideLine"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@+id/upperGuideLine" />

<android.support.constraint.Guideline
    android:id="@+id/lowerGuideLine"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    app:layout_constraintGuide_percent="0.84" />

</android.support.constraint.ConstraintLayout>

How to find the operating system version using JavaScript?

Hey for a quick solution you can consider the following library : UAPARSER - https://www.npmjs.com/package/ua-parser-js

example :

<script type="text/javascript" src="ua-parser.min.js"></script>
<script type="text/javascript">

var parser = new UAParser();
console.log(parser.getOS()) // will log  {name: "", version:""}

you can also install the library via npm, and import it like this:

import { UAParser } from 'ua-parser-js';
let parser = new UAParser();
parser.getOS();

the library is a JS based user agent string parser (window.navigator.userAgent is the user agent on browser) , so you can get with it other details aswell such as Browser,device,engines etc..and it can work with node js as well.

if you need typing for the library : https://www.npmjs.com/package/@types/ua-parser-js

How to make a hyperlink in telegram without using bots?

First make link with @bold bot . Then Copy text and paste it to remove "via @bold"

Entity Framework Code First - two Foreign Keys from same table

InverseProperty in EF Core makes the solution easy and clean.

InverseProperty

So the desired solution would be:

public class Team
{
    [Key]
    public int TeamId { get; set;} 
    public string Name { get; set; }

    [InverseProperty(nameof(Match.HomeTeam))]
    public ICollection<Match> HomeMatches{ get; set; }

    [InverseProperty(nameof(Match.GuestTeam))]
    public ICollection<Match> AwayMatches{ get; set; }
}


public class Match
{
    [Key]
    public int MatchId { get; set; }

    [ForeignKey(nameof(HomeTeam)), Column(Order = 0)]
    public int HomeTeamId { get; set; }
    [ForeignKey(nameof(GuestTeam)), Column(Order = 1)]
    public int GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public Team HomeTeam { get; set; }
    public Team GuestTeam { get; set; }
}