Programs & Examples On #Rufus scheduler

rufus-scheduler is a job scheduler for Ruby (at, cron, in, every and interval jobs). It's not a substitute for cron, it's just a small in-process scheduler.

How to get sp_executesql result into a variable?

This worked for me:

DECLARE @SQL NVARCHAR(4000)

DECLARE @tbl Table (
    Id int,
    Account varchar(50),
    Amount int
) 

-- Lots of code to Create my dynamic sql statement

insert into @tbl EXEC sp_executesql @SQL

select * from @tbl

Subversion ignoring "--password" and "--username" options

I had a similar problem, I wanted to use a different user name for a svn+ssh repository. In the end, I used svn relocate (as described in in this answer. In my case, I'm using svn 1.6.11 and did the following:

svn switch --relocate \
    svn+ssh://olduser@svnserver/path/to/repo \
    svn+ssh://newuser@svnserver/path/to/repo

where svn+ssh://olduser@svnserver/path/to/repo can be found in the URL: line output of svn info command. This command asked me for the password of newuser.

Note that this change is persistent, i.e. if you want only temporarily switch to the new username with this method, you'll have to issue a similar command again after svn update etc.

LINQ Group By into a Dictionary Object

Dictionary<string, List<CustomObject>> myDictionary = ListOfCustomObjects
    .GroupBy(o => o.PropertyName)
    .ToDictionary(g => g.Key, g => g.ToList());

How to use Bootstrap 4 in ASP.NET Core

We use bootstrap 4 in asp.net core but reference the libraries from "npm" using the "Package Installer" extension and found this to be better than Nuget for Javascript/CSS libraries.

We then use the "Bundler & Minifier" extension to copy the relevant files for distribution (from the npm node_modules folder, which sits outside the project) into wwwroot as we like for development/deployment.

The maximum recursion 100 has been exhausted before statement completion

it is just a sample to avoid max recursion error. we have to use option (maxrecursion 365); or option (maxrecursion 0);

DECLARE @STARTDATE datetime; 
DECLARE @EntDt datetime; 
set @STARTDATE = '01/01/2009';  
set @EntDt = '12/31/2009'; 
declare @dcnt int; 
;with DateList as   
 (   
    select @STARTDATE DateValue   
    union all   
    select DateValue + 1 from    DateList      
    where   DateValue + 1 < convert(VARCHAR(15),@EntDt,101)   
 )   
  select count(*) as DayCnt from (   
  select DateValue,DATENAME(WEEKDAY, DateValue ) as WEEKDAY from DateList
  where DATENAME(WEEKDAY, DateValue ) not IN ( 'Saturday','Sunday' )     
  )a
option (maxrecursion 365);

How to instantiate a javascript class in another js file?

If you are using javascript in HTML, you should include file1.js and file2.js inside your html:

<script src="path_to/file1.js"></script>
<script src="path_to/file2.js"></script>

Note, file1 should come first before file2.

JSON Java 8 LocalDateTime format in Spring Boot

1) Dependency

 compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.8.8' 

2) Annotation with date-time format.

public class RestObject {

    private LocalDateTime timestamp;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    public LocalDateTime getTimestamp() {
        return timestamp;
    }
}

3) Spring Config.

@Configuration
public class JacksonConfig {

    @Bean
    @Primary
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
        System.out.println("Config is starting.");
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        return objectMapper;
    }
}

How can I stream webcam video with C#?

The usual API for this is DirectShow.

You can use P/Invoke to import the C++ APIs, but I think there are already a few projects out there that have done this.

http://channel9.msdn.com/forums/TechOff/93476-Programatically-Using-A-Webcam-In-C/

http://www.codeproject.com/KB/directx/DirXVidStrm.aspx

To get the streaming part, you probably want to use DirectShow to apply a compression codec to reduce lag, then you can get a Stream and transmit it. You could consider using multicast to reduce network load.

Convert pandas timezone-aware DateTimeIndex to naive timestamp, but in certain timezone

Late contribution but just came across something similar in Python datetime and pandas give different timestamps for the same date.

If you have timezone-aware datetime in pandas, technically, tz_localize(None) changes the POSIX timestamp (that is used internally) as if the local time from the timestamp was UTC. Local in this context means local in the specified timezone. Ex:

import pandas as pd

t = pd.date_range(start="2013-05-18 12:00:00", periods=2, freq='H', tz="US/Central")
# DatetimeIndex(['2013-05-18 12:00:00-05:00', '2013-05-18 13:00:00-05:00'], dtype='datetime64[ns, US/Central]', freq='H')

t_loc = t.tz_localize(None)
# DatetimeIndex(['2013-05-18 12:00:00', '2013-05-18 13:00:00'], dtype='datetime64[ns]', freq='H')

# offset in seconds according to timezone:
(t_loc.values-t.values)//1e9
# array([-18000, -18000], dtype='timedelta64[ns]')

Note that this will leave you with strange things during DST transitions, e.g.

t = pd.date_range(start="2020-03-08 01:00:00", periods=2, freq='H', tz="US/Central")
(t.values[1]-t.values[0])//1e9
# numpy.timedelta64(3600,'ns')

t_loc = t.tz_localize(None)
(t_loc.values[1]-t_loc.values[0])//1e9
# numpy.timedelta64(7200,'ns')

In contrast, tz_convert(None) does not modify the internal timestamp, it just removes the tzinfo.

t_utc = t.tz_convert(None)
(t_utc.values-t.values)//1e9
# array([0, 0], dtype='timedelta64[ns]')

My bottom line would be: stick with timezone-aware datetime if you can or only use t.tz_convert(None) which doesn't modify the underlying POSIX timestamp. Just keep in mind that you're practically working with UTC then.

(Python 3.8.2 x64 on Windows 10, pandas v1.0.5.)

How do I declare a model class in my Angular 2 component using TypeScript?

my code is

    import { Component } from '@angular/core';

class model {
  username : string;
  password : string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})



export class AppComponent {

 username : string;
 password : string;
  usermodel = new model();

  login(){
  if(this.usermodel.username == "admin"){
    alert("hi");
  }else{
    alert("bye");
    this.usermodel.username = "";
  }    
  }
}

and the html goes like this :

<div class="login">
  Usernmae : <input type="text" [(ngModel)]="usermodel.username"/>
  Password : <input type="text" [(ngModel)]="usermodel.password"/>
  <input type="button" value="Click Me" (click)="login()" />
</div>

What is the best way to test for an empty string in Go?

Both styles are used within the Go's standard libraries.

if len(s) > 0 { ... }

can be found in the strconv package: http://golang.org/src/pkg/strconv/atoi.go

if s != "" { ... }

can be found in the encoding/json package: http://golang.org/src/pkg/encoding/json/encode.go

Both are idiomatic and are clear enough. It is more a matter of personal taste and about clarity.

Russ Cox writes in a golang-nuts thread:

The one that makes the code clear.
If I'm about to look at element x I typically write
len(s) > x, even for x == 0, but if I care about
"is it this specific string" I tend to write s == "".

It's reasonable to assume that a mature compiler will compile
len(s) == 0 and s == "" into the same, efficient code.
...

Make the code clear.

As pointed out in Timmmm's answer, the Go compiler does generate identical code in both cases.

Relative imports in Python 3

I think the best solution is to create a package for your module: Here is more info on how to do it.

Once you have a package you don't need to worry about relative import, you can just do absolute imports.

FileSystemWatcher Changed event is raised twice

After struggling with the Changed event firing twice as well, I found that the easiest solution is to compare the byte[] contents of the file before and after the event fires, then only execute your code if the contents of the file actually changed.

The basic problem is this same event is fired for each specific type of change to a file, besides just content changes. Just saving a change to the file contents fires the event multiple times (due to a change in the file date, attributes, or whatever else it is detecting).

The FileSystemWatcher class SHOULD be providing a lot more events for all the various changes a file or directory can experience. This is an annoying oversight by the .NET team. It's absurd that a single action within the system or by a user would result in firing a single event in .NET more than once. This is an incredibly dumb design.

And before one of you apologists makes up some absolutely ridiculous excuses why WE are all capable of writing custom code to prevent an event from firing multiple times but the developers at Microsoft are not, save your time. This has become the worst part of the StackOverflow experience: all the butt-kissing apologists that refuse to admit that there are design flaws in software all around us that we use every day that could be corrected if the publisher would simply invest the time and expense.

Which variable size to use (db, dw, dd) with x86 assembly?

The full list is:

DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)

See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html

They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):

    db      0x55                ; just the byte 0x55
    db      0x55,0x56,0x57      ; three bytes in succession
    db      'a',0x55            ; character constants are OK
    db      'hello',13,10,'$'   ; so are string constants
    dw      0x1234              ; 0x34 0x12
    dw      'A'                 ; 0x41 0x00 (it's just a number)
    dw      'AB'                ; 0x41 0x42 (character constant)
    dw      'ABC'               ; 0x41 0x42 0x43 0x00 (string)
    dd      0x12345678          ; 0x78 0x56 0x34 0x12
    dq      0x1122334455667788  ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    ddq     0x112233445566778899aabbccddeeff00
    ; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
    ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    do      0x112233445566778899aabbccddeeff00 ; same as previous
    dd      1.234567e20         ; floating-point constant
    dq      1.234567e20         ; double-precision float
    dt      1.234567e20         ; extended-precision float

DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.

Window.Open with PDF stream instead of PDF location

It looks like window.open will take a Data URI as the location parameter.

So you can open it like this from the question: Opening PDF String in new window with javascript:

window.open("data:application/pdf;base64, " + base64EncodedPDF);

Here's an runnable example in plunker, and sample pdf file that's already base64 encoded.

Then on the server, you can convert the byte array to base64 encoding like this:

string fileName = @"C:\TEMP\TEST.pdf";
byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);
string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);

NOTE: This seems difficult to implement in IE because the URL length is prohibitively small for sending an entire PDF.

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

what is the use of "response.setContentType("text/html")" in servlet

You have to tell the browser what you are sending back so that the browser can take appropriate action like launching a PDF viewer if its a PDF that is being received or launching a video player to play video file ,rendering the HTML if the content type is simple html response, save the bytes of the response as a downloaded file, etc.

some common MIME types are text/html,application/pdf,video/quicktime,application/java,image/jpeg,application/jar etc

In your case since you are sending HTML response to client you will have to set the content type as text/html

Can not find module “@angular-devkit/build-angular”

This worked for me: Type npm audit fix in the commandline. Afterwards I was able to use ng serve --open again.

How to get the current user's Active Directory details in C#

Add reference to COM "Active DS Type Library"


            Int32 nameTypeNT4               = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_NT4;
            Int32 nameTypeDN                = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_1779;
            Int32 nameTypeUserPrincipalName = (int) ActiveDs.ADS_NAME_TYPE_ENUM.ADS_NAME_TYPE_USER_PRINCIPAL_NAME;

            ActiveDs.NameTranslate nameTranslate = new ActiveDs.NameTranslate();

            // Convert NT name DOMAIN\User into AD distinguished name 
            // "CN= User\\, Name,OU=IT,OU=All Users,DC=Company,DC=com"
            nameTranslate.Set(nameTypeNT4, ntUser);

            String distinguishedName = nameTranslate.Get(nameTypeDN);

            Console.WriteLine(distinguishedName);

            // Convert AD distinguished name "CN= User\\, Name,OU=IT,OU=All Users,DC=Company,DC=com" 
            // into NT name DOMAIN\User
            ntUser = String.Empty;
            nameTranslate.Set(nameTypeDN, distinguishedName);
            ntUser = nameTranslate.Get(nameTypeNT4);
            Console.WriteLine(ntUser);

            // Convert NT name DOMAIN\User into AD UserPrincipalName [email protected]
            nameTranslate.Set(nameTypeNT4, ntUser);
            String userPrincipalName = nameTranslate.Get(nameTypeUserPrincipalName);

            Console.WriteLine(userPrincipalName);

Impact of Xcode build options "Enable bitcode" Yes/No

From the docs

  • can I use the above method without any negative impact and without compromising a future appstore submission?

Bitcode will allow apple to optimise the app without you having to submit another build. But, you can only enable this feature if all frameworks and apps in the app bundle have this feature enabled. Having it helps, but not having it should not have any negative impact.

  • What does the ENABLE_BITCODE actually do, will it be a non-optional requirement in the future?

For iOS apps, bitcode is the default, but optional. If you provide bitcode, all apps and frameworks in the app bundle need to include bitcode. For watchOS apps, bitcode is required.

  • Are there any performance impacts if I enable / disable it?

The App Store and operating system optimize the installation of iOS and watchOS apps by tailoring app delivery to the capabilities of the user’s particular device, with minimal footprint. This optimization, called app thinning, lets you create apps that use the most device features, occupy minimum disk space, and accommodate future updates that can be applied by Apple. Faster downloads and more space for other apps and content provides a better user experience.

There should not be any performance impacts.

grunt: command not found when running from terminal

For windows

npm install -g grunt-cli

npm install load-grunt-tasks

Then run

grunt

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

What i did was i commented out the

props.put("mail.smtp.starttls.enable","true"); 

Because apparently for G-mail you did not need it. Then if you haven't already done this you need to create an app password in G-mail for your program. I did that and it worked perfectly. Here this link will show you how: https://support.google.com/accounts/answer/185833.

Set line height in Html <p> to make the html looks like a office word when <p> has different font sizes

I found that in my code when I used a ration or percentage for line-height line-height;1.5;

My page would scale in such a way that lower case font and upper case font would take up different page heights (I.E. All caps took more room than all lower). Normally I think this looks better, but I had to go to a fixed height line-height:24px; so that I could predict exactly how many pixels each page would take with a given number of lines.

What's the difference between utf8_general_ci and utf8_unicode_ci?

This post describes it very nicely.

In short: utf8_unicode_ci uses the Unicode Collation Algorithm as defined in the Unicode standards, whereas utf8_general_ci is a more simple sort order which results in "less accurate" sorting results.

How to execute multiple SQL statements from java

I'm not sure that you want to send two SELECT statements in one request statement because you may not be able to access both ResultSets. The database may only return the last result set.

Multiple ResultSets

However, if you're calling a stored procedure that you know can return multiple resultsets something like this will work

CallableStatement stmt = con.prepareCall(...);
try {
...

boolean results = stmt.execute();

while (results) {
    ResultSet rs = stmt.getResultSet();
    try {
    while (rs.next()) {
        // read the data
    }
    } finally {
        try { rs.close(); } catch (Throwable ignore) {}
    }

    // are there anymore result sets?
    results = stmt.getMoreResults();
}
} finally {
    try { stmt.close(); } catch (Throwable ignore) {}
}

Multiple SQL Statements

If you're talking about multiple SQL statements and only one SELECT then your database should be able to support the one String of SQL. For example I have used something like this on Sybase

StringBuffer sql = new StringBuffer( "SET rowcount 100" );
sql.append( " SELECT * FROM tbl_books ..." );
sql.append( " SET rowcount 0" );

stmt = conn.prepareStatement( sql.toString() );

This will depend on the syntax supported by your database. In this example note the addtional spaces padding the statements so that there is white space between the staments.

JavaScript dictionary with names

An easier, native and more efficient way of emulating a dict in JavaScript than a hash table:

It also exploits that JavaScript is weakly typed. Rather type inference.

Here's how (an excerpt from Google Chrome's console):

var myDict = {};

myDict.one = 1;
1

myDict.two = 2;
2

if (myDict.hasOwnProperty('three'))
{
  console.log(myDict.two);
}
else
{
  console.log('Key does not exist!');
}
Key does not exist! VM361:8

if (myDict.hasOwnProperty('two'))
{
  console.log(myDict.two);
}
else
{
  console.log('Key does not exist!');
}
2 VM362:4

Object.keys(myDict);
["one", "two"]

delete(myDict.two);
true

myDict.hasOwnProperty('two');
false

myDict.two
undefined

myDict.one
1

CSS: how to position element in lower right?

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

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

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

How to read html from a url in python 3

Try the 'requests' module, it's much simpler.

#pip install requests for installation

import requests

url = 'https://www.google.com/'
r = requests.get(url)
r.text

more info here > http://docs.python-requests.org/en/master/

How to list imported modules?

import sys
sys.modules.keys()

An approximation of getting all imports for the current module only would be to inspect globals() for modules:

import types
def imports():
    for name, val in globals().items():
        if isinstance(val, types.ModuleType):
            yield val.__name__

This won't return local imports, or non-module imports like from x import y. Note that this returns val.__name__ so you get the original module name if you used import module as alias; yield name instead if you want the alias.

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

.loc accept row and column selectors simultaneously (as do .ix/.iloc FYI) This is done in a single pass as well.

In [1]: df = DataFrame(np.random.rand(4,5), columns = list('abcde'))

In [2]: df
Out[2]: 
          a         b         c         d         e
0  0.669701  0.780497  0.955690  0.451573  0.232194
1  0.952762  0.585579  0.890801  0.643251  0.556220
2  0.900713  0.790938  0.952628  0.505775  0.582365
3  0.994205  0.330560  0.286694  0.125061  0.575153

In [5]: df.loc[df['c']>0.5,['a','d']]
Out[5]: 
          a         d
0  0.669701  0.451573
1  0.952762  0.643251
2  0.900713  0.505775

And if you want the values (though this should pass directly to sklearn as is); frames support the array interface

In [6]: df.loc[df['c']>0.5,['a','d']].values
Out[6]: 
array([[ 0.66970138,  0.45157274],
       [ 0.95276167,  0.64325143],
       [ 0.90071271,  0.50577509]])

How to center the elements in ConstraintLayout

You can center a view as a percentage of the screen size.

This example uses 50% of width and height:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#FF0000"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHeight_percent=".5"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_percent=".5"></LinearLayout>

</android.support.constraint.ConstraintLayout>

This was done using ConstraintLayout version 1.1.3. Don't forget to add it to your dependencies in the gradle, and increase the version if there is a new version out there:

dependencies {
...
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}

enter image description here

android start activity from service

UPDATE ANDROID 10 AND HIGHER

Start an activity from service (foreground or background) is no longer allowed.

There are still some restrictions that can be seen in the documentation

https://developer.android.com/guide/components/activities/background-starts

How to use JUnit to test asynchronous processes

If you use a CompletableFuture (introduced in Java 8) or a SettableFuture (from Google Guava), you can make your test finish as soon as it's done, rather than waiting a pre-set amount of time. Your test would look something like this:

CompletableFuture<String> future = new CompletableFuture<>();
executorService.submit(new Runnable() {         
    @Override
    public void run() {
        future.complete("Hello World!");                
    }
});
assertEquals("Hello World!", future.get());

Xcode build failure "Undefined symbols for architecture x86_64"

I also encountered the same problem , the above methods will not work . I accidentally deleted the files in the following directory on it . enter image description here

Or

~/Library/Developer/Xcode/DerivedData/

enter image description here

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

A good practice is write text inside String.xml

example:

String.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="yellow">Yellow</string>
</resources>

and inside layout:

<TextView android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="@string/yellow" />

JSON and XML comparison

Processing speed may not be the only relevant matter, however, as that's the question, here are some numbers in a benchmark: JSON vs. XML: Some hard numbers about verbosity. For the speed, in this simple benchmark, XML presents a 21% overhead over JSON.

An important note about the verbosity, which is as the article says, the most common complain: this is not so much relevant in practice (neither XML nor JSON data are typically handled by humans, but by machines), even if for the matter of speed, it requires some reasonable more time to compress.

Also, in this benchmark, a big amount of data was processed, and a typical web application won't transmit data chunks of such sizes, as big as 90MB, and compression may not be beneficial (for small enough data chunks, a compressed chunk will be bigger than the uncompressed chunk), so not applicable.

Still, if no compression is involved, JSON, as obviously terser, will weight less over the transmission channel, especially if transmitted through a WebSocket connection, where the absence of the classic HTTP overhead may make the difference at the advantage of JSON, even more significant.

After transmission, data is to be consumed, and this count in the overall processing time. If big or complex enough data are to be transmitted, the lack of a schema automatically checked for by a validating XML parser, may require more check on JSON data; these checks would have to be executed in JavaScript, which is not known to be particularly fast, and so it may present an additional overhead over XML in such cases.

Anyway, only testing will provides the answer for your particular use-case (if speed is really the only matter, and not standard nor safety nor integrity…).

Update 1: worth to mention, is EXI, the binary XML format, which offers compression at less cost than using Gzip, and save processing otherwise needed to decompress compressed XML. EXI is to XML, what BSON is to JSON. Have a quick overview here, with some reference to efficiency in both space and time: EXI: The last binary standard?.

Update 2: there also exists a binary XML performance reports, conducted by the W3C, as efficiency and low memory and CPU footprint, is also a matter for the XML area too: Efficient XML Interchange Evaluation.

Update 2015-03-01

Worth to be noticed in this context, as HTTP overhead was raised as an issue: the IANA has registered the EXI encoding (the efficient binary XML mentioned above), as a a Content Coding for the HTTP protocol (alongside with compress, deflate and gzip). This means EXI is an option which can be expected to be understood by browsers among possibly other HTTP clients. See Hypertext Transfer Protocol Parameters (iana.org).

Where to find free public Web Services?

https://www.programmableweb.com/ -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.

Change default text in input type="file"?

This might help someone in the future, you can style the label for the input as you like and put anything you want inside it and hide the input with display none.

It works perfectly on cordova with iOS

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/ratchet/2.0.2/css/ratchet.css" rel="stylesheet"/>_x000D_
<label for="imageUpload" class="btn btn-primary btn-block btn-outlined">Seleccionar imagenes</label>_x000D_
<input type="file" id="imageUpload" accept="image/*" style="display: none">
_x000D_
_x000D_
_x000D_

Shortest way to check for null and assign another value if not

To extend @Dave's answer...if planRec.approved_by is already a string

this.approved_by = planRec.approved_by ?? "";

Configuring IntelliJ IDEA for unit testing with JUnit

In my case (IntelliJ 2020-02, Kotlin dev) JUnit library was already included by Create project wizard. I needed to enable JUnit plugin:

IntelliJ JUnit plugin

to get green Run test icons next to each test class and method:

enter image description here

and CTRL+Shift+R will run test under caret, and CTRL+shift+D to debug.

ImportError: No module named Image

The PIL distribution is mispackaged for egg installation.

Install Pillow instead, the friendly PIL fork.

asp.net Button OnClick event not firing

If you are using updatepanel on onclick event, this may happen.

Use 'EnableEventValidation="false"' in your page markup like this :

<%@ Page Language="C#" MasterPageFile="~/ars_home.master" AutoEventWireup="true" CodeFile="Transaction_Window.aspx.cs" Inherits="Transaction_Window" EnableEventValidation="false" %>

Hope this helps

Java 8 optional: ifPresent return object orElseThrow exception

Actually what you are searching is: Optional.map. Your code would then look like:

object.map(o -> "result" /* or your function */)
      .orElseThrow(MyCustomException::new);

I would rather omit passing the Optional if you can. In the end you gain nothing using an Optional here. A slightly other variant:

public String getString(Object yourObject) {
  if (Objects.isNull(yourObject)) { // or use requireNonNull instead if NullPointerException suffices
     throw new MyCustomException();
  }
  String result = ...
  // your string mapping function
  return result;
}

If you already have the Optional-object due to another call, I would still recommend you to use the map-method, instead of isPresent, etc. for the single reason, that I find it more readable (clearly a subjective decision ;-)).

Git add and commit in one command

I use the following alias for add all and commit:

git config --global alias.ac '!git add -A && git commit -a'

Then, by typing:

git ac

I get a vim window to get more editing tools for my commit message.

What is the difference between a "line feed" and a "carriage return"?

A line feed means moving one line forward. The code is \n.
A carriage return means moving the cursor to the beginning of the line. The code is \r.

Windows editors often still use the combination of both as \r\n in text files. Unix uses mostly only the \n.

The separation comes from typewriter times, when you turned the wheel to move the paper to change the line and moved the carriage to restart typing on the beginning of a line. This was two steps.

How to programmatically set style attribute in a view

Yes, you can use for example in a button

Button b = new Button(this);
b.setBackgroundResource(R.drawable.selector_test);

Responsive background image in div full width

When you use background-size: cover the background image will automatically be stretched to cover the entire container. Aspect ratio is maintained however, so you will always lose part of the image, unless the aspect ratio of the image and the element it is applied to are identical.

I see two ways you could solve this:

  • Do not maintain the aspect ratio of the image by setting background-size: 100% 100% This will also make the image cover the entire container, but the ratio will not be maintained. Disadvantage is that this distorts your image, and therefore may look very weird, depending on the image. With the image you are using in the fiddle, I think you could get away with it though.

  • You could also calculate and set the height of the element with javascript, based on its width, so it gets the same ratio as the image. This calculation would have to be done on load and on resize. It should be easy enough with a few lines of code (feel free to ask if you want an example). Disadvantage of this method is that your width may become very small (on mobile devices), and therfore the calculated height also, which may cause the content of the container to overflow. This could be solved by changing the size of the content as well or something, but it adds some complexity to the solution/

How to detect the currently pressed key?

Since .NET Framework version 3.0, it is possible to use the Keyboard.IsKeyDown method from the new System.Windows.Input namespace. For instance:

if (((Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl)) && Keyboard.IsKeyDown(Key.F))
{
    // CTRL + F is currently pressed
}

Even though it's part of WPF, that method works fine for WinForm applications (provided that you add references to PresentationCore.dll and WindowsBase.dll). Unfortunately, however, the 3.0 and 3.5 versions of the Keyboard.IsKeyDown method did not work for WinForm applications. Therefore, if you do want to use it in a WinForm application, you'll need to be targeting .NET Framework 4.0 or later in order for it to work.

Accessing dictionary value by index in python

If you really just want a random value from the available key range, use random.choice on the dictionary's values (converted to list form, if Python 3).

>>> from random import choice
>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>>> choice(list(d.values()))

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

500000 microseconds are 500000000 nanoseconds. You only wait for 500 ns = 0.5 µs.

How to make connection to Postgres via Node.js

Here is an example I used to connect node.js to my Postgres database.

The interface in node.js that I used can be found here https://github.com/brianc/node-postgres

var pg = require('pg');
var conString = "postgres://YourUserName:YourPassword@localhost:5432/YourDatabase";

var client = new pg.Client(conString);
client.connect();

//queries are queued and executed one after another once the connection becomes available
var x = 1000;

while (x > 0) {
    client.query("INSERT INTO junk(name, a_number) values('Ted',12)");
    client.query("INSERT INTO junk(name, a_number) values($1, $2)", ['John', x]);
    x = x - 1;
}

var query = client.query("SELECT * FROM junk");
//fired after last row is emitted

query.on('row', function(row) {
    console.log(row);
});

query.on('end', function() {
    client.end();
});



//queries can be executed either via text/parameter values passed as individual arguments
//or by passing an options object containing text, (optional) parameter values, and (optional) query name
client.query({
    name: 'insert beatle',
    text: "INSERT INTO beatles(name, height, birthday) values($1, $2, $3)",
    values: ['George', 70, new Date(1946, 02, 14)]
});

//subsequent queries with the same name will be executed without re-parsing the query plan by postgres
client.query({
    name: 'insert beatle',
    values: ['Paul', 63, new Date(1945, 04, 03)]
});
var query = client.query("SELECT * FROM beatles WHERE name = $1", ['john']);

//can stream row results back 1 at a time
query.on('row', function(row) {
    console.log(row);
    console.log("Beatle name: %s", row.name); //Beatle name: John
    console.log("Beatle birth year: %d", row.birthday.getYear()); //dates are returned as javascript dates
    console.log("Beatle height: %d' %d\"", Math.floor(row.height / 12), row.height % 12); //integers are returned as javascript ints
});

//fired after last row is emitted
query.on('end', function() {
    client.end();
});

UPDATE:- THE query.on function is now deprecated and hence the above code will not work as intended. As a solution for this look at:- query.on is not a function

Sending Windows key using SendKeys

Alt+F4 is working only in brackets

SendKeys.SendWait("(%{F4})");

Is there any way to kill a Thread?

Just to build up on @SCB's idea (which was exactly what I needed) to create a KillableThread subclass with a customized function:

from threading import Thread, Event

class KillableThread(Thread):
    def __init__(self, sleep_interval=1, target=None, name=None, args=(), kwargs={}):
        super().__init__(None, target, name, args, kwargs)
        self._kill = Event()
        self._interval = sleep_interval
        print(self._target)

    def run(self):
        while True:
            # Call custom function with arguments
            self._target(*self._args)

            # If no kill signal is set, sleep for the interval,
            # If kill signal comes in while sleeping, immediately
            #  wake up and handle
            is_killed = self._kill.wait(self._interval)
            if is_killed:
                break

        print("Killing Thread")

    def kill(self):
        self._kill.set()

if __name__ == '__main__':

    def print_msg(msg):
        print(msg)

    t = KillableThread(10, print_msg, args=("hello world"))
    t.start()
    time.sleep(6)
    print("About to kill thread")
    t.kill()

Naturally, like with @SBC, the thread doesn't wait to run a new loop to stop. In this example, you would see the "Killing Thread" message printed right after the "About to kill thread" instead of waiting for 4 more seconds for the thread to complete (since we have slept for 6 seconds already).

Second argument in KillableThread constructor is your custom function (print_msg here). Args argument are the arguments that will be used when calling the function (("hello world")) here.

Are there pointers in php?

Variable names in PHP start with $ so $entryId is the name of a variable. $this is a special variable in Object Oriented programming in PHP, which is reference to current object. -> is used to access an object member (like properties or methods) in PHP, like the syntax in C++. so your code means this:

Place the value of variable $entryId into the entryId field (or property) of this object.

The & operator in PHP, means pass reference. Here is a example:

$b=2;
$a=$b;
$a=3;
print $a;
print $b;
// output is 32

$b=2;
$a=&$b; // note the & operator
$a=3;
print $a;
print $b;
// output is 33

In the above code, because we used & operator, a reference to where $b is pointing is stored in $a. So $a is actually a reference to $b.

In PHP, arguments are passed by value by default (inspired by C). So when calling a function, when you pass in your values, they are copied by value not by reference. This is the default IN MOST SITUATIONS. However there is a way to have pass by reference behaviour, when defining a function. Example:

function plus_by_reference( &$param ) {
      // what ever you do, will affect the actual parameter outside the function
      $param++;
}

$a=2;
plus_by_reference( $a );
echo $a;
// output is 3

There are many built-in functions that behave like this. Like the sort() function that sorts an array will affect directly on the array and will not return another sorted array.

There is something interesting to note though. Because pass-by-value mode could result in more memory usage, and PHP is an interpreted language (so programs written in PHP are not as fast as compiled programs), to make the code run faster and minimize memory usage, there are some tweaks in the PHP interpreter. One is lazy-copy (I'm not sure about the name). Which means this:

When you are coping a variable into another, PHP will copy a reference to the first variable into the second variable. So your new variable, is actually a reference to the first one until now. The value is not copied yet. But if you try to change any of these variables, PHP will make a copy of the value, and then changes the variable. This way you will have the opportunity to save memory and time, IF YOU DO NOT CHANGE THE VALUE.

So:

$b=3;
$a=$b;
// $a points to $b, equals to $a=&$b
$b=4;
// now PHP will copy 3 into $a, and places 4 into $b

After all this, if you want to place the value of $entryId into 'entryId' property of your object, the above code will do this, and will not copy the value of entryId, until you change any of them, results in less memory usage. If you actually want them both to point to the same value, then use this:

$this->entryId=&$entryId;

Python regex for integer?

I prefer ^[-+]?([1-9]\d*|0)$ because ^[-+]?[0-9]+$ allows the string starting with 0.

RE_INT = re.compile(r'^[-+]?([1-9]\d*|0)$')


class TestRE(unittest.TestCase):
    def test_int(self):
        self.assertFalse(RE_INT.match('+'))
        self.assertFalse(RE_INT.match('-'))

        self.assertTrue(RE_INT.match('1'))
        self.assertTrue(RE_INT.match('+1'))
        self.assertTrue(RE_INT.match('-1'))
        self.assertTrue(RE_INT.match('0'))
        self.assertTrue(RE_INT.match('+0'))
        self.assertTrue(RE_INT.match('-0'))

        self.assertTrue(RE_INT.match('11'))
        self.assertFalse(RE_INT.match('00'))
        self.assertFalse(RE_INT.match('01'))
        self.assertTrue(RE_INT.match('+11'))
        self.assertFalse(RE_INT.match('+00'))
        self.assertFalse(RE_INT.match('+01'))
        self.assertTrue(RE_INT.match('-11'))
        self.assertFalse(RE_INT.match('-00'))
        self.assertFalse(RE_INT.match('-01'))

        self.assertTrue(RE_INT.match('1234567890'))
        self.assertTrue(RE_INT.match('+1234567890'))
        self.assertTrue(RE_INT.match('-1234567890'))

How to see full query from SHOW PROCESSLIST

Show Processlist fetches the information from another table. Here is how you can pull the data and look at 'INFO' column which contains the whole query :

select * from INFORMATION_SCHEMA.PROCESSLIST where db = 'somedb';

You can add any condition or ignore based on your requirement.

The output of the query is resulted as :

+-------+------+-----------------+--------+---------+------+-----------+----------------------------------------------------------+
| ID    | USER | HOST            | DB     | COMMAND | TIME | STATE     | INFO                                                     |
+-------+------+-----------------+--------+---------+------+-----------+----------------------------------------------------------+
|     5 | ssss | localhost:41060 | somedb | Sleep   |    3 |           | NULL                                                     |
| 58169 | root | localhost       | somedb | Query   |    0 | executing | select * from sometable where tblColumnName = 'someName' |

How to show x and y axes in a MATLAB graph?

This should work in Matlab:

set(gca, 'XAxisLocation', 'origin')

Options are: bottom, top, origin.

For Y.axis:

YAxisLocation; left, right, origin

jQuery - Create hidden form element on the fly

function addHidden(theForm, key, value) {
    // Create a hidden input element, and append it to the form:
    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = key; //name-as-seen-at-the-server
    input.value = value;
    theForm.appendChild(input);
}

// Form reference:
var theForm = document.forms['detParameterForm'];

// Add data:
addHidden(theForm, 'key-one', 'value');

What does the PHP error message "Notice: Use of undefined constant" mean?

The error message is due to the unfortunate fact that PHP will implicitly declare an unknown token as a constant string of the same name.

That is, it's trying to interpret this (note the missing quote marks):

$_POST[department]

The only valid way this would be valid syntax in PHP is if there was previously a constant department defined. So sadly, rather than dying with a Fatal error at this point, it issues this Notice and acts as though a constant had been defined with the same name and value:

// Implicit declaration of constant called department with value 'department'
define('department', 'department');  

There are various ways you can get this error message, but they all have the same root cause - a token that could be a constant.

Strings missing quotes: $my_array[bad_key]

This is what the problem is in your case, and it's because you've got string array keys that haven't been quoted. Fixing the string keys will fix the bug:

Change:

$department = mysql_real_escape_string($_POST[department]);
...(etc)...

To:

$department = mysql_real_escape_string($_POST['department']);
...(etc)...

Variable missing dollar sign: var_without_dollar

Another reason you might see this error message is if you leave off the $ from a variable, or $this-> from a member. Eg, either of the following would cause a similar error message:

my_local;   // should be $my_local
my_member;  // should be $this->my_member

Invalid character in variable name: $bad-variable-name

A similar but more subtle issue can result if you try to use a disallowed character in a variable name - a hyphen (-) instead of an underscore _ would be a common case.

For example, this is OK, since underscores are allowed in variable names:

if (123 === $my_var) {
  do_something();
}

But this isn't:

if (123 === $my-var) {
  do_something();
}

It'll be interpreted the same as this:

if (123 === $my - var) {  // variable $my minus constant 'var'
  do_something();
}

Referring to a class constant without specifying the class scope

In order to refer to a class constant you need to specify the class scope with ::, if you miss this off PHP will think you're talking about a global define().

Eg:

class MyClass {
  const MY_CONST = 123;

  public function my_method() {
    return self::MY_CONST;  // This is fine
  }


  public function my_method() {
    return MyClass::MY_CONST;  // This is fine
  }

  public function my_bad_method() {
    return MY_CONST;  // BUG - need to specify class scope
  }
}

Using a constant that's not defined in this version of PHP, or is defined in an extension that's not installed

There are some system-defined constants that only exist in newer versions of PHP, for example the mode option constants for round() such as PHP_ROUND_HALF_DOWN only exist in PHP 5.3 or later.

So if you tried to use this feature in PHP 5.2, say:

$rounded = round($my_var, 0, PHP_ROUND_HALF_DOWN);

You'd get this error message:

Use of undefined constant PHP_ROUND_HALF_DOWN - assumed 'PHP_ROUND_HALF_DOWN' Warning (2): Wrong parameter count for round()

Factorial in numpy and scipy

SciPy has the function scipy.special.factorial (formerly scipy.misc.factorial)

>>> import math
>>> import scipy.special
>>> math.factorial(6)
720
>>> scipy.special.factorial(6)
array(720.0)

Getting only 1 decimal place

Are you trying to represent it with only one digit:

print("{:.1f}".format(number)) # Python3
print "%.1f" % number          # Python2

or actually round off the other decimal places?

round(number,1)

or even round strictly down?

math.floor(number*10)/10

How to remove "index.php" in codeigniter's path

If you are using Apache place a .htaccess file in your root web directory containing the following:

RewriteEngine on
RewriteCond $1 !^(index\.php|[Javascript / CSS / Image root Folder name(s)]|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

Another good version is located here:

http://snipplr.com/view/5966/codeigniter-htaccess/

Unsetting array values in a foreach loop

Try that:

foreach ($images[1] as $key => &$image) {
    if (yourConditionGoesHere) {
        unset($images[1][$key])
    }
}
unset($image); // detach reference after loop  

Normally, foreach operates on a copy of your array so any changes you make, are made to that copy and don't affect the actual array.

So you need to unset the values via $images[$key];

The reference on &$image prevents the loop from creating a copy of the array which would waste memory.

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

if you are using tomcat you may try this

<servlet-mapping>

    <http-method>POST</http-method>

</servlet-mapping>

in addition to <servlet-name> and <url-mapping>

Get all child views inside LinearLayout at once

((ViewGroup) findViewById(android.R.id.content));// you can use this in an Activity to get your layout root view, then pass it to findAllEdittexts() method below.

Here I am iterating only EdiTexts, if you want all Views you can replace EditText with View.

SparseArray<EditText> array = new SparseArray<EditText>();

private void findAllEdittexts(ViewGroup viewGroup) {

    int count = viewGroup.getChildCount();
    for (int i = 0; i < count; i++) {
        View view = viewGroup.getChildAt(i);
        if (view instanceof ViewGroup)
            findAllEdittexts((ViewGroup) view);
        else if (view instanceof EditText) {
            EditText edittext = (EditText) view;
            array.put(editText.getId(), editText);
        }
    }
}

A reference to the dll could not be added

The following worked for me:

Short answer

Run the following via command line (cmd):

TlbImp.exe cvextern.dll        //where cvextern.dll is your dll you want to fix.

And a valid dll will be created for you.

Longer answer

  • Open cmd

  • Find TlbImp.exe. Probably located in C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin. If you can't find it go to your root folder (C:\ or D:) and run:

    dir tlbimp.exe /s              //this will locate the file.
    
  • Run tlbimp.exe and put your dll behind it. Example: If your dll is cvextern.dll. You can run:

    TlbImp.exe cvextern.dll
    
  • A new dll has been created in the same folder of tlbimp.exe. You can use that as reference in your project.

Passing parameters to a Bash function

Drop the parentheses and commas:

 myBackupFunction ".." "..." "xx"

And the function should look like this:

function myBackupFunction() {
    # Here $1 is the first parameter, $2 the second, etc.
}

How to return result of a SELECT inside a function in PostgreSQL?

Use RETURN QUERY:

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt   text   -- also visible as OUT parameter inside function
               , cnt   bigint
               , ratio bigint) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt
        , count(*) AS cnt                 -- column alias only visible inside
        , (count(*) * 100) / _max_tokens  -- I added brackets
   FROM  (
      SELECT t.txt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      LIMIT  _max_tokens
      ) t
   GROUP  BY t.txt
   ORDER  BY cnt DESC;                    -- potential ambiguity 
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM word_frequency(123);

Explanation:

  • It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE is one way to do that. There are others. Data types of OUT parameters have to match exactly what is returned by the query.

  • Choose names for OUT parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.

    But note the potential naming conflict between the OUT parameter cnt and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...) Postgres uses the column alias over the OUT parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:

    1. Use the ordinal position of the item in the SELECT list: ORDER BY 2 DESC. Example:
    2. Repeat the expression ORDER BY count(*).
    3. (Not applicable here.) Set the configuration parameter plpgsql.variable_conflict or use the special command #variable_conflict error | use_variable | use_column in the function. See:
  • Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt and cnt in my examples.

  • Added a missing ; and corrected a syntax error in the header. (_max_tokens int), not (int maxTokens) - type after name.

  • While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric (or a floating point type). See below.

Alternative

This is what I think your query should actually look like (calculating a relative share per token):

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt            text
               , abs_cnt        bigint
               , relative_share numeric) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt, t.cnt
        , round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2)  -- AS relative_share
   FROM  (
      SELECT t.txt, count(*) AS cnt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      GROUP  BY t.txt
      ORDER  BY cnt DESC
      LIMIT  _max_tokens
      ) t
   ORDER  BY t.cnt DESC;
END
$func$  LANGUAGE plpgsql;

The expression sum(t.cnt) OVER () is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.

A final explicit RETURN statement is not required (but allowed) when working with OUT parameters or RETURNS TABLE (which makes implicit use of OUT parameters).

round() with two parameters only works for numeric types. count() in the subquery produces a bigint result and a sum() over this bigint produces a numeric result, thus we deal with a numeric number automatically and everything just falls into place.

How to detect page zoom level in all modern browsers?

This may or may not help anyone, but I had a page I could not get to center correctly no matter what Css tricks I tried so I wrote a JQuery file call Center Page:

The problem occurred with zoom level of the browser, the page would shift based upon if you were 100%, 125%, 150%, etc.

The code below is in a JQuery file called centerpage.js.

From my page I had to link to JQuery and this file to get it work, even though my master page already had a link to JQuery.

<title>Home Page.</title>
<script src="Scripts/jquery-1.7.1.min.js"></script>
<script src="Scripts/centerpage.js"></script>

centerpage.js:

// centering page element
function centerPage() {
    // get body element
    var body = document.body;

    // if the body element exists
    if (body != null) {
        // get the clientWidth
        var clientWidth = body.clientWidth;

        // request data for centering
        var windowWidth = document.documentElement.clientWidth;
        var left = (windowWidth - bodyWidth) / 2;

        // this is a hack, but it works for me a better method is to determine the 
        // scale but for now it works for my needs
        if (left > 84) {
            // the zoom level is most likely around 150 or higher
            $('#MainBody').removeClass('body').addClass('body150');
        } else if (left < 100) {
            // the zoom level is most likely around 110 - 140
            $('#MainBody').removeClass('body').addClass('body125');
        }
    }
}


// CONTROLLING EVENTS IN jQuery
$(document).ready(function() {
    // center the page
    centerPage();
});

Also if you want to center a panel:

// centering panel
function centerPanel($panelControl) {
    // if the panel control exists
    if ($panelControl && $panelControl.length) {
        // request data for centering
        var windowWidth = document.documentElement.clientWidth;
        var windowHeight = document.documentElement.clientHeight;
        var panelHeight = $panelControl.height();
        var panelWidth = $panelControl.width();

        // centering
        $panelControl.css({
            'position': 'absolute',
            'top': (windowHeight - panelHeight) / 2,
            'left': (windowWidth - panelWidth) / 2
        });

        // only need force for IE6
        $('#backgroundPanel').css('height', windowHeight);
    }
}

Fastest method to replace all instances of a character in a string

// Find, Replace, Case
// i.e "Test to see if this works? (Yes|No)".replaceAll('(Yes|No)', 'Yes!');
// i.e.2 "Test to see if this works? (Yes|No)".replaceAll('(yes|no)', 'Yes!', true);
String.prototype.replaceAll = function(_f, _r, _c){ 

  var o = this.toString();
  var r = '';
  var s = o;
  var b = 0;
  var e = -1;
  if(_c){ _f = _f.toLowerCase(); s = o.toLowerCase(); }

  while((e=s.indexOf(_f)) > -1)
  {
    r += o.substring(b, b+e) + _r;
    s = s.substring(e+_f.length, s.length);
    b += e+_f.length;
  }

  // Add Leftover
  if(s.length>0){ r+=o.substring(o.length-s.length, o.length); }

  // Return New String
  return r;
};

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.

Here is a complete example from your data that shows a bar of for each required value at each date:

import pylab as pl
import datetime

data = """0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014"""

values = []
dates = []

for line in data.split("\n"):
    x, y = line.split()
    values.append(int(x))
    dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()

You need to parse the date with strptime and set the x-axis to use dates (as described in this answer).

If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(range(len(dates)), values)

EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks (and move them by half the bar width):

fig = pl.figure()
ax = pl.subplot(111)
width=0.8
ax.bar(range(len(dates)), values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)

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

Good question.

True regular languages can not decide arbitrarily deeply nested well-formed parenthesis. If your alphabet contains '(' and ')' the goal is to decide if a string of these has well-formed matching parenthesis. Since this is a necessary requirement for regular expressions the answer is no.

However, if you loosen the requirement and add recursion you can probably do it. The reason is that the recursion can act as a stack letting you "count" the current nesting depth by pushing onto this stack.

Russ Cox wrote "Regular Expression Matching Can Be Simple And Fast" which is a wonderful treatise on regex engine implementation.

In Go's http package, how do I get the query string on a POST request?

Here's a more concrete example of how to access GET parameters. The Request object has a method that parses them out for you called Query:

Assuming a request URL like http://host:port/something?param1=b

func newHandler(w http.ResponseWriter, r *http.Request) {
  fmt.Println("GET params were:", r.URL.Query())

  // if only one expected
  param1 := r.URL.Query().Get("param1")
  if param1 != "" {
    // ... process it, will be the first (only) if multiple were given
    // note: if they pass in like ?param1=&param2= param1 will also be "" :|
  }

  // if multiples possible, or to process empty values like param1 in
  // ?param1=&param2=something
  param1s := r.URL.Query()["param1"]
  if len(param1s) > 0 {
    // ... process them ... or you could just iterate over them without a check
    // this way you can also tell if they passed in the parameter as the empty string
    // it will be an element of the array that is the empty string
  }    
}

Also note "the keys in a Values map [i.e. Query() return value] are case-sensitive."

What is the &#xA; character?

It's a linefeed character. How you use it would be up to you.

android pinch zoom

I have created a project for basic pinch-zoom that supports Android 2.1+

Available here

Git in Visual Studio - add existing project?

The process is greatly simplified for VS2017 / VS2019 (maybe even earlier, but I have not tested) in conjunction with GitHub:

  1. Create an empty repository in GitHub => https://github.com//.git

  2. Install GitHub extension for Visual Studio

  3. Follow these instructions: (optionally add to source control to git initialize) -> Team explorer -> Sync -> Publish to GitHub -> https://github.com//.git

How to set java_home on Windows 7?

if you have not restarted your computer after installing jdk just restart your computer.

if you want to make a portable java and set path before using java, just make a batch file i explained below.

if you want to run this batch file when your computer start just put your batch file shortcut in startup folder. In windows 7 startup folder is "C:\Users\user\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"

make a batch file like this:

set Java_Home=C:\Program Files\Java\jdk1.8.0_11
set PATH=%PATH%;C:\Program Files\Java\jdk1.8.0_11\bin

note: java_home and path are variables. you can make any variable as you wish. for example set amir=good_boy and you can see amir by %amir% or you can see java_home by %java_home%

AngularJS - ng-if check string empty value

You don't need to explicitly use qualifiers like item.photo == '' or item.photo != ''. Like in JavaScript, an empty string will be evaluated as false.

Your views will be much cleaner and readable as well.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>_x000D_
<div ng-app init="item = {photo: ''}">_x000D_
   <div ng-if="item.photo"> show if photo is not empty</div>_x000D_
   <div ng-if="!item.photo"> show if photo is empty</div>_x000D_
  _x000D_
   <input type=text ng-model="item.photo" placeholder="photo" />_x000D_
</div
_x000D_
_x000D_
_x000D_

Updated to remove bug in Angular

Sum of two input value by jquery

Cast them to a Number

$('#total_price').val(Number(a)+Number(b));

But before you do that

if (!isNaN($('input[name=service_price]').val()) {...

CSS to prevent child element from inheriting parent styles

CSS rules are inherited by default - hence the "cascading" name. To get what you want you need to use !important:

form div
{
    font-size: 12px;
    font-weight: bold;
}

div.content
{
    // any rule you want here, followed by !important
}

What's the difference between JavaScript and Java?

JavaScript is an object-oriented scripting language that allows you to create dynamic HTML pages, allowing you to process input data and maintain data, usually within the browser.

Java is a programming language, core set of libraries, and virtual machine platform that allows you to create compiled programs that run on nearly every platform, without distribution of source code in its raw form or recompilation.

While the two have similar names, they are really two completely different programming languages/models/platforms, and are used to solve completely different sets of problems.

Also, this is directly from the Wikipedia Javascript article:

A common misconception is that JavaScript is similar or closely related to Java; this is not so. Both have a C-like syntax, are object-oriented, are typically sandboxed and are widely used in client-side Web applications, but the similarities end there. Java has static typing; JavaScript's typing is dynamic (meaning a variable can hold an object of any type and cannot be restricted). Java is loaded from compiled bytecode; JavaScript is loaded as human-readable code. C is their last common ancestor language.

Convert nested Python dict to object?

Taking what I feel are the best aspects of the previous examples, here's what I came up with:

class Struct:
  '''The recursive class for building and representing objects with.'''
  def __init__(self, obj):
    for k, v in obj.iteritems():
      if isinstance(v, dict):
        setattr(self, k, Struct(v))
      else:
        setattr(self, k, v)
  def __getitem__(self, val):
    return self.__dict__[val]
  def __repr__(self):
    return '{%s}' % str(', '.join('%s : %s' % (k, repr(v)) for
      (k, v) in self.__dict__.iteritems()))

How do I get the max ID with Linq to Entity?

The best way to get the id of the entity you added is like this:

public int InsertEntity(Entity factor)
{
    Db.Entities.Add(factor);
    Db.SaveChanges();
    var id = factor.id;
    return id;
}

TypeError: unsupported operand type(s) for -: 'str' and 'int'

  1. The reason this is failing is because (Python 3) input returns a string. To convert it to an integer, use int(some_string).

  2. You do not typically keep track of indices manually in Python. A better way to implement such a function would be

    def cat_n_times(s, n):
        for i in range(n):
            print(s) 
    
    text = input("What would you like the computer to repeat back to you: ")
    num = int(input("How many times: ")) # Convert to an int immediately.
    
    cat_n_times(text, num)
    
  3. I changed your API above a bit. It seems to me that n should be the number of times and s should be the string.

WooCommerce: Finding the products in database

Bulk add new categories to Woo:

Insert category id, name, url key

INSERT INTO wp_terms 
VALUES
  (57, 'Apples', 'fruit-apples', '0'),
  (58, 'Bananas', 'fruit-bananas', '0');

Set the term values as catergories

INSERT INTO wp_term_taxonomy 
VALUES
  (57, 57, 'product_cat', '', 17, 0),
  (58, 58, 'product_cat', '', 17, 0)

17 - is parent category, if there is one

key here is to make sure the wp_term_taxonomy table term_taxonomy_id, term_id are equal to wp_term table's term_id

After doing the steps above go to wordpress admin and save any existing category. This will update the DB to include your bulk added categories

How to get an input text value in JavaScript

<input type="password"id="har">
<input type="submit"value="get password"onclick="har()">
<script>
    function har() {
        var txt_val;
        txt_val = document.getElementById("har").value;
        alert(txt_val);
    }
</script>

Get current AUTO_INCREMENT value for any table

I was looking for the same and ended up by creating a static method inside a Helper class (in my case I named it App\Helpers\Database).

The method

/**
 * Method to get the autoincrement value from a database table
 *
 * @access public
 *
 * @param string $database The database name or configuration in the .env file
 * @param string $table    The table name
 *
 * @return mixed
 */
public static function getAutoIncrementValue($database, $table)
{
    $database ?? env('DB_DATABASE');

    return \DB::select("
        SELECT AUTO_INCREMENT 
        FROM information_schema.TABLES 
        WHERE TABLE_SCHEMA = '" . env('DB_DATABASE') . "' 
        AND TABLE_NAME = '" . $table . "'"
    )[0]->AUTO_INCREMENT;
}

To call the method and get the MySql AUTO_INCREMENT just use the following:

$auto_increment = \App\Helpers\Database::getAutoIncrementValue(env('DB_DATABASE'), 'your_table_name');

Hope it helps.

What difference does .AsNoTracking() make?

No Tracking LINQ to Entities queries

Usage of AsNoTracking() is recommended when your query is meant for read operations. In these scenarios, you get back your entities but they are not tracked by your context.This ensures minimal memory usage and optimal performance

Pros

  1. Improved performance over regular LINQ queries.
  2. Fully materialized objects.
  3. Simplest to write with syntax built into the programming language.

Cons

  1. Not suitable for CUD operations.
  2. Certain technical restrictions, such as: Patterns using DefaultIfEmpty for OUTER JOIN queries result in more complex queries than simple OUTER JOIN statements in Entity SQL.
  3. You still can’t use LIKE with general pattern matching.

More info available here:

Performance considerations for Entity Framework

Entity Framework and NoTracking

How do I revert back to an OpenWrt router configuration?

Some addition to previous comments: 'firstboot' won't be available until you run 'mount_root' command.

So here is a full recap of what needs to be done. All manipulations I did on Windows 8.1.

  • Enter Failsafe mode (hold the reset button on boot for a few seconds)
  • Assign a static IP address, 192.168.1.2, to your PC. Example of a command: netsh interface ip set address name="Ethernet" static 192.168.1.2 255.255.255.0 192.168.1.1
  • Connect to address 192.168.1.1 from telnet (I use PuTTY) and login/password isn't required).
  • Run 'mount_root' (otherwise 'firstboot' won't be available).
  • Run 'firstboot' to reset.
  • Run 'reboot -f' to reboot.

Now you can enter to the router console from a browser. Also don't forget to return your PC from static to DHCP address assignment. Example: netsh interface ip set address name="Ethernet" source=dhcp

How should I do integer division in Perl?

Integer division $x divided by $y ...

$z = -1 & $x / $y

How does it work?

$x / $y

return the floating point division

&

perform a bit-wise AND

-1

stands for

&HFFFFFFFF

for the largest integer ... whence

$z = -1 & $x / $y

gives the integer division ...

Force download a pdf link using javascript/ajax/jquery

Using Javascript you can download like this in a simple method

var oReq = new XMLHttpRequest();
// The Endpoint of your server 
var URLToPDF = "https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf";
// Configure XMLHttpRequest
oReq.open("GET", URLToPDF, true);

// Important to use the blob response type
oReq.responseType = "blob";

// When the file request finishes
// Is up to you, the configuration for error events etc.
oReq.onload = function() {
// Once the file is downloaded, open a new window with the PDF
// Remember to allow the POP-UPS in your browser
var file = new Blob([oReq.response], { 
    type: 'application/pdf' 
});

// Generate file download directly in the browser !
saveAs(file, "mypdffilename.pdf");
};

oReq.send();

What's the difference between a POST and a PUT HTTP REQUEST?

HTTP PUT:

PUT puts a file or resource at a specific URI, and exactly at that URI. If there's already a file or resource at that URI, PUT replaces that file or resource. If there is no file or resource there, PUT creates one. PUT is idempotent, but paradoxically PUT responses are not cacheable.

HTTP 1.1 RFC location for PUT

HTTP POST:

POST sends data to a specific URI and expects the resource at that URI to handle the request. The web server at this point can determine what to do with the data in the context of the specified resource. The POST method is not idempotent, however POST responses are cacheable so long as the server sets the appropriate Cache-Control and Expires headers.

The official HTTP RFC specifies POST to be:

  • Annotation of existing resources;
  • Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
  • Providing a block of data, such as the result of submitting a form, to a data-handling process;
  • Extending a database through an append operation.

HTTP 1.1 RFC location for POST

Difference between POST and PUT:

The RFC itself explains the core difference:

The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI, it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.

Additionally, and a bit more concisely, RFC 7231 Section 4.3.4 PUT states (emphasis added),

4.3.4. PUT

The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload.

Using the right method, unrelated aside:

One benefit of REST ROA vs SOAP is that when using HTTP REST ROA, it encourages the proper usage of the HTTP verbs/methods. So for example you would only use PUT when you want to create a resource at that exact location. And you would never use GET to create or modify a resource.

How to get the first and last date of the current year?

The best way to get First Date and Last Date of a year Is

SELECT CAST(CAST(YEAR(DATEADD(YEAR,-1,GETDATE())) AS VARCHAR) + '-' + '01' + '-' + '01' AS DATE) FIRST_DATE
SELECT CAST(CAST(YEAR(DATEADD(YEAR,-1,GETDATE())) AS VARCHAR) + '-' + '12' + '-' + '31' AS DATE) LAST_DATE

Can you append strings to variables in PHP?

This is because PHP uses the period character . for string concatenation, not the plus character +. Therefore to append to a string you want to use the .= operator:

for ($i=1;$i<=100;$i++)
{
    $selectBox .= '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox .= '</select>';

"This SqlTransaction has completed; it is no longer usable."... configuration error?

For what it's worth, I've run into this on what was previously working code. I had added SELECT statements in a trigger for debug testing and forgot to remove them. Entity Framework / MVC doesnt play nice when other stuff is output to the "grid". Make sure to check for any rogue queries and remove them.

Creating a jQuery object from a big HTML-string

As of jQuery 1.8 you can just use parseHtml to create your jQuery object:

var myString = "<div>Some stuff<div>Some more stuff<span id='theAnswer'>The stuff I am looking for</span></div></div>";
var $jQueryObject = $($.parseHTML(myString));

I've created a JSFidle that demonstrates this: http://jsfiddle.net/MCSyr/2/

It parses the arbitrary HTML string into a jQuery object, and uses find to display the result in a div.

Make Bootstrap's Carousel both center AND responsive?

This work for me very simple just add attribute align="center". Tested on Bootstrap 4.

<!-- The slideshow -->
            <div class="carousel-inner" align="center">             
                <div class="carousel-item active">
                    <img src="image1.jpg" alt="no image" height="550">
                </div>
                <div class="carousel-item">
                    <img src="image2.jpg" alt="no image" height="550">
                </div>                
                <div class="carousel-item">
                    <img src="image3.png" alt="no image" height="550">
                </div>
             </div>

How do I find out what type each object is in a ArrayList<Object>?

You almost never want you use something like:

Object o = ...
if (o.getClass().equals(Foo.class)) {
    ...
}

because you aren't accounting for possible subclasses. You really want to use Class#isAssignableFrom:

Object o = ...
if (Foo.class.isAssignableFrom(o)) {
    ...
}

How can I serve static html from spring boot?

I had to add thymeleaf dependency to pom.xml. Without this dependency Spring boot didn't find static resources.

 <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Get refresh token google api

If I may expand on user987361's answer:

From the offline access portion of the OAuth2.0 docs:

When your application receives a refresh token, it is important to store that refresh token for future use. If your application loses the refresh token, it will have to re-prompt the user for consent before obtaining another refresh token. If you need to re-prompt the user for consent, include the approval_prompt parameter in the authorization code request, and set the value to force.

So, when you have already granted access, subsequent requests for a grant_type of authorization_code will not return the refresh_token, even if access_type was set to offline in the query string of the consent page.

As stated in the quote above, in order to obtain a new refresh_token after already receiving one, you will need to send your user back through the prompt, which you can do by setting approval_prompt to force.

Cheers,

PS This change was announced in a blog post as well.

Running bash script from within python

Adding an answer because I was directed here after asking how to run a bash script from python. You receive an error OSError: [Errno 2] file not found if your script takes in parameters. Lets say for instance your script took in a sleep time parameter: subprocess.call("sleep.sh 10") will not work, you must pass it as an array: subprocess.call(["sleep.sh", 10])

Does JavaScript have the interface type (such as Java's 'interface')?

I know this is an old one, but I've recently found myself needing more and more to have a handy API for checking objects against interfaces. So I wrote this: https://github.com/tomhicks/methodical

It's also available via NPM: npm install methodical

It basically does everything suggested above, with some options for being a bit more strict, and all without having to do loads of if (typeof x.method === 'function') boilerplate.

Hopefully someone finds it useful.

Best practices to test protected methods with PHPUnit

teastburn has the right approach. Even simpler is to call the method directly and return the answer:

class PHPUnitUtil
{
  public static function callMethod($obj, $name, array $args) {
        $class = new \ReflectionClass($obj);
        $method = $class->getMethod($name);
        $method->setAccessible(true);
        return $method->invokeArgs($obj, $args);
    }
}

You can call this simply in your tests by:

$returnVal = PHPUnitUtil::callMethod(
                $this->object,
                '_nameOfProtectedMethod', 
                array($arg1, $arg2)
             );

What to put in a python module docstring?

To quote the specifications:

The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.

The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object's docstring.) The docstring for a package (i.e., the docstring of the package's __init__.py module) should also list the modules and subpackages exported by the package.

The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its __init__ method. Individual methods should be documented by their own docstring.

The docstring of a function or method is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...". A multiline-docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.

Permissions error when connecting to EC2 via SSH on Mac OSx

In my case it's because the permission for my home directory is 775, and SSH is not happy about it. It should work after executing:

server$ chmod go-w ~/
server$ chmod 700 ~/.ssh
server$ chmod 600 ~/.ssh/authorized_keys

I had very similar experience this afternoon. I was setting up django on EC2, and suddenly I cannot SSH into the box anymore. Glad I still had an active connection, so I modified /etc/ssh/sshd_config to set:

PasswordAuthentication yes

and set password for ec2-user, then I can login by entering the password.

However, after some googling I found this thread: http://ubuntuforums.org/showthread.php?t=577279. It turned out that during my setup of django I changed the permission for my home directory, and SSH is very strict about this. So the file permission must be set correctly.

SQL: how to select a single id ("row") that meets multiple criteria from a single column

Try this:

Select user_id
from yourtable
where ancestry in ('England', 'France', 'Germany')
group by user_id
having count(user_id) = 3

The last line means the user's ancestry has all 3 countries.

Get full query string in C# ASP.NET

just a moment ago, i came across with the same issue. and i resolve it in the following manner.

Response.Redirect("../index.aspx?Name="+this.textName.Text+"&LastName="+this.textlName.Text);

with reference to the this

Detect when an HTML5 video finishes

Here is a simple approach which triggers when the video ends.

<html>
<body>

    <video id="myVideo" controls="controls">
        <source src="video.mp4" type="video/mp4">
        etc ...
    </video>

</body>
<script type='text/javascript'>

    document.getElementById('myVideo').addEventListener('ended', function(e) {

        alert('The End');

    })

</script>
</html> 

In the 'EventListener' line substitute the word 'ended' with 'pause' or 'play' to capture those events as well.

How do I script a "yes" response for installing programs?

echo y | command should work.

Also, some installers have an "auto-yes" flag. It's -y for apt-get on Ubuntu.

What does the 'b' character do in front of a string literal?

To quote the Python 2.x documentation:

A prefix of 'b' or 'B' is ignored in Python 2; it indicates that the literal should become a bytes literal in Python 3 (e.g. when code is automatically converted with 2to3). A 'u' or 'b' prefix may be followed by an 'r' prefix.

The Python 3 documentation states:

Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.

Convert array of integers to comma-separated string

.NET 4

string.Join(",", arr)

.NET earlier

string.Join(",", Array.ConvertAll(arr, x => x.ToString()))

Sending emails with Javascript

If this is just going to open up the user's client to send the email, why not let them compose it there as well. You lose the ability to track what they are sending, but if that's not important, then just collect the addresses and subject and pop up the client to let the user fill in the body.

Open a file with Notepad in C#

You can use Process.Start, calling notepad.exe with the file as a parameter.

 Process.Start(@"notepad.exe", pathToFile);

How to check Django version

Simply type python -m django --version or type pip freeze to see all the versions of installed modules including Django.

Count number of rows within each group

There are plenty of wonderful answers here already, but I wanted to throw in 1 more option for those wanting to add a new column to the original dataset that contains the number of times that row is repeated.

df1$counts <- sapply(X = paste(df1$Year, df1$Month), 
                     FUN = function(x) { sum(paste(df1$Year, df1$Month) == x) })

The same could be accomplished by combining any of the above answers with the merge() function.

How do I configure Apache 2 to run Perl CGI scripts?

This post is intended to rescue the people who are suffering from *not being able to properly setup Apache2 for Perl on Ubuntu. (The system configurations specific to your Linux machine will be mentioned within square brackets, like [this]).

Possible outcome of an improperly setup Apache 2:

  1. Browser trying to download the .pl file instead of executing and giving out the result.
  2. Forbidden.
  3. Internal server error.

If one follows the steps described below with a reasonable intelligence, he/she can get through the errors mentioned above.

Before starting the steps. Go to /etc/hosts file and add IP address / domain-name` for example:

127.0.0.1 www.BECK.com

Step 1: Install apache2 Step 2: Install mod_perl Step 3: Configure apache2

open sites-available/default and add the following,

<Files ~ "\.(pl|cgi)$">
    SetHandler perl-script
    PerlResponseHandler ModPerl::PerlRun
    Options +ExecCGI
    PerlSendHeader On
</Files>

<Directory />
    Options FollowSymLinks
    AllowOverride None
</Directory>
<Directory [path-to-store-your-website-files-like-.html-(perl-scripts-should-be-stored-in-cgi-bin] >
####(The Perl/CGI scripts can be stored out of the cgi-bin directory, but that's a story for another day. Let's concentrate on washing out the issue at hand)
####
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

ScriptAlias /cgi-bin/ [path-where-you-want-your-.pl-and-.cgi-files]

<Directory [path-where-you-want-your-.pl-and-.cgi-files]>
    AllowOverride None
    Options ExecCGI -MultiViews +SymLinksIfOwnerMatch
    AddHandler cgi-script .pl
    Order allow,deny
    allow from all
</Directory>
<Files ~ "\.(pl|cgi)$">
    SetHandler perl-script
    PerlResponseHandler ModPerl::PerlRun
    Options +ExecCGI
    PerlSendHeader On
</Files>

<Directory />
    Options FollowSymLinks
    AllowOverride None
</Directory>
<Directory [path-to-store-your-website-files-like-.html-(perl-scripts-should-be-stored-in-cgi-bin] >
####(The Perl/CGI scripts can be stored out of the cgi-bin directory, but that's a story for another day. Let's concentrate on washing out the issue at hand)
####
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

ScriptAlias /cgi-bin/ [path-where-you-want-your-.pl-and-.cgi-files]

<Directory [path-where-you-want-your-.pl-and-.cgi-files]>
    AllowOverride None
    Options ExecCGI -MultiViews +SymLinksIfOwnerMatch
    AddHandler cgi-script .pl
    Order allow,deny
    allow from all
</Directory>

Step 4:

Add the following lines to your /etc/apache2/apache2.conf file.

AddHandler cgi-script .cgi .pl
<Files ~ "\.pl$">
Options +ExecCGI
</Files>
<Files ~ "\.cgi$">
Options +ExecCGI
</Files>

<IfModule mod_perl.c>
<IfModule mod_alias.c>
Alias /perl/ /home/sly/host/perl/
</IfModule>
<Location /perl>
SetHandler perl-script
PerlHandler Apache::Registry
Options +ExecCGI
</Location>
</IfModule>

<Files ~ "\.pl$">
Options +ExecCGI
</Files>

Step 5:

Very important, or at least I guess so, only after doing this step, I got it to work.

AddHandler cgi-script .cgi .pl

<Files ~ "\.pl$">
Options +ExecCGI
</Files>
<Files ~ "\.cgi$">
Options +ExecCGI
</Files>

<IfModule mod_perl.c>
<IfModule mod_alias.c>
Alias /perl/ /home/sly/host/perl/
</IfModule>
<Location /perl>
SetHandler perl-script
PerlHandler Apache::Registry
Options +ExecCGI
</Location>
</IfModule>

<Files ~ "\.pl$">
Options +ExecCGI
</Files>

Step 6

Very important, or at least I guess so, only after doing this step, I got it to work.

Add the following to you /etc/apache2/sites-enabled/000-default file

<Files ~ "\.(pl|cgi)$">
SetHandler perl-script
PerlResponseHandler ModPerl::PerlRun
Options +ExecCGI
PerlSendHeader On
</Files>

Step 7:

Now add, your Perl script as test.pl in the place where you mentioned before in step 3 as [path-where-you-want-your-.pl-and-.cgi-files].

Give permissions to the .pl file using chmod and then, type the webaddress/cgi-bin/test.pl in the address bar of the browser, there you go, you got it.

(Now, many of the things would have been redundant in this post. Kindly ignore it.)

A simple scenario using wait() and notify() in java

Not a queue example, but extremely simple :)

class MyHouse {
    private boolean pizzaArrived = false;

    public void eatPizza(){
        synchronized(this){
            while(!pizzaArrived){
                wait();
            }
        }
        System.out.println("yumyum..");
    }

    public void pizzaGuy(){
        synchronized(this){
             this.pizzaArrived = true;
             notifyAll();
        }
    }
}

Some important points:
1) NEVER do

 if(!pizzaArrived){
     wait();
 }

Always use while(condition), because

  • a) threads can sporadically awake from waiting state without being notified by anyone. (even when the pizza guy didn't ring the chime, somebody would decide try eating the pizza.).
  • b) You should check for the condition again after acquiring the synchronized lock. Let's say pizza don't last forever. You awake, line-up for the pizza, but it's not enough for everybody. If you don't check, you might eat paper! :) (probably better example would be while(!pizzaExists){ wait(); }.

2) You must hold the lock (synchronized) before invoking wait/nofity. Threads also have to acquire lock before waking.

3) Try to avoid acquiring any lock within your synchronized block and strive to not invoke alien methods (methods you don't know for sure what they are doing). If you have to, make sure to take measures to avoid deadlocks.

4) Be careful with notify(). Stick with notifyAll() until you know what you are doing.

5)Last, but not least, read Java Concurrency in Practice!

Check if element is clickable in Selenium Java

There are instances when element.isDisplayed() && element.isEnabled() will return true but still element will not be clickable, because it is hidden/overlapped by some other element.

In such case, Exception caught is:

org.openqa.selenium.WebDriverException: unknown error: Element is not clickable at point (781, 704). Other element would receive the click: <div class="footer">...</div>

Use this code instead:

WebElement  element=driver.findElement(By.xpath"");  
JavascriptExecutor ex=(JavascriptExecutor)driver;
ex.executeScript("arguments[0].click()", element);

It will work.

Receive JSON POST with PHP

Read the doc:

In general, php://input should be used instead of $HTTP_RAW_POST_DATA.

as in the php Manual

Calculating time difference between 2 dates in minutes

Try this one:

select * from MyTab T where date_add(T.runTime, INTERVAL 20 MINUTE) < NOW()

NOTE: this should work if you're using MySQL DateTime format. If you're using Unix Timestamp (integer), then it would be even easier:

select * from MyTab T where UNIX_TIMESTAMP() - T.runTime > 20*60

UNIX_TIMESTAMP() function returns you current unix timestamp.

Resize command prompt through commands

If you want to run a .bat file in full screen, right click on the "example.bat" and click create shortcut, then right click on the shortcut and click properties, then click layout, in layout you can adjust your file to the screen manually, however you can only run it this way if you use the shortcut. You can also change font size by clicking font instead of layout, select lucida and adjust the font size then click apply

array filter in python?

>>> A           = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A  = [6, 9, 12];
>>> set(A) - set(subset_of_A)
set([8, 10, 11, 7])
>>> 

IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

I've solved it, doing the following steps:

  1. I created a new application's group in IIS.
  2. Open advanced settings for the site or web application that is having this problem.
  3. And set the new application's group.

Here you have the images of these steps:

Create a new application's group

After you create the application's group

Set the application group in your site or web app

Integer ASCII value to character in BASH using printf

One line

printf "\x$(printf %x 65)"

Two lines

set $(printf %x 65)
printf "\x$1"

Here is one if you do not mind using awk

awk 'BEGIN{printf "%c", 65}'

How to upgrade scikit-learn package in anaconda

If you are using Jupyter in anaconda, after conda update scikit-learn in terminal, close anaconda and restart, otherwise the error will occur again.

In PowerShell, how can I test if a variable holds a numeric value?

You can do something like :

$testvar -match '^[0-9]+$'

or

$testvar -match '^\d+$'

Returns True if $testvar is a number.

How to display HTML tags as plain text

you may use htmlspecialchars()

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // &lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;
?>

Is there an Eclipse plugin to run system shell in the Console?

I wrote this to get a native shell...it uses the same GTK widget the gnome-terminal uses so the behavior should be nearly identical.

http://github.com/maihde/Eclipse-Terminal

Best way in asp.net to force https for an entire site?

This is a fuller answer based on @Troy Hunt's. Add this function to your WebApplication class in Global.asax.cs:

    protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        // Allow https pages in debugging
        if (Request.IsLocal)
        {
            if (Request.Url.Scheme == "http")
            {
                int localSslPort = 44362; // Your local IIS port for HTTPS

                var path = "https://" + Request.Url.Host + ":" + localSslPort + Request.Url.PathAndQuery;

                Response.Status = "301 Moved Permanently";
                Response.AddHeader("Location", path);
            }
        }
        else
        {
            switch (Request.Url.Scheme)
            {
                case "https":
                    Response.AddHeader("Strict-Transport-Security", "max-age=31536000");
                    break;
                case "http":
                    var path = "https://" + Request.Url.Host + Request.Url.PathAndQuery;
                    Response.Status = "301 Moved Permanently";
                    Response.AddHeader("Location", path);
                    break;
            }
        }
    }

(To enable SSL on your local build enable it in the Properties dock for the project)

Simple Random Samples from a Sql database

There's a very interesting discussion of this type of issue here: http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/

I think with absolutely no assumptions about the table that your O(n lg n) solution is the best. Though actually with a good optimizer or a slightly different technique the query you list may be a bit better, O(m*n) where m is the number of random rows desired, as it wouldn't necesssarily have to sort the whole large array, it could just search for the smallest m times. But for the sort of numbers you posted, m is bigger than lg n anyway.

Three asumptions we might try out:

  1. there is a unique, indexed, primary key in the table

  2. the number of random rows you want to select (m) is much smaller than the number of rows in the table (n)

  3. the unique primary key is an integer that ranges from 1 to n with no gaps

With only assumptions 1 and 2 I think this can be done in O(n), though you'll need to write a whole index to the table to match assumption 3, so it's not necesarily a fast O(n). If we can ADDITIONALLY assume something else nice about the table, we can do the task in O(m log m). Assumption 3 would be an easy nice additional property to work with. With a nice random number generator that guaranteed no duplicates when generating m numbers in a row, an O(m) solution would be possible.

Given the three assumptions, the basic idea is to generate m unique random numbers between 1 and n, and then select the rows with those keys from the table. I don't have mysql or anything in front of me right now, so in slightly pseudocode this would look something like:


create table RandomKeys (RandomKey int)
create table RandomKeysAttempt (RandomKey int)

-- generate m random keys between 1 and n
for i = 1 to m
  insert RandomKeysAttempt select rand()*n + 1

-- eliminate duplicates
insert RandomKeys select distinct RandomKey from RandomKeysAttempt

-- as long as we don't have enough, keep generating new keys,
-- with luck (and m much less than n), this won't be necessary
while count(RandomKeys) < m
  NextAttempt = rand()*n + 1
  if not exists (select * from RandomKeys where RandomKey = NextAttempt)
    insert RandomKeys select NextAttempt

-- get our random rows
select *
from RandomKeys r
join table t ON r.RandomKey = t.UniqueKey

If you were really concerned about efficiency, you might consider doing the random key generation in some sort of procedural language and inserting the results in the database, as almost anything other than SQL would probably be better at the sort of looping and random number generation required.

How to replace � in a string

Use the unicode escape sequence. First you'll have to find the codepoint for the character you seek to replace (let's just say it is ABCD in hex):

str = str.replaceAll("\uABCD", "");

Pythonically add header to a csv file

This worked for me.

header = ['row1', 'row2', 'row3']
some_list = [1, 2, 3]
with open('test.csv', 'wt', newline ='') as file:
    writer = csv.writer(file, delimiter=',')
    writer.writerow(i for i in header)
    for j in some_list:
        writer.writerow(j)

Using multiple property files (via PropertyPlaceholderConfigurer) in multiple projects/modules

If you ensure that every place holder, in each of the contexts involved, is ignoring unresolvable keys then both of these approaches work. For example:

<context:property-placeholder
location="classpath:dao.properties,
          classpath:services.properties,
          classpath:user.properties"
ignore-unresolvable="true"/>

or

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:dao.properties</value>
                <value>classpath:services.properties</value>
                <value>classpath:user.properties</value>
            </list>
        </property> 
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
    </bean>

Importing lodash into angular2 + typescript application

I successfully imported lodash in my project with the following commands:

npm install lodash --save
typings install lodash --save

Then i imported it in the following way:

import * as _ from 'lodash';

and in systemjs.config.js i defined this:

map: { 'lodash' : 'node_modules/lodash/lodash.js' }

Change background of LinearLayout in Android

Use this code, where li is the LinearLayout: li.setBackgroundColor(Color.parseColor("#ffff00"));

How to dynamically add a class to manual class names?

A simple possible syntax will be:

<div className={`wrapper searchDiv ${this.state.something}`}>

MVC pattern on Android

According to the explanation that the Xamarin team explained (on the iOS MVC "I know it seems weird, but wait a second"):

  • The model (data or application logic),
  • The view (user interface), and
  • The controller (code behind).

I can say this:

The model on Android is simply the parcelable object. The view is the XML layout, and the controller is the (activity + its fragment).

*This is just my opinion, not from any resource or a book.

How do I loop through or enumerate a JavaScript object?

In ECMAScript 5 you have new approach in iteration fields of literal - Object.keys

More information you can see on MDN

My choice is below as a faster solution in current versions of browsers (Chrome30, IE10, FF25)

var keys = Object.keys(p),
    len = keys.length,
    i = 0,
    prop,
    value;
while (i < len) {
    prop = keys[i];
    value = p[prop];
    i += 1;
}

You can compare performance of this approach with different implementations on jsperf.com:

Browser support you can see on Kangax's compat table

For old browser you have simple and full polyfill

UPD:

performance comparison for all most popular cases in this question on perfjs.info:

object literal iteration

twitter bootstrap typeahead ajax example

To those looking for a coffeescript version of the accepted answer:

$(".typeahead").typeahead source: (query, process) ->
  $.get "/typeahead",
    query: query
  , (data) ->
    process data.options

bash echo number of lines of file given in a bash variable without the file name

wc can't get the filename if you don't give it one.

wc -l < "$JAVA_TAGS_FILE"

Replacing &nbsp; from javascript dom text node

If you only need to replace &nbsp; then you can use a far simpler regex:

var textWithNBSpaceReplaced = originalText.replace(/&nbsp;/g, ' ');

Also, there is a typo in your div example, it says &nnbsp; instead of &nbsp;.

How do you get a directory listing in C?

GLib is a portability/utility library for C which forms the basis of the GTK+ graphical toolkit. It can be used as a standalone library.

It contains portable wrappers for managing directories. See Glib File Utilities documentation for details.

Personally, I wouldn't even consider writing large amounts of C-code without something like GLib behind me. Portability is one thing, but it's also nice to get data structures, thread helpers, events, mainloops etc. for free

Jikes, I'm almost starting to sound like a sales guy :) (don't worry, glib is open source (LGPL) and I'm not affiliated with it in any way)

jQuery 'each' loop with JSON array

This works for me:

$.get("data.php", function(data){
    var expected = ['justIn', 'recent', 'old'];
    var outString = '';
    $.each(expected, function(i, val){
        var contentArray = data[val];
        outString += '<ul><li><b>' + val + '</b>: ';
        $.each(contentArray, function(i1, val2){
            var textID = val2.textId;
            var text = val2.text;
            var textType = val2.textType;
            outString += '<br />('+textID+') '+'<i>'+text+'</i> '+textType;
        });
        outString += '</li></ul>';
    });
    $('#contentHere').append(outString);
}, 'json');

This produces this output:

<div id="contentHere"><ul>
<li><b>justIn</b>:
<br />
(123) <i>Hello</i> Greeting<br>
(514) <i>What's up?</i> Question<br>
(122) <i>Come over here</i> Order</li>
</ul><ul>
<li><b>recent</b>:
<br />
(1255) <i>Hello</i> Greeting<br>
(6564) <i>What's up?</i> Question<br>
(0192) <i>Come over here</i> Order</li>
</ul><ul>
<li><b>old</b>:
<br />
(5213) <i>Hello</i> Greeting<br>
(9758) <i>What's up?</i> Question<br>
(7655) <i>Come over here</i> Order</li>
</ul></div>

And looks like this:

  • justIn:
    (123) Hello Greeting
    (514) What's up? Question
    (122) Come over here Order
  • recent:
    (1255) Hello Greeting
    (6564) What's up? Question
    (0192) Come over here Order
  • old:
    (5213) Hello Greeting
    (9758) What's up? Question
    (7655) Come over here Order

Also, remember to set the contentType as 'json'

Google Map API v3 ~ Simply Close an infowindow?

The following event listener solved this nicely for me even when using multiple markers and info windows:

//Add click event listener
google.maps.event.addListener(marker, 'click', function() {
  // Helper to check if the info window is already open
  google.maps.InfoWindow.prototype.isOpen = function(){
      var map = infoWindow.getMap();
      return (map !== null && typeof map !== "undefined");
  }
  // Do the check
  if (infoWindow.isOpen()){
    // Close the info window
    infoWindow.close();
  } else {
    //Set the new content
    infoWindow.setContent(contentString);
    //Open the infowindow
    infoWindow.open(map, marker);
  }
});

How to add `style=display:"block"` to an element using jQuery?

There are multiple function to do this work that wrote in bottom based on priority.

Set one or more CSS properties for the set of matched elements.

$("div").css("display", "block")
// Or add multiple CSS properties
$("div").css({
  display: "block",
  color: "red",
  ...
})

Display the matched elements and is roughly equivalent to calling .css("display", "block")

You can display element using .show() instead

$("div").show()

Set one or more attributes for the set of matched elements.

If target element hasn't style attribute, you can use this method to add inline style to element.

$("div").attr("style", "display:block")
// Or add multiple CSS properties
$("div").attr("style", "display:block; color:red")

  • JavaScript

You can add specific CSS property to element using pure javascript, if you don't want to use jQuery.

var div = document.querySelector("div");
// One property
div.style.display = "block";
// Multiple properties
div.style.cssText = "display:block; color:red"; 
// Multiple properties
div.setAttribute("style", "display:block; color:red");

How to resolve symbolic links in a shell script

Since I've run into this many times over the years, and this time around I needed a pure bash portable version that I could use on OSX and linux, I went ahead and wrote one:

The living version lives here:

https://github.com/keen99/shell-functions/tree/master/resolve_path

but for the sake of SO, here's the current version (I feel it's well tested..but I'm open to feedback!)

Might not be difficult to make it work for plain bourne shell (sh), but I didn't try...I like $FUNCNAME too much. :)

#!/bin/bash

resolve_path() {
    #I'm bash only, please!
    # usage:  resolve_path <a file or directory> 
    # follows symlinks and relative paths, returns a full real path
    #
    local owd="$PWD"
    #echo "$FUNCNAME for $1" >&2
    local opath="$1"
    local npath=""
    local obase=$(basename "$opath")
    local odir=$(dirname "$opath")
    if [[ -L "$opath" ]]
    then
    #it's a link.
    #file or directory, we want to cd into it's dir
        cd $odir
    #then extract where the link points.
        npath=$(readlink "$obase")
        #have to -L BEFORE we -f, because -f includes -L :(
        if [[ -L $npath ]]
         then
        #the link points to another symlink, so go follow that.
            resolve_path "$npath"
            #and finish out early, we're done.
            return $?
            #done
        elif [[ -f $npath ]]
        #the link points to a file.
         then
            #get the dir for the new file
            nbase=$(basename $npath)
            npath=$(dirname $npath)
            cd "$npath"
            ndir=$(pwd -P)
            retval=0
            #done
        elif [[ -d $npath ]]
         then
        #the link points to a directory.
            cd "$npath"
            ndir=$(pwd -P)
            retval=0
            #done
        else
            echo "$FUNCNAME: ERROR: unknown condition inside link!!" >&2
            echo "opath [[ $opath ]]" >&2
            echo "npath [[ $npath ]]" >&2
            return 1
        fi
    else
        if ! [[ -e "$opath" ]]
         then
            echo "$FUNCNAME: $opath: No such file or directory" >&2
            return 1
            #and break early
        elif [[ -d "$opath" ]]
         then 
            cd "$opath"
            ndir=$(pwd -P)
            retval=0
            #done
        elif [[ -f "$opath" ]]
         then
            cd $odir
            ndir=$(pwd -P)
            nbase=$(basename "$opath")
            retval=0
            #done
        else
            echo "$FUNCNAME: ERROR: unknown condition outside link!!" >&2
            echo "opath [[ $opath ]]" >&2
            return 1
        fi
    fi
    #now assemble our output
    echo -n "$ndir"
    if [[ "x${nbase:=}" != "x" ]]
     then
        echo "/$nbase"
    else 
        echo
    fi
    #now return to where we were
    cd "$owd"
    return $retval
}

here's a classic example, thanks to brew:

%% ls -l `which mvn`
lrwxr-xr-x  1 draistrick  502  29 Dec 17 10:50 /usr/local/bin/mvn@ -> ../Cellar/maven/3.2.3/bin/mvn

use this function and it will return the -real- path:

%% cat test.sh
#!/bin/bash
. resolve_path.inc
echo
echo "relative symlinked path:"
which mvn
echo
echo "and the real path:"
resolve_path `which mvn`


%% test.sh

relative symlinked path:
/usr/local/bin/mvn

and the real path:
/usr/local/Cellar/maven/3.2.3/libexec/bin/mvn 

How we can bold only the name in table td tag not the value

Surround what you want to be bold with:

<span style="font-weight:bold">Your bold text</span>

This would go inside your <td> tag.

What is middleware exactly?

Middleware is a terribly nebulous term. What is "middleware" in one case won't be in another. In general, you can expect something classed as middleware to have the following characteristics:

  • Primarily (usually exclusively) software; usually doesn't need any specialized hardware.

  • If it weren't there, applications that depend on it would have to incorporate it as part of their application and would experience a lot of duplication.

  • Almost certainly connects two applications and passes data between them.

You'll notice that this is pretty much the same definition as an operating system. So, for instance, a TCP/IP stack or caching could be considered middleware. But your OS could provide the same features, too. Indeed, middleware can be thought of like a special extension to an operating system, specific to a set of applications that depend on it. It just provides a higher-level service.

Some examples of middleware:

  • distributed cache
  • message queue
  • transaction monitor
  • packet rewriter
  • automated backup system

Rotating a Vector in 3D Space

If you want to rotate a vector you should construct what is known as a rotation matrix.

Rotation in 2D

Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are

    x' = x cos ? - y sin ?
    y' = x sin ? + y cos ?

To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider

    Unit vector along X axis = <1, 0>
    x' = 1 cos 90 - 0 sin 90 = 0
    y' = 1 sin 90 + 0 cos 90 = 1
    New coordinates of the vector, <x', y'> = <0, 1>  ?  Y-axis

When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is

    |cos ?   -sin ?| |x| = |x cos ? - y sin ?| = |x'|
    |sin ?    cos ?| |y|   |x sin ? + y cos ?|   |y'|

Rotation in 3D

That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be

    |cos ?   -sin ?   0| |x|   |x cos ? - y sin ?|   |x'|
    |sin ?    cos ?   0| |y| = |x sin ? + y cos ?| = |y'|
    |  0       0      1| |z|   |        z        |   |z'|

around the Y-axis would be

    | cos ?    0   sin ?| |x|   | x cos ? + z sin ?|   |x'|
    |   0      1       0| |y| = |         y        | = |y'|
    |-sin ?    0   cos ?| |z|   |-x sin ? + z cos ?|   |z'|

around the X-axis would be

    |1     0           0| |x|   |        x        |   |x'|
    |0   cos ?    -sin ?| |y| = |y cos ? - z sin ?| = |y'|
    |0   sin ?     cos ?| |z|   |y sin ? + z cos ?|   |z'|

Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.

Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.

I hope this clarifies basic rotation.

Rotation not Revolution

The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.

Composition

I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).

Rotation around Arbitrary Vector

A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.

using stored procedure in entity framework

Mindless passenger has a project that allows you to call a stored proc from entity frame work like this....

using (testentities te = new testentities())
{
    //-------------------------------------------------------------
    // Simple stored proc
    //-------------------------------------------------------------
    var parms1 = new testone() { inparm = "abcd" };
    var results1 = te.CallStoredProc<testone>(te.testoneproc, parms1);
    var r1 = results1.ToList<TestOneResultSet>();
}

... and I am working on a stored procedure framework (here) which you can call like in one of my test methods shown below...

[TestClass]
public class TenantDataBasedTests : BaseIntegrationTest
{
    [TestMethod]
    public void GetTenantForName_ReturnsOneRecord()
    {
        // ARRANGE
        const int expectedCount = 1;
        const string expectedName = "Me";

        // Build the paraemeters object
        var parameters = new GetTenantForTenantNameParameters
        {
            TenantName = expectedName
        };

        // get an instance of the stored procedure passing the parameters
        var procedure = new GetTenantForTenantNameProcedure(parameters);

        // Initialise the procedure name and schema from procedure attributes
        procedure.InitializeFromAttributes();

        // Add some tenants to context so we have something for the procedure to return!
        AddTenentsToContext(Context);

        // ACT
        // Get the results by calling the stored procedure from the context extention method 
        var results = Context.ExecuteStoredProcedure(procedure);

        // ASSERT
        Assert.AreEqual(expectedCount, results.Count);
    }
}

internal class GetTenantForTenantNameParameters
{
    [Name("TenantName")]
    [Size(100)]
    [ParameterDbType(SqlDbType.VarChar)]
    public string TenantName { get; set; }
}

[Schema("app")]
[Name("Tenant_GetForTenantName")]
internal class GetTenantForTenantNameProcedure
    : StoredProcedureBase<TenantResultRow, GetTenantForTenantNameParameters>
{
    public GetTenantForTenantNameProcedure(
        GetTenantForTenantNameParameters parameters)
        : base(parameters)
    {
    }
}

If either of those two approaches are any good?

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

os.walk without digging into directories below

Don't use os.walk.

Example:

import os

root = "C:\\"
for item in os.listdir(root):
    if os.path.isfile(os.path.join(root, item)):
        print item

performing HTTP requests with cURL (using PROXY)

From man curl:

-x, --proxy <[protocol://][user:password@]proxyhost[:port]>

     Use the specified HTTP proxy. 
     If the port number is not specified, it is assumed at port 1080.

General way:

export http_proxy=http://your.proxy.server:port/

Then you can connect through proxy from (many) application.

And, as per comment below, for https:

export https_proxy=https://your.proxy.server:port/

Java Read Large Text File With 70million line of text

enter image description hereI actually did a research in this topic for months in my free time and came up with a benchmark and here is a code to benchmark all the different ways to read a File line by line.The individual performance may vary based on the underlying system. I ran on a windows 10 Java 8 Intel i5 HP laptop:Here is the code.

import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.stream.Stream;

public class ReadComplexDelimitedFile {
    private static long total = 0;
    private static final Pattern FIELD_DELIMITER_PATTERN = Pattern.compile("\\^\\|\\^");

    @SuppressWarnings("unused")
    private void readFileUsingScanner() {

        String s;
        try (Scanner stdin = new Scanner(new File(this.getClass().getResource("input.txt").getPath()))) {
            while (stdin.hasNextLine()) {
                s = stdin.nextLine();
                String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
                total = total + fields.length;
            }
        } catch (Exception e) {
            System.err.println("Error");
        }

    }

    //Winner
    private void readFileUsingCustomBufferedReader() {

        try (CustomBufferedReader stdin = new CustomBufferedReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
            String s;
            while ((s = stdin.readLine()) != null) {
                String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
                total += fields.length;
            }
        } catch (Exception e) {
            System.err.println("Error");
        }

    }


    private void readFileUsingBufferedReader() {

        try (BufferedReader stdin = new BufferedReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
            String s;
            while ((s = stdin.readLine()) != null) {
                String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
                total += fields.length;
            }
        } catch (Exception e) {
            System.err.println("Error");
        }
    }

    private void readFileUsingLineReader() {

        try (LineNumberReader stdin = new LineNumberReader(new FileReader(new File(this.getClass().getResource("input.txt").getPath())))) {
            String s;
            while ((s = stdin.readLine()) != null) {
                String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
                total += fields.length;
            }
        } catch (Exception e) {
            System.err.println("Error");
        }
    }

    private void readFileUsingStreams() {

        try (Stream<String> stream = Files.lines((new File(this.getClass().getResource("input.txt").getPath())).toPath())) {
            total += stream.mapToInt(s -> FIELD_DELIMITER_PATTERN.split(s, 0).length).sum();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }


    private void readFileUsingBufferedReaderFileChannel() {
        try (FileInputStream fis = new FileInputStream(this.getClass().getResource("input.txt").getPath())) {
            try (FileChannel inputChannel = fis.getChannel()) {
                try (CustomBufferedReader stdin = new CustomBufferedReader(Channels.newReader(inputChannel, "UTF-8"))) {
                    String s;
                    while ((s = stdin.readLine()) != null) {
                        String[] fields = FIELD_DELIMITER_PATTERN.split(s, 0);
                        total = total + fields.length;
                    }
                }
            } catch (Exception e) {
                System.err.println("Error");
            }
        } catch (Exception e) {
            System.err.println("Error");
        }

    }


    public static void main(String args[]) {
        //JVM wamrup
        for (int i = 0; i < 100000; i++) {
            total += i;
        }
        // We know scanner is slow-Still warming up
        ReadComplexDelimitedFile readComplexDelimitedFile = new ReadComplexDelimitedFile();
        List<Long> longList = new ArrayList<>(50);
        for (int i = 0; i < 50; i++) {
            total = 0;
            long startTime = System.nanoTime();
            //readComplexDelimitedFile.readFileUsingScanner();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingScanner");
        longList.forEach(System.out::println);
        // Actual performance test starts here

        longList = new ArrayList<>(10);
        for (int i = 0; i < 10; i++) {
            total = 0;
            long startTime = System.nanoTime();
            readComplexDelimitedFile.readFileUsingBufferedReaderFileChannel();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingBufferedReaderFileChannel");
        longList.forEach(System.out::println);
        longList.clear();
        for (int i = 0; i < 10; i++) {
            total = 0;
            long startTime = System.nanoTime();
            readComplexDelimitedFile.readFileUsingBufferedReader();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingBufferedReader");
        longList.forEach(System.out::println);
        longList.clear();
        for (int i = 0; i < 10; i++) {
            total = 0;
            long startTime = System.nanoTime();
            readComplexDelimitedFile.readFileUsingStreams();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingStreams");
        longList.forEach(System.out::println);
        longList.clear();
        for (int i = 0; i < 10; i++) {
            total = 0;
            long startTime = System.nanoTime();
            readComplexDelimitedFile.readFileUsingCustomBufferedReader();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingCustomBufferedReader");
        longList.forEach(System.out::println);
        longList.clear();
        for (int i = 0; i < 10; i++) {
            total = 0;
            long startTime = System.nanoTime();
            readComplexDelimitedFile.readFileUsingLineReader();
            long stopTime = System.nanoTime();
            long timeDifference = stopTime - startTime;
            longList.add(timeDifference);

        }
        System.out.println("Time taken for readFileUsingLineReader");
        longList.forEach(System.out::println);

    }
}

I had to rewrite BufferedReader to avoid synchronized and a couple of boundary conditions that is not needed.(Atleast that's what I felt.It is not unit tested so use it at your own risk.)

import com.sun.istack.internal.NotNull;

import java.io.*;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
 * Reads text from a character-input stream, buffering characters so as to
 * provide for the efficient reading of characters, arrays, and lines.
 * <p>
 * <p> The buffer size may be specified, or the default size may be used.  The
 * default is large enough for most purposes.
 * <p>
 * <p> In general, each read request made of a Reader causes a corresponding
 * read request to be made of the underlying character or byte stream.  It is
 * therefore advisable to wrap a CustomBufferedReader around any Reader whose read()
 * operations may be costly, such as FileReaders and InputStreamReaders.  For
 * example,
 * <p>
 * <pre>
 * CustomBufferedReader in
 *   = new CustomBufferedReader(new FileReader("foo.in"));
 * </pre>
 * <p>
 * will buffer the input from the specified file.  Without buffering, each
 * invocation of read() or readLine() could cause bytes to be read from the
 * file, converted into characters, and then returned, which can be very
 * inefficient.
 * <p>
 * <p> Programs that use DataInputStreams for textual input can be localized by
 * replacing each DataInputStream with an appropriate CustomBufferedReader.
 *
 * @author Mark Reinhold
 * @see FileReader
 * @see InputStreamReader
 * @see java.nio.file.Files#newBufferedReader
 * @since JDK1.1
 */

public class CustomBufferedReader extends Reader {

    private final Reader in;

    private char cb[];
    private int nChars, nextChar;

    private static final int INVALIDATED = -2;
    private static final int UNMARKED = -1;
    private int markedChar = UNMARKED;
    private int readAheadLimit = 0; /* Valid only when markedChar > 0 */

    /**
     * If the next character is a line feed, skip it
     */
    private boolean skipLF = false;

    /**
     * The skipLF flag when the mark was set
     */
    private boolean markedSkipLF = false;

    private static int defaultCharBufferSize = 8192;
    private static int defaultExpectedLineLength = 80;
    private ReadWriteLock rwlock;


    /**
     * Creates a buffering character-input stream that uses an input buffer of
     * the specified size.
     *
     * @param in A Reader
     * @param sz Input-buffer size
     * @throws IllegalArgumentException If {@code sz <= 0}
     */
    public CustomBufferedReader(@NotNull final Reader in, int sz) {
        super(in);
        if (sz <= 0)
            throw new IllegalArgumentException("Buffer size <= 0");
        this.in = in;
        cb = new char[sz];
        nextChar = nChars = 0;
        rwlock = new ReentrantReadWriteLock();
    }

    /**
     * Creates a buffering character-input stream that uses a default-sized
     * input buffer.
     *
     * @param in A Reader
     */
    public CustomBufferedReader(@NotNull final Reader in) {
        this(in, defaultCharBufferSize);
    }


    /**
     * Fills the input buffer, taking the mark into account if it is valid.
     */
    private void fill() throws IOException {
        int dst;
        if (markedChar <= UNMARKED) {
            /* No mark */
            dst = 0;
        } else {
            /* Marked */
            int delta = nextChar - markedChar;
            if (delta >= readAheadLimit) {
                /* Gone past read-ahead limit: Invalidate mark */
                markedChar = INVALIDATED;
                readAheadLimit = 0;
                dst = 0;
            } else {
                if (readAheadLimit <= cb.length) {
                    /* Shuffle in the current buffer */
                    System.arraycopy(cb, markedChar, cb, 0, delta);
                    markedChar = 0;
                    dst = delta;
                } else {
                    /* Reallocate buffer to accommodate read-ahead limit */
                    char ncb[] = new char[readAheadLimit];
                    System.arraycopy(cb, markedChar, ncb, 0, delta);
                    cb = ncb;
                    markedChar = 0;
                    dst = delta;
                }
                nextChar = nChars = delta;
            }
        }

        int n;
        do {
            n = in.read(cb, dst, cb.length - dst);
        } while (n == 0);
        if (n > 0) {
            nChars = dst + n;
            nextChar = dst;
        }
    }

    /**
     * Reads a single character.
     *
     * @return The character read, as an integer in the range
     * 0 to 65535 (<tt>0x00-0xffff</tt>), or -1 if the
     * end of the stream has been reached
     * @throws IOException If an I/O error occurs
     */
    public char readChar() throws IOException {
        for (; ; ) {
            if (nextChar >= nChars) {
                fill();
                if (nextChar >= nChars)
                    return (char) -1;
            }
            return cb[nextChar++];
        }
    }

    /**
     * Reads characters into a portion of an array, reading from the underlying
     * stream if necessary.
     */
    private int read1(char[] cbuf, int off, int len) throws IOException {
        if (nextChar >= nChars) {
            /* If the requested length is at least as large as the buffer, and
               if there is no mark/reset activity, and if line feeds are not
               being skipped, do not bother to copy the characters into the
               local buffer.  In this way buffered streams will cascade
               harmlessly. */
            if (len >= cb.length && markedChar <= UNMARKED && !skipLF) {
                return in.read(cbuf, off, len);
            }
            fill();
        }
        if (nextChar >= nChars) return -1;
        int n = Math.min(len, nChars - nextChar);
        System.arraycopy(cb, nextChar, cbuf, off, n);
        nextChar += n;
        return n;
    }

    /**
     * Reads characters into a portion of an array.
     * <p>
     * <p> This method implements the general contract of the corresponding
     * <code>{@link Reader#read(char[], int, int) read}</code> method of the
     * <code>{@link Reader}</code> class.  As an additional convenience, it
     * attempts to read as many characters as possible by repeatedly invoking
     * the <code>read</code> method of the underlying stream.  This iterated
     * <code>read</code> continues until one of the following conditions becomes
     * true: <ul>
     * <p>
     * <li> The specified number of characters have been read,
     * <p>
     * <li> The <code>read</code> method of the underlying stream returns
     * <code>-1</code>, indicating end-of-file, or
     * <p>
     * <li> The <code>ready</code> method of the underlying stream
     * returns <code>false</code>, indicating that further input requests
     * would block.
     * <p>
     * </ul> If the first <code>read</code> on the underlying stream returns
     * <code>-1</code> to indicate end-of-file then this method returns
     * <code>-1</code>.  Otherwise this method returns the number of characters
     * actually read.
     * <p>
     * <p> Subclasses of this class are encouraged, but not required, to
     * attempt to read as many characters as possible in the same fashion.
     * <p>
     * <p> Ordinarily this method takes characters from this stream's character
     * buffer, filling it from the underlying stream as necessary.  If,
     * however, the buffer is empty, the mark is not valid, and the requested
     * length is at least as large as the buffer, then this method will read
     * characters directly from the underlying stream into the given array.
     * Thus redundant <code>CustomBufferedReader</code>s will not copy data
     * unnecessarily.
     *
     * @param cbuf Destination buffer
     * @param off  Offset at which to start storing characters
     * @param len  Maximum number of characters to read
     * @return The number of characters read, or -1 if the end of the
     * stream has been reached
     * @throws IOException If an I/O error occurs
     */
    public int read(char cbuf[], int off, int len) throws IOException {
        int n = read1(cbuf, off, len);
        if (n <= 0) return n;
        while ((n < len) && in.ready()) {
            int n1 = read1(cbuf, off + n, len - n);
            if (n1 <= 0) break;
            n += n1;
        }
        return n;
    }

    /**
     * Reads a line of text.  A line is considered to be terminated by any one
     * of a line feed ('\n'), a carriage return ('\r'), or a carriage return
     * followed immediately by a linefeed.
     *
     * @param ignoreLF If true, the next '\n' will be skipped
     * @return A String containing the contents of the line, not including
     * any line-termination characters, or null if the end of the
     * stream has been reached
     * @throws IOException If an I/O error occurs
     * @see java.io.LineNumberReader#readLine()
     */
    String readLine(boolean ignoreLF) throws IOException {
        StringBuilder s = null;
        int startChar;



        bufferLoop:
        for (; ; ) {

            if (nextChar >= nChars)
                fill();
            if (nextChar >= nChars) { /* EOF */
                if (s != null && s.length() > 0)
                    return s.toString();
                else
                    return null;
            }
            boolean eol = false;
            char c = 0;
            int i;

            /* Skip a leftover '\n', if necessary */



            charLoop:
            for (i = nextChar; i < nChars; i++) {
                c = cb[i];
                if ((c == '\n')) {
                    eol = true;
                    break charLoop;
                }
            }

            startChar = nextChar;
            nextChar = i;

            if (eol) {
                String str;
                if (s == null) {
                    str = new String(cb, startChar, i - startChar);
                } else {
                    s.append(cb, startChar, i - startChar);
                    str = s.toString();
                }
                nextChar++;
                return str;
            }

            if (s == null)
                s = new StringBuilder(defaultExpectedLineLength);
            s.append(cb, startChar, i - startChar);
        }
    }

    /**
     * Reads a line of text.  A line is considered to be terminated by any one
     * of a line feed ('\n'), a carriage return ('\r'), or a carriage return
     * followed immediately by a linefeed.
     *
     * @return A String containing the contents of the line, not including
     * any line-termination characters, or null if the end of the
     * stream has been reached
     * @throws IOException If an I/O error occurs
     * @see java.nio.file.Files#readAllLines
     */
    public String readLine() throws IOException {
        return readLine(false);
    }

    /**
     * Skips characters.
     *
     * @param n The number of characters to skip
     * @return The number of characters actually skipped
     * @throws IllegalArgumentException If <code>n</code> is negative.
     * @throws IOException              If an I/O error occurs
     */
    public long skip(long n) throws IOException {
        if (n < 0L) {
            throw new IllegalArgumentException("skip value is negative");
        }
        rwlock.readLock().lock();
            long r = n;
            try{
            while (r > 0) {
                if (nextChar >= nChars)
                    fill();
                if (nextChar >= nChars) /* EOF */
                    break;
                if (skipLF) {
                    skipLF = false;
                    if (cb[nextChar] == '\n') {
                        nextChar++;
                    }
                }
                long d = nChars - nextChar;
                if (r <= d) {
                    nextChar += r;
                    r = 0;
                    break;
                } else {
                    r -= d;
                    nextChar = nChars;
                }
            }
        } finally {
            rwlock.readLock().unlock();
        }
        return n - r;
    }

    /**
     * Tells whether this stream is ready to be read.  A buffered character
     * stream is ready if the buffer is not empty, or if the underlying
     * character stream is ready.
     *
     * @throws IOException If an I/O error occurs
     */
    public boolean ready() throws IOException {
        rwlock.readLock().lock();
        try {
            /*
             * If newline needs to be skipped and the next char to be read
             * is a newline character, then just skip it right away.
             */
            if (skipLF) {
                /* Note that in.ready() will return true if and only if the next
                 * read on the stream will not block.
                 */
                if (nextChar >= nChars && in.ready()) {
                    fill();
                }
                if (nextChar < nChars) {
                    if (cb[nextChar] == '\n')
                        nextChar++;
                    skipLF = false;
                }
            }
        } finally {
            rwlock.readLock().unlock();
        }
        return (nextChar < nChars) || in.ready();

    }

    /**
     * Tells whether this stream supports the mark() operation, which it does.
     */
    public boolean markSupported() {
        return true;
    }

    /**
     * Marks the present position in the stream.  Subsequent calls to reset()
     * will attempt to reposition the stream to this point.
     *
     * @param readAheadLimit Limit on the number of characters that may be
     *                       read while still preserving the mark. An attempt
     *                       to reset the stream after reading characters
     *                       up to this limit or beyond may fail.
     *                       A limit value larger than the size of the input
     *                       buffer will cause a new buffer to be allocated
     *                       whose size is no smaller than limit.
     *                       Therefore large values should be used with care.
     * @throws IllegalArgumentException If {@code readAheadLimit < 0}
     * @throws IOException              If an I/O error occurs
     */
    public void mark(int readAheadLimit) throws IOException {
        if (readAheadLimit < 0) {
            throw new IllegalArgumentException("Read-ahead limit < 0");
        }
        rwlock.readLock().lock();
        try {
            this.readAheadLimit = readAheadLimit;
            markedChar = nextChar;
            markedSkipLF = skipLF;
        } finally {
            rwlock.readLock().unlock();
        }
    }

    /**
     * Resets the stream to the most recent mark.
     *
     * @throws IOException If the stream has never been marked,
     *                     or if the mark has been invalidated
     */
    public void reset() throws IOException {
        rwlock.readLock().lock();
        try {
            if (markedChar < 0)
                throw new IOException((markedChar == INVALIDATED)
                        ? "Mark invalid"
                        : "Stream not marked");
            nextChar = markedChar;
            skipLF = markedSkipLF;
        } finally {
            rwlock.readLock().unlock();
        }
    }

    public void close() throws IOException {
        rwlock.readLock().lock();
        try {
            in.close();
        } finally {
            cb = null;
            rwlock.readLock().unlock();
        }

    }

    public Stream<String> lines() {
        Iterator<String> iter = new Iterator<String>() {
            String nextLine = null;

            @Override
            public boolean hasNext() {
                if (nextLine != null) {
                    return true;
                } else {
                    try {
                        nextLine = readLine();
                        return (nextLine != null);
                    } catch (IOException e) {
                        throw new UncheckedIOException(e);
                    }
                }
            }

            @Override
            public String next() {
                if (nextLine != null || hasNext()) {
                    String line = nextLine;
                    nextLine = null;
                    return line;
                } else {
                    throw new NoSuchElementException();
                }
            }
        };
        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
                iter, Spliterator.ORDERED | Spliterator.NONNULL), false);
    }
}

And now the results:

Time taken for readFileUsingBufferedReaderFileChannel 2902690903 1845190694 1894071377 1815161868 1861056735 1867693540 1857521371 1794176251 1768008762 1853089582

Time taken for readFileUsingBufferedReader 2022837353 1925901163 1802266711 1842689572 1899984555 1843101306 1998642345 1821242301 1820168806 1830375108

Time taken for readFileUsingStreams 1992855461 1930827034 1850876033 1843402533 1800378283 1863581324 1810857226 1798497108 1809531144 1796345853

Time taken for readFileUsingCustomBufferedReader 1759732702 1765987214 1776997357 1772999486 1768559162 1755248431 1744434555 1750349867 1740582606 1751390934

Time taken for readFileUsingLineReader 1845307174 1830950256 1829847321 1828125293 1827936280 1836947487 1832186310 1820276327 1830157935 1829171481

Process finished with exit code 0

Inference: The test was run on a 200 MB file. The test was repeated several times. The data looked like this

Start Date^|^Start Time^|^End Date^|^End Time^|^Event Title ^|^All Day Event^|^No End Time^|^Event Description^|^Contact ^|^Contact Email^|^Contact Phone^|^Location^|^Category^|^Mandatory^|^Registration^|^Maximum^|^Last Date To Register
9/5/2011^|^3:00:00 PM^|^9/5/2011^|^^|^Social Studies Dept. Meeting^|^N^|^Y^|^Department meeting^|^Chris Gallagher^|^[email protected]^|^814-555-5179^|^High School^|^2^|^N^|^N^|^25^|^9/2/2011

Bottomline not much difference between BufferedReader and my CustomReader and it is very miniscule and hence you can use this to read your file.

Trust me you don't have to break your head.use BufferedReader with readLine,it is properly tested.At worst if you feel you can improve it just override and change it to StringBuilder instead of StringBuffer just to shave off half a second

How do I undo the most recent local commits in Git?

Undoing a commit is a little scary if you don't know how it works. But it's actually amazingly easy if you do understand. I'll show you the 4 different ways you can undo a commit.

option 1: git reset --hard

Say you have this, where C is your HEAD and (F) is the state of your files.

   (F)
A-B-C
    ?
  master

You want to nuke commit C and never see it again and lose all the changes in locally modified files. You do this:

git reset --hard HEAD~1

The result is:

 (F)
A-B
  ?
master

Now B is the HEAD. Because you used --hard, your files are reset to their state at commit B.

option 2: git reset

Ah, but suppose commit C wasn't a disaster, but just a bit off. You want to undo the commit but keep your changes for a bit of editing before you do a better commit. Starting again from here, with C as your HEAD:

   (F)
A-B-C
    ?
  master

You can do this, leaving off the --hard:

git reset HEAD~1

In this case the result is:

   (F)
A-B-C
  ?
master

In both cases, HEAD is just a pointer to the latest commit. When you do a git reset HEAD~1, you tell Git to move the HEAD pointer back one commit. But (unless you use --hard) you leave your files as they were. So now git status shows the changes you had checked into C. You haven't lost a thing!

option 3: git reset --soft

For the lightest touch, you can even undo your commit but leave your files and your index:

git reset --soft HEAD~1

This not only leaves your files alone, it even leaves your index alone. When you do git status, you'll see that the same files are in the index as before. In fact, right after this command, you could do git commit and you'd be redoing the same commit you just had.

option 4: you did git reset --hard and need to get that code back

One more thing: Suppose you destroy a commit as in the first example, but then discover you needed it after all? Tough luck, right?

Nope, there's still a way to get it back. Type git reflog and you'll see a list of (partial) commit shas (that is, hashes) that you've moved around in. Find the commit you destroyed, and do this:

git checkout -b someNewBranchName shaYouDestroyed

You've now resurrected that commit. Commits don't actually get destroyed in Git for some 90 days, so you can usually go back and rescue one you didn't mean to get rid of.

How to get Time from DateTime format in SQL?

on MSSQL2012 or above

cast(dateadd(ms,datediff(ms, [StartDateTime], [StopDateTime]),0) as Time(0))

...or...

convert(time(0),dateadd(ms,datediff(ms, [StartDateTime], [StopDateTime]),0) )

Writing/outputting HTML strings unescaped

Sometimes it can be tricky to use raw html. Mostly because of XSS vulnerability. If that is a concern, but you still want to use raw html, you can encode the scary parts.

@Html.Raw("(<b>" + Html.Encode("<script>console.log('insert')</script>" + "Hello") + "</b>)")

Results in

(<b>&lt;script&gt;console.log('insert')&lt;/script&gt;Hello</b>)

Nested Git repositories?

I would use one repository per project. That way, the history becomes easier to browse through.

I would also check the version of the third party library I'm using, into the repository of the project using it.

Why do we use $rootScope.$broadcast in AngularJS?

$rootScope basically functions as an event listener and dispatcher.

To answer the question of how it is used, it used in conjunction with rootScope.$on;

$rootScope.$broadcast("hi");

$rootScope.$on("hi", function(){
    //do something
});

However, it is a bad practice to use $rootScope as your own app's general event service, since you will quickly end up in a situation where every app depends on $rootScope, and you do not know what components are listening to what events.

The best practice is to create a service for each custom event you want to listen to or broadcast.

.service("hiEventService",function($rootScope) {
    this.broadcast = function() {$rootScope.$broadcast("hi")}
    this.listen = function(callback) {$rootScope.$on("hi",callback)}
})

How do I find duplicate values in a table in Oracle?

Doing

select count(j1.job_number), j1.job_number, j1.id, j2.id
from   jobs j1 join jobs j2 on (j1.job_numer = j2.job_number)
where  j1.id != j2.id
group by j1.job_number

will give you the duplicated rows' ids.

write newline into a file

Change the lines

if(nodeValue!=null)
    fop.write(nodeValue.getBytes());

fop.flush();

to

if(nodeValue!=null) {
    fop.write(nodeValue.getBytes());
    fop.write(System.getProperty("line.separator").getBytes());
}

fop.flush();

Update to address your edit:

In order to write each word on a different line, you need to split up your input string and then write each word separately.

private static void GetText(String nodeValue) throws IOException {

    if(!file3.exists()) {
        file3.createNewFile();
    }

    FileOutputStream fop=new FileOutputStream(file3,true);
    if(nodeValue!=null)
        for(final String s : nodeValue.split(" ")){
            fop.write(s.getBytes());
            fop.write(System.getProperty("line.separator").getBytes());
        }
    }

    fop.flush();
    fop.close();

}

How do I concatenate two arrays in C#?

More efficient (faster) to use Buffer.BlockCopy over Array.CopyTo,

int[] x = new int [] { 1, 2, 3};
int[] y = new int [] { 4, 5 };

int[] z = new int[x.Length + y.Length];
var byteIndex = x.Length * sizeof(int);
Buffer.BlockCopy(x, 0, z, 0, byteIndex);
Buffer.BlockCopy(y, 0, z, byteIndex, y.Length * sizeof(int));

I wrote a simple test program that "warms up the Jitter", compiled in release mode and ran it without a debugger attached, on my machine.

For 10,000,000 iterations of the example in the question

Concat took 3088ms

CopyTo took 1079ms

BlockCopy took 603ms

If I alter the test arrays to two sequences from 0 to 99 then I get results similar to this,

Concat took 45945ms

CopyTo took 2230ms

BlockCopy took 1689ms

From these results I can assert that the CopyTo and BlockCopy methods are significantly more efficient than Concat and furthermore, if performance is a goal, BlockCopy has value over CopyTo.

To caveat this answer, if performance doesn't matter, or there will be few iterations choose the method you find easiest. Buffer.BlockCopy does offer some utility for type conversion beyond the scope of this question.

Iterating over a numpy array

I see that no good desciption for using numpy.nditer() is here. So, I am gonna go with one. According to NumPy v1.21 dev0 manual, The iterator object nditer, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.

I have to calculate mean_squared_error and I have already calculate y_predicted and I have y_actual from the boston dataset, available with sklearn.

def cal_mse(y_actual, y_predicted):
    """ this function will return mean squared error
       args:
           y_actual (ndarray): np array containing target variable
           y_predicted (ndarray): np array containing predictions from DecisionTreeRegressor
       returns:
           mse (integer)
    """
    sq_error = 0
    for i in np.nditer(np.arange(y_pred.shape[0])):
        sq_error += (y_actual[i] - y_predicted[i])**2
    mse = 1/y_actual.shape[0] * sq_error
    
    return mse

Hope this helps :). for further explaination visit

How to put an image next to each other

Check this out. Just use float and get rid of relative.

http://jsfiddle.net/JhpRk/

#icons{float:left;}

Set session variable in laravel

in Laravel 5.4

use this method:

Session::put('variableName', $value);

Fastest method of screen capturing on Windows

I wrote a video capture software, similar to FRAPS for DirectX applications. The source code is available and my article explains the general technique. Look at http://blog.nektra.com/main/2013/07/23/instrumenting-direct3d-applications-to-capture-video-and-calculate-frames-per-second/

Respect to your questions related to performance,

  • DirectX should be faster than GDI except when you are reading from the frontbuffer which is very slow. My approach is similar to FRAPS (reading from backbuffer). I intercept a set of methods from Direct3D interfaces.

  • For video recording in realtime (with minimal application impact), a fast codec is essential. FRAPS uses it's own lossless video codec. Lagarith and HUFFYUV are generic lossless video codecs designed for realtime applications. You should look at them if you want to output video files.

  • Another approach to recording screencasts could be to write a Mirror Driver. According to Wikipedia: When video mirroring is active, each time the system draws to the primary video device at a location inside the mirrored area, a copy of the draw operation is executed on the mirrored video device in real-time. See mirror drivers at MSDN: http://msdn.microsoft.com/en-us/library/windows/hardware/ff568315(v=vs.85).aspx.

How to refer to relative paths of resources when working with a code repository

I spent a long time figuring out the answer to this, but I finally got it (and it's actually really simple):

import sys
import os
sys.path.append(os.getcwd() + '/your/subfolder/of/choice')

# now import whatever other modules you want, both the standard ones,
# as the ones supplied in your subfolders

This will append the relative path of your subfolder to the directories for python to look in It's pretty quick and dirty, but it works like a charm :)

How to check String in response body with mockMvc

Spring security's @WithMockUser and hamcrest's containsString matcher makes for a simple and elegant solution:

@Test
@WithMockUser(roles = "USER")
public void loginWithRoleUserThenExpectUserSpecificContent() throws Exception {
    mockMvc.perform(get("/index"))
            .andExpect(status().isOk())
            .andExpect(content().string(containsString("This content is only shown to users.")));
}

More examples on github

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

According to the w3c, cols and rows are both required attributes for textareas. Rows and Cols are the number of characters that are going to fit in the textarea rather than pixels or some other potentially arbitrary value. Go with the rows/cols.

What is a superfast way to read large files line-by-line in VBA?

'you can modify above and read full file in one go and then display each line as shown below

Option Explicit

Public Function QuickRead(FName As String) As Variant
    Dim i As Integer
    Dim res As String
    Dim l As Long
    Dim v As Variant

    i = FreeFile
    l = FileLen(FName)
    res = Space(l)
    Open FName For Binary Access Read As #i
    Get #i, , res
    Close i
    'split the file with vbcrlf
    QuickRead = Split(res, vbCrLf)
End Function

Sub Test()
    ' you can replace file for "c:\writename.txt to any file name you desire
    Dim strFilePathName As String: strFilePathName = "C:\writename.txt"
    Dim strFileLine As String
    Dim v As Variant
    Dim i As Long
    v = QuickRead(strFilePathName)
    For i = 0 To UBound(v)
        MsgBox v(i)
    Next
End Sub

Difference between | and || or & and && for comparison

& and | are bitwise operators that can operate on both integer and Boolean arguments, and && and || are logical operators that can operate only on Boolean arguments. In many languages, if both arguments are Boolean, the key difference is that the logical operators will perform short circuit evaluation and not evaluate the second argument if the first argument is enough to determine the answer (e.g. in the case of &&, if the first argument is false, the second argument is irrelevant).

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

If it is not defined in the web service or application or server (apache or IIS) that is hosting the web service consumable then you could create infinite connections until failure

wildcard * in CSS for classes

An alternative solution:

div[class|='tocolor'] will match for values of the "class" attribute that begin with "tocolor-", including "tocolor-1", "tocolor-2", etc.

Beware that this won't match

<div class="foo tocolor-">

Reference: https://www.w3.org/TR/css3-selectors/#attribute-representation

[att|=val]

Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D)

Upload files from Java client to a HTTP server

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    String uploadFolder = getServletContext().getRealPath("")
            + File.separator + DATA_DIRECTORY;//DATA_DIRECTORY is directory where you upload this file on the server

    ServletFileUpload upload = new ServletFileUpload(factory);

    upload.setSizeMax(MAX_REQUEST_SIZE);//MAX_REQUEST_SIZE is the size which size you prefer

And use <form enctype="multipart/form-data"> and use <input type="file"> in the html

Accessing nested JavaScript objects and arrays by string path

AngularJS

Speigg's approach is very neat and clean, though I found this reply while searching for the solution of accessing AngularJS $scope properties by string path and with a little modification it does the job:

$scope.resolve = function( path, obj ) {
    return path.split('.').reduce( function( prev, curr ) {
        return prev[curr];
    }, obj || this );
}

Just place this function in your root controller and use it any child scope like this:

$scope.resolve( 'path.to.any.object.in.scope')

Where does PostgreSQL store the database?

The location of specific tables/indexes can be adjusted by TABLESPACEs:

CREATE TABLESPACE dbspace LOCATION '/data/dbs';
CREATE TABLE something (......) TABLESPACE dbspace;
CREATE TABLE otherthing (......) TABLESPACE dbspace;

Is Google Play Store supported in avd emulators?

Starting from Android Studio 2.3.2 now you can create an AVD that has Play Store pre-installed on it. Currently, it is supported on the AVD's running

  • A device definition of Nexus 5 or 5X phone, or any Android Wear
  • A system image since Android 7.0 (API 24)

Official Source

For other emulators, you can try the solution mentioned in this answer.

How to find all the tables in MySQL with specific column names in them?

To get all tables with columns columnA or ColumnB in the database YourDatabase:

SELECT DISTINCT TABLE_NAME 
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME IN ('columnA','ColumnB')
        AND TABLE_SCHEMA='YourDatabase';

How to get every first element in 2 dimensional list

Compared the 3 methods

  1. 2D list: 5.323603868484497 seconds
  2. Numpy library : 0.3201274871826172 seconds
  3. Zip (Thanks to Joran Beasley) : 0.12395167350769043 seconds
D2_list=[list(range(100))]*100
t1=time.time()
for i in range(10**5):
    for j in range(10):
        b=[k[j] for k in D2_list]
D2_list_time=time.time()-t1

array=np.array(D2_list)
t1=time.time()        
for i in range(10**5):
    for j in range(10):
        b=array[:,j]        
Numpy_time=time.time()-t1

D2_trans = list(zip(*D2_list)) 
t1=time.time()        
for i in range(10**5):
    for j in range(10):
        b=D2_trans[j]
Zip_time=time.time()-t1

print ('2D List:',D2_list_time)
print ('Numpy:',Numpy_time)
print ('Zip:',Zip_time)

The Zip method works best. It was quite useful when I had to do some column wise processes for mapreduce jobs in the cluster servers where numpy was not installed.

How to execute a remote command over ssh with arguments?

This is an example that works on the AWS Cloud. The scenario is that some machine that booted from autoscaling needs to perform some action on another server, passing the newly spawned instance DNS via SSH

# Get the public DNS of the current machine (AWS specific)
MY_DNS=`curl -s http://169.254.169.254/latest/meta-data/public-hostname`


ssh \
    -o StrictHostKeyChecking=no \
    -i ~/.ssh/id_rsa \
    [email protected] \
<< EOF
cd ~/
echo "Hey I was just SSHed by ${MY_DNS}"
run_other_commands
# Newline is important before final EOF!

EOF

TypeError: Invalid dimensions for image data when plotting array with imshow()

There is a (somewhat) related question on StackOverflow:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

Count unique values in a column in Excel

Here's an elegant array formula (which I found here http://www.excel-easy.com/examples/count-unique-values.html) that does the trick nicely:

Type

=SUM(1/COUNTIF(List,List))

and confirm with CTRL-SHIFT-ENTER

How do I pull my project from github?

Since you have wiped out your computer and want to checkout your project again, you could start by doing the below initial settings:

git config --global user.name "Your Name"
git config --global user.email [email protected]

Login to your github account, go to the repository you want to clone, and copy the URL under "Clone with HTTPS".

You can clone the remote repository by using HTTPS, even if you had setup SSH the last time:

git clone https://github.com/username/repo-name.git

NOTE:

If you had setup SSH for your remote repository previously, you will have to add that key to the known hosts ssh file on your PC; if you don't and try to do git clone [email protected]:username/repo-name.git, you will see an error similar to the one below:

Cloning into 'repo-name'...
The authenticity of host 'github.com (192.30.255.112)' can't be established.
RSA key fingerprint is SHA256:nThbg6kXDoJWGl7E1IGOCspZomTxdCARLviMw6E5SY8.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'github.com,192.30.255.112' (RSA) to the list of known hosts.
[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Using HTTPS is a easier than SSH in this case.

Error: Could not find or load main class

I got this error because I was trying to run

javac HelloWorld.java && java HelloWorld.class

when I should have removed .class:

javac HelloWorld.java && java HelloWorld

Create two-dimensional arrays and access sub-arrays in Ruby

rows, cols = x,y  # your values
grid = Array.new(rows) { Array.new(cols) }

As for accessing elements, this article is pretty good for step by step way to encapsulate an array in the way you want:

How to ruby array

substring of an entire column in pandas dataframe

I needed to convert a single column of strings of form nn.n% to float. I needed to remove the % from the element in each row. The attend data frame has two columns.

attend.iloc[:,1:2]=attend.iloc[:,1:2].applymap(lambda x: float(x[:-1]))

Its an extenstion to the original answer. In my case it takes a dataframe and applies a function to each value in a specific column. The function removes the last character and converts the remaining string to float.

Trigger change event <select> using jquery

Another working solution for those who were blocked with jQuery trigger handler, that dosent fire on native events will be like below (100% working) :

var sortBySelect = document.querySelector("select.your-class"); 
sortBySelect.value = "new value"; 
sortBySelect.dispatchEvent(new Event("change"));

Including a groovy script in another groovy

After some investigation I have come to the conclusion that the following approach seems the best.

some/subpackage/Util.groovy

@GrabResolver(name = 'nexus', root = 'https://local-nexus-server:8443/repository/maven-public', m2Compatible = true)
@Grab('com.google.errorprone:error_prone_annotations:2.1.3')
@Grab('com.google.guava:guava:23.0')
@GrabExclude('com.google.errorprone:error_prone_annotations')

import com.google.common.base.Strings

class Util {
    void msg(int a, String b, Map c) {
        println 'Message printed by msg method inside Util.groovy'
        println "Print 5 asterisks using the Guava dependency ${Strings.repeat("*", 5)}"
        println "Arguments are a=$a, b=$b, c=$c"
    }
}

example.groovy

#!/usr/bin/env groovy
Class clazz = new GroovyClassLoader().parseClass("${new File(getClass().protectionDomain.codeSource.location.path).parent}/some/subpackage/Util.groovy" as File)
GroovyObject u = clazz.newInstance()
u.msg(1, 'b', [a: 'b', c: 'd'])

In order to run the example.groovy script, add it to your system path and type from any directory:

example.groovy

The script prints:

Message printed by msg method inside Util.groovy
Print 5 asterisks using the Guava dependency *****
Arguments are a=1, b=b, c=[a:b, c:d]

The above example was tested in the following environment: Groovy Version: 2.4.13 JVM: 1.8.0_151 Vendor: Oracle Corporation OS: Linux

The example demonstrates the following:

  • How to use a Util class inside a groovy script.
  • A Util class calling the Guava third party library by including it as a Grape dependency (@Grab('com.google.guava:guava:23.0')).
  • The Util class can reside in a subdirectory.
  • Passing arguments to a method within the Util class.

Additional comments/suggestions:

  • Always use a groovy class instead of groovy script for reusable functionality within your groovy scripts. The above example uses the Util class defined in the Util.groovy file. Using groovy scripts for reusable functionality is problematic. For example, if using a groovy script then the Util class would have to be instantiated at the bottom of the script with new Util(), but most importantly it would have to be placed in a file named anything but Util.groovy. Refer to Scripts versus classes for more details about the differences between groovy scripts and groovy classes.
  • In the above example I use the path "${new File(getClass().protectionDomain.codeSource.location.path).parent}/some/subpackage/Util.groovy" instead of "some/subpackage/Util.groovy". This will guarantee that the Util.groovy file will always be found in relation to the groovy script's location (example.groovy) and not the current working directory. For example, using "some/subpackage/Util.groovy" would result in searching at WORK_DIR/some/subpackage/Util.groovy.
  • Follow the Java class naming convention to name your groovy scripts. I personally prefer a small deviation where the scripts start with a lower letter instead of a capital one. For example, myScript.groovy is a script name, and MyClass.groovy is a class name. Naming my-script.groovy will result in runtime errors in certain scenarios because the resulting class will not have a valid Java class name.
  • In the JVM world in general the relevant functionality is named JSR 223: Scripting for the Java. In groovy in particular the functionality is named Groovy integration mechanisms. In fact, the same approach can be used in order to call any JVM language from within Groovy or Java. Some notable examples of such JVM languages are Groovy, Java, Scala, JRuby, and JavaScript (Rhino).

C++ Array Of Pointers

For example, if you want an array of int pointers it will be int* a[10]. It means that variable a is a collection of 10 int* s.

EDIT

I guess this is what you want to do:

class Bar
{
};

class Foo
{
public:

    //Takes number of bar elements in the pointer array
    Foo(int size_in);

    ~Foo();
    void add(Bar& bar);
private:

    //Pointer to bar array
    Bar** m_pBarArr;

    //Current fee bar index
    int m_index;
};

Foo::Foo(int size_in) : m_index(0)
{
    //Allocate memory for the array of bar pointers
    m_pBarArr = new Bar*[size_in];
}

Foo::~Foo()
{
    //Notice delete[] and not delete
    delete[] m_pBarArr;
    m_pBarArr = NULL;
}

void Foo::add(Bar &bar)
{
    //Store the pointer into the array. 
    //This is dangerous, you are assuming that bar object
    //is valid even when you try to use it
    m_pBarArr[m_index++] = &bar;
}

Replacing a character from a certain index

You can also Use below method if you have to replace string between specific index

def Replace_Substring_Between_Index(singleLine,stringToReplace='',startPos=0,endPos=1):
    try:
       singleLine = singleLine[:startPos]+stringToReplace+singleLine[endPos:]
    except Exception as e:
        exception="There is Exception at this step while calling replace_str_index method, Reason = " + str(e)
        BuiltIn.log_to_console(exception)
    return singleLine

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

How do I rename both a Git local and remote branch name?

I had to do the following task to rename local and remote branch:

# Rename the local branch to the new name
git branch -m <old_name> <new_name>

#  Delete the old remote branch
git push origin --delete <old_name>

# push to new remote branch - creates new remote branch
git push origin <new_name>

# set new remote branch as default remote branch for local branch
git branch --set-upstream-to=origin/<new_name> <new_name>

Saving the PuTTY session logging

To set permanent PuTTY session parameters do:

  1. Create sessions in PuTTY. Name it as "MyskinPROD"

  2. Configure the path for this session to point to "C:\dir\&Y&M&D&T_&H_putty.log".

  3. Create a Windows "Shortcut" to C:...\Putty.exe.

  4. Open "Shortcut" Properties and append "Target" line with parameters as shown below:

    "C:\Program Files (x86)\UTL\putty.exe" -ssh -load MyskinPROD user@ServerIP -pw password
    

Now, your PuTTY shortcut will bring in the "MyskinPROD" configuration every time you open the shortcut.

Check the screenshots and details on how I did it in my environment:

http://www.evernote.com/shard/s184/sh/93ebf08f-fde2-4dad-bccf-961c98fb614b/983d2ff8f2d1e6184318825d68b0b829

Bootstrap DatePicker, how to set the start date for tomorrow?

If you are using bootstrap-datepicker you may use this style:

$('#datepicker').datepicker('setStartDate', "01-01-1900");

extracting days from a numpy.timedelta64 value

Suppose you have a timedelta series:

import pandas as pd
from datetime import datetime
z = pd.DataFrame({'a':[datetime.strptime('20150101', '%Y%m%d')],'b':[datetime.strptime('20140601', '%Y%m%d')]})

td_series = (z['a'] - z['b'])

One way to convert this timedelta column or series is to cast it to a Timedelta object (pandas 0.15.0+) and then extract the days from the object:

td_series.astype(pd.Timedelta).apply(lambda l: l.days)

Another way is to cast the series as a timedelta64 in days, and then cast it as an int:

td_series.astype('timedelta64[D]').astype(int)

How to find Oracle Service Name

With SQL Developer you should also find it without writing any query. Right click on your Connection/Propriety.

You should see the name on the left under something like "connection details" and should look like "Connectionname@servicename", or on the right, under the connection's details.

How can I add a line to a file in a shell script?

Use perl -i, with a command that replaces the beginning of line 1 with what you want to insert (the .bk will have the effect that your original file is backed up):

perl -i.bk -pe 's/^/column1, column2, column3\n/ if($.==1)' testfile.csv