Programs & Examples On #Apache dbi

How to change font of UIButton with Swift

If you need to change only size (Swift 4.0):

button.titleLabel?.font = button.titleLabel?.font.withSize(12)

Convert a char to upper case using regular expressions (EditPad Pro)

TextPad will allow you to perform this operation.

example:

test this sentence

Find what: \([^ ]*\) \(.*\) Replace with: \U\1\E \2

the \U will cause all following chars to be upper

the \E will turn off the \U

the result will be:

TEST this sentence

Import functions from another js file. Javascript

//In module.js add below code

export function multiply() {
    return 2 * 3;
}

// Consume the module in calc.js

import { multiply } from './modules.js';

const result = multiply();

console.log(`Result: ${result}`);

// Module.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Module</title>
</head>
<body>

  <script type="module" src="./calc.js"></script>
</body>
</html>

Its a design pattern same code can be found below, please use a live server to test it else you will get CORS error

https://github.com/rohan12patil/JSDesignPatterns/tree/master/Structural%20Patterns/module

Angular 4/5/6 Global Variables

I use environment for that. It works automatically and you don't have to create new injectable service and most usefull for me, don't need to import via constructor.

1) Create environment variable in your environment.ts

export const environment = {
    ...
    // runtime variables
    isContentLoading: false,
    isDeployNeeded: false
}

2) Import environment.ts in *.ts file and create public variable (i.e. "env") to be able to use in html template

import { environment } from 'environments/environment';

@Component(...)
export class TestComponent {
    ...
    env = environment;
}

3) Use it in template...

<app-spinner *ngIf='env.isContentLoading'></app-spinner>

in *.ts ...

env.isContentLoading = false 

(or just environment.isContentLoading in case you don't need it for template)


You can create your own set of globals within environment.ts like so:

export const globals = {
    isContentLoading: false,
    isDeployNeeded: false
}

and import directly these variables (y)

Open PDF in new browser full window

To do it from a Base64 encoding you can use the following function:

function base64ToArrayBuffer(data) {
  const bString = window.atob(data);
  const bLength = bString.length;
  const bytes = new Uint8Array(bLength);
  for (let i = 0; i < bLength; i++) {
      bytes[i] = bString.charCodeAt(i);
  }
  return bytes;
}
function base64toPDF(base64EncodedData, fileName = 'file') {
  const bufferArray = base64ToArrayBuffer(base64EncodedData);
  const blobStore = new Blob([bufferArray], { type: 'application/pdf' });
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blobStore);
      return;
  }
  const data = window.URL.createObjectURL(blobStore);
  const link = document.createElement('a');
  document.body.appendChild(link);
  link.href = data;
  link.download = `${fileName}.pdf`;
  link.click();
  window.URL.revokeObjectURL(data);
  link.remove();
}

Difference between r+ and w+ in fopen()

r = read mode only
r+ = read/write mode
w = write mode only
w+ = read/write mode, if the file already exists override it (empty it)

So yes, if the file already exists w+ will erase the file and give you an empty file.

Using tr to replace newline with space

Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings

or use:

tr '\r\n' ' '

Use superscripts in R axis labels

The other option in this particular case would be to type the degree symbol: °

R seems to handle it fine. Type Option-k on a Mac to get it. Not sure about other platforms.

Get drop down value

If your dropdown is something like this:

<select id="thedropdown">
  <option value="1">one</option>
  <option value="2">two</option>
</select>

Then you would use something like:

var a = document.getElementById("thedropdown");
alert(a.options[a.selectedIndex].value);

But a library like jQuery simplifies things:

alert($('#thedropdown').val());

Simple http post example in Objective-C?

 NSMutableDictionary *contentDictionary = [[NSMutableDictionary alloc]init];
[contentDictionary setValue:@"name" forKey:@"email"];
[contentDictionary setValue:@"name" forKey:@"username"];
[contentDictionary setValue:@"name" forKey:@"password"];
[contentDictionary setValue:@"name" forKey:@"firstName"];
[contentDictionary setValue:@"name" forKey:@"lastName"];

NSData *data = [NSJSONSerialization dataWithJSONObject:contentDictionary options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonStr = [[NSString alloc] initWithData:data
                                          encoding:NSUTF8StringEncoding];
NSLog(@"%@",jsonStr);

NSString *urlString = [NSString stringWithFormat:@"http://testgcride.com:8081/v1/users"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
   [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];


[request setHTTPBody:[jsonStr dataUsingEncoding:NSUTF8StringEncoding]];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"moinsam" password:@"cheese"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];

AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:<block> failure:<block>];

Create an ISO date object in javascript

I solved this problem instantiating a new Date object in node.js:...

In Javascript, send the Date().toISOString() to nodejs:...

var start_date = new Date(2012, 01, 03, 8, 30);

$.ajax({
    type: 'POST',
    data: { start_date: start_date.toISOString() },
    url: '/queryScheduleCollection',
    dataType: 'JSON'
}).done(function( response ) { ... });

Then use the ISOString to create a new Date object in nodejs:..

exports.queryScheduleCollection = function(db){
    return function(req, res){

        var start_date = new Date(req.body.start_date);

        db.collection('schedule_collection').find(
            { start_date: { $gte: start_date } }
        ).toArray( function (err,d){
            ...
            res.json(d)
        })
    }
};

Note: I'm using Express and Mongoskin.

How do I install Python 3 on an AWS EC2 instance?

Here are the steps I used to manually install python3 for anyone else who wants to do it as it's not super straight forward. EDIT: It's almost certainly easier to use the yum package manager (see other answers).

Note, you'll probably want to do sudo yum groupinstall 'Development Tools' before doing this otherwise pip won't install.

wget https://www.python.org/ftp/python/3.4.2/Python-3.4.2.tgz
tar zxvf Python-3.4.2.tgz
cd Python-3.4.2
sudo yum install gcc
./configure --prefix=/opt/python3
make
sudo yum install openssl-devel
sudo make install
sudo ln -s /opt/python3/bin/python3 /usr/bin/python3
python3 (should start the interpreter if it's worked (quit() to exit)

Sum one number to every element in a list (or array) in Python

if you want to operate with list of numbers it is better to use NumPy arrays:

import numpy
a = [1, 1, 1 ,1, 1]
ar = numpy.array(a)
print ar + 2

gives

[3, 3, 3, 3, 3]

Remove specific commit

So you did some work and pushed it, lets call them commits A and B. Your coworker did some work as well, commits C And D. You merged your coworkers work into yours (merge commit E), then continued working, committed that, too (commit F), and discovered that your coworker changed some things he shouldn't have.

So your commit history looks like this:

A -- B -- C -- D -- D' -- E -- F

You really want to get rid of C, D, and D'. Since you say you merged your coworkers work into yours, these commits already "out there", so removing the commits using e.g. git rebase is a no-no. Believe me, I've tried.

Now, I see two ways out:

  • if you haven't pushed E and F to your coworker or anyone else (typically your "origin" server) yet, you could still remove those from the history for the time being. This is your work that you want to save. This can be done with a

    git reset D'
    

    (replace D' with the actual commit hash that you can obtain from a git log

    At this point, commits E and F are gone and the changes are uncommitted changes in your local workspace again. At this point I would move them to a branch or turn them into a patch and save it for later. Now, revert your coworker's work, either automatically with a git revert or manually. When you've done that, replay your work on top of that. You may have merge conflicts, but at least they'll be in the code you wrote, instead of your coworker's code.

  • If you've already pushed the work you did after your coworker's commits, you can still try and get a "reverse patch" either manually or using git revert, but since your work is "in the way", so to speak you'll probably get more merge conflicts and more confusing ones. Looks like that's what you ended up in...

Read a text file using Node.js?

You can use readstream and pipe to read the file line by line without read all the file into memory one time.

var fs = require('fs'),
    es = require('event-stream'),
    os = require('os');

var s = fs.createReadStream(path)
    .pipe(es.split())
    .pipe(es.mapSync(function(line) {
        //pause the readstream
        s.pause();
        console.log("line:", line);
        s.resume();
    })
    .on('error', function(err) {
        console.log('Error:', err);
    })
    .on('end', function() {
        console.log('Finish reading.');
    })
);

Replacement for "rename" in dplyr

dplyr >= 1.0.0

In addition to dplyr::rename in newer versions of dplyr is rename_with()

rename_with() renames columns using a function.

You can apply a function over a tidy-select set of columns using the .cols argument:

iris %>% 
  dplyr::rename_with(.fn = ~ gsub("^S", "s", .), .cols = where(is.numeric))

    sepal.Length sepal.Width Petal.Length Petal.Width    Species
1            5.1         3.5          1.4         0.2     setosa
2            4.9         3.0          1.4         0.2     setosa
3            4.7         3.2          1.3         0.2     setosa
4            4.6         3.1          1.5         0.2     setosa
5            5.0         3.6          1.4         0.2     setosa

Get class labels from Keras functional model

y_prob = model.predict(x) 
y_classes = y_prob.argmax(axis=-1)

As suggested here.

window.open target _self v window.location.href?

You can omit window and just use location.href. For example:

location.href = 'http://google.im/';

SQL DATEPART(dw,date) need monday = 1 and sunday = 7

Looks like the DATEFIRST settings is the only way, but it's not possible to make a SET statement in a scalar/table valued function. Therefore, it becomes very error-prone to the colleagues following your code. (become a trap to the others)

In fact, SQL server datepart function should be improved to accept this as parameter instead.

At the meantime, it looks like using the English Name of the week is the safest choice.

How can I manually generate a .pyc file from a .py file

You can use compileall in the terminal. The following command will go recursively into sub directories and make pyc files for all the python files it finds. The compileall module is part of the python standard library, so you don't need to install anything extra to use it. This works exactly the same way for python2 and python3.

python -m compileall .

.war vs .ear file

Refer: http://www.wellho.net/mouth/754_tar-jar-war-ear-sar-files.html

tar (tape archives) - Format used is file written in serial units of fileName, fileSize, fileData - no compression. can be huge

Jar (java archive) - compression techniques used - generally contains java information like class/java files. But can contain any files and directory structure

war (web application archives) - similar like jar files only have specific directory structure as per JSP/Servlet spec for deployment purposes

ear (enterprise archives) - similar like jar files. have directory structure following J2EE requirements so that it can be deployed on J2EE application servers. - can contain multiple JAR and WAR files

Should I use window.navigate or document.location in JavaScript?

I'd go with window.location = "http://...";. I've been coding cross-browser JavaScript for a few years, and I've never experienced problems using this approach.

window.navigate and window.location.href seems a bit odd to me.

Eclipse: How do you change the highlight color of the currently selected method/expression?

If you're using eclipse with PHP package and want to change highlighted colour then there is slight difference to above answer.

  1. Right click on highlighted word
  2. Select 'Preferences'
  3. Go to General > Editors > Text Editors > Annotations. Now look for "PHP elements 'read' occurrences" and "PHP elements 'write' occurrences". You can select your desired colour there.

Change Highlighted text colour in Eclips with PHP

How do I find out if first character of a string is a number?

IN KOTLIN :

Suppose that you have a String like this :

private val phoneNumber="9121111111"

At first you should get the first one :

val firstChar=phoneNumber.slice(0..0)

At second you can check the first char that return a Boolean :

firstChar.isInt() // or isFloat()

SyntaxError: Use of const in strict mode?

Updating NodeJS solves this problem. But, after running sudo npm install -g n you might get following error:

npm: relocation error: npm: symbol SSL_set_cert_cb, version libssl.so.10 not defined in file libssl.so.10 with link time reference

In order to overcome this error, try upgrading openssl using the below command:

sudo yum update openssl

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

Did something like that once:

CREATE TABLE exclusions(excl VARCHAR(250));
INSERT INTO exclusions(excl)
VALUES
       ('%timeline%'),
       ('%Placeholders%'),
       ('%Stages%'),
       ('%master_stage_1205x465%'),
       ('%Accessories%'),
       ('%chosen-sprite.png'),
('%WebResource.axd');
GO
CREATE VIEW ToBeDeleted AS 
SELECT * FROM chunks
       WHERE chunks.file_id IN
       (
       SELECT DISTINCT
             lf.file_id
       FROM LargeFiles lf
       WHERE lf.file_id NOT IN
             (
             SELECT DISTINCT
                    lf.file_id
             FROM LargeFiles lf
                LEFT JOIN exclusions e ON(lf.URL LIKE e.excl)
                WHERE e.excl IS NULL
             )
       );
GO
CHECKPOINT
GO
SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;
WHILE @r>0

BEGIN
    DELETE TOP (10000) FROM ToBeDeleted;
    SET @r = @@ROWCOUNT  
END
GO

Proper way to get page content

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array( 'prev_text' >' Previous','post_type' => 'page', 'posts_per_page' => 5, 'paged' => $paged );
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post();
//get all pages 
the_ID();
the_title();

//if you want specific page of content then write
if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
{
echo get_the_ID();
the_title();
the_content();
}

endwhile;

//if you want specific page of content then write in loop

  if(get_the_ID=='11')//make sure to use get_the_ID instead the_ID
    {
    echo get_the_ID();
    the_title();
    the_content();
    }

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

Routing for custom ASP.NET MVC 404 Error page

I had the same problem, the thing you have to do is, instead of adding the customErrors attribute in the web.config file in your Views folder, you have to add it in the web.config file in your projects root folder

Android add placeholder text to EditText

If you want to insert text inside your EditText view that stays there after the field is selected (unlike how hint behaves), do this:

In Java:

// Cast Your EditText as a TextView
((TextView) findViewById(R.id.email)).setText("your Text")

In Kotlin:

// Cast your EditText into a TextView
// Like this
(findViewById(R.id.email) as TextView).text = "Your Text"
// Or simply like this
findViewById<TextView>(R.id.email).text = "Your Text"

hide/show a image in jquery

I know this is an older post but it may be useful for those who are looking to show a .NET server side image using jQuery.

You have to use a slightly different logic.

So, $("#<%=myServerimg.ClientID%>").show() will not work if you hid the image using myServerimg.visible = false.

Instead, use the following on server side:

myServerimg.Style.Add("display", "none")

Writing MemoryStream to Response Object

I had the same issue. try this: copy to MemoryStream -> delete file -> download.

string absolutePath = "~/your path";
try {
    //copy to MemoryStream
    MemoryStream ms = new MemoryStream();
    using (FileStream fs = File.OpenRead(Server.MapPath(absolutePath))) 
    { 
        fs.CopyTo(ms); 
    }

    //Delete file
    if(File.Exists(Server.MapPath(absolutePath)))
       File.Delete(Server.MapPath(absolutePath))

    //Download file
    Response.Clear()
    Response.ContentType = "image/jpg";
    Response.AddHeader("Content-Disposition", "attachment;filename=\"" + absolutePath + "\"");
    Response.BinaryWrite(ms.ToArray())
}
catch {}

Response.End();

Git: How to find a deleted file in the project commit history?

Summary:

  1. Step 1

You search your file full path in history of deleted files git log --diff-filter=D --summary | grep filename

  1. Step 2

You restore your file from commit before it was deleted

restore () {
  filepath="$@"
  last_commit=$(git log --all --full-history -- $filepath | grep commit | head -1 | awk '{print $2; exit}')
  echo "Restoring file from commit before $last_commit"
  git checkout $last_commit^ -- $filepath
}

restore my/file_path

How to use a DataAdapter with stored procedure and parameter

SqlConnection con = new SqlConnection(@"Some Connection String");//connection object
SqlDataAdapter da = new SqlDataAdapter("ParaEmp_Select",con);//SqlDataAdapter class object
da.SelectCommand.CommandType = CommandType.StoredProcedure; //command sype
da.SelectCommand.Parameters.Add("@Contactid", SqlDbType.Int).Value = 123; //pass perametter
DataTable dt = new DataTable();  //dataset class object
da.Fill(dt); //call the stored producer

How to print the ld(linker) search path

Mac version: $ ld -v 2, don't know how to get detailed paths. output

Library search paths:
    /usr/lib
    /usr/local/lib
Framework search paths:
    /Library/Frameworks/
    /System/Library/Frameworks/

Parsing JSON object in PHP using json_decode

You have to make sure first that your server allow remote connection so that the function file_get_contents($url) works fine , most server disable this feature for security reason.

jquery select element by xpath

document.evaluate() (DOM Level 3 XPath) is supported in Firefox, Chrome, Safari and Opera - the only major browser missing is MSIE. Nevertheless, jQuery supports basic XPath expressions: http://docs.jquery.com/DOM/Traversing/Selectors#XPath_Selectors (moved into a plugin in the current jQuery version, see https://plugins.jquery.com/xpath/). It simply converts XPath expressions into equivalent CSS selectors however.

How to delete last item in list?

You need:

record = record[:-1]

before the for loop.

This will set record to the current record list but without the last item. You may, depending on your needs, want to ensure the list isn't empty before doing this.

How can I brew link a specific version?

brew switch libfoo mycopy

You can use brew switch to switch between versions of the same package, if it's installed as versioned subdirectories under Cellar/<packagename>/

This will list versions installed ( for example I had Cellar/sdl2/2.0.3, I've compiled into Cellar/sdl2/2.0.4)

brew info sdl2

Then to switch between them

brew switch sdl2 2.0.4
brew info 

Info now shows * next to the 2.0.4

To install under Cellar/<packagename>/<version> from source you can do for example

cd ~/somewhere/src/foo-2.0.4
./configure --prefix $(brew --Cellar)/foo/2.0.4
make

check where it gets installed with

make install -n

if all looks correct

make install

Then from cd $(brew --Cellar) do the switch between version.

I'm using brew version 0.9.5

What is JavaScript's highest integer value that a number can go to without losing precision?

Firefox 3 doesn't seem to have a problem with huge numbers.

1e+200 * 1e+100 will calculate fine to 1e+300.

Safari seem to have no problem with it as well. (For the record, this is on a Mac if anyone else decides to test this.)

Unless I lost my brain at this time of day, this is way bigger than a 64-bit integer.

ASP MVC in IIS 7 results in: HTTP Error 403.14 - Forbidden

Answered on SO here, question: 403 - Forbidden on basic MVC 3 deploy on iis7.5

Run aspnet_regiis -i. Often I've found you need to do that to get 4.0 apps to work. Open a command prompt as an Administrator (right click the command prompt icon and select Run as Administrator):

cd \
cd Windows\Microsoft.NET\Framework\v4.xxx.xxx
aspnet_regiis -i

Once it has installed and registered, make sure you application is using an application pool that is set to .NET 4.0.

UPDATE: I just found an issue with this command. Using -i updated all application pools to ASP.NET 4.0.

Using aspnet_regiis -ir installs the version of ASP.NET but does not change any web applications to this version. You may also want to review the -iru option.

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

If emails is the pandas dataframe and emails.message the column for email text

## Helper functions
def get_text_from_email(msg):
    '''To get the content from email objects'''
    parts = []
    for part in msg.walk():
        if part.get_content_type() == 'text/plain':
            parts.append( part.get_payload() )
    return ''.join(parts)

def split_email_addresses(line):
    '''To separate multiple email addresses'''
    if line:
        addrs = line.split(',')
        addrs = frozenset(map(lambda x: x.strip(), addrs))
    else:
        addrs = None
    return addrs 

import email
# Parse the emails into a list email objects
messages = list(map(email.message_from_string, emails['message']))
emails.drop('message', axis=1, inplace=True)
# Get fields from parsed email objects
keys = messages[0].keys()
for key in keys:
    emails[key] = [doc[key] for doc in messages]
# Parse content from emails
emails['content'] = list(map(get_text_from_email, messages))
# Split multiple email addresses
emails['From'] = emails['From'].map(split_email_addresses)
emails['To'] = emails['To'].map(split_email_addresses)

# Extract the root of 'file' as 'user'
emails['user'] = emails['file'].map(lambda x:x.split('/')[0])
del messages

emails.head()

CSS How to set div height 100% minus nPx

Use an outer wrapper div set to 100% and then your inner wrapper div 100% should be now relative to that.

I thought for sure this used to work for me, but apparently not:

<html>
<body>
<div id="outerwrapper" style="border : 1px solid red ; height : 100%">
<div id="header" style="border : 1px solid blue ; height : 60px"></div>
<div id="wrapper"  style="border : 1px solid green ; height : 100% ; overflow : scroll ;">
  <div id="left" style="height : 100% ; width : 50% ; overflow : scroll; float : left ; clear : left ;">Some text 

on the left</div>
  <div id="right" style="height : 100% ; width 50% ; overflow : scroll; float : left ;">Some Text on the 

right</div>
</div>
</div>
</body>
</html>

git pull fails "unable to resolve reference" "unable to update local ref"

Try it:

git gc --prune=now

git remote prune origin

git pull

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

You only need the async pipe:

<li *ngFor="let afd of afdeling | async">
    {{afd.patientid}}
</li>

always use the async pipe when dealing with Observables directly without explicitly unsubscribe.

Good tutorial for using HTML5 History API (Pushstate?)

Here is a great screen-cast on the topic by Ryan Bates of railscasts. At the end he simply disables the ajax functionality if the history.pushState method is not available:

http://railscasts.com/episodes/246-ajax-history-state

How to copy part of an array to another array in C#?

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

int [] b= new int[a.length]; //New Array and the size of a which is 4

Array.Copy(a,b,a.length);

Where Array is class having method Copy, which copies the element of a array to b array.

While copying from one array to another array, you have to provide same data type to another array of which you are copying.

no debugging symbols found when using gdb

The most frequent cause of "no debugging symbols found" when -g is present is that there is some "stray" -s or -S argument somewhere on the link line.

From man ld:

   -s
   --strip-all
       Omit all symbol information from the output file.

   -S
   --strip-debug
       Omit debugger symbol information (but not all symbols) from the output file.

Python coding standards/best practices

PEP 8 is good, the only thing that i wish it came down harder on was the Tabs-vs-Spaces holy war.

Basically if you are starting a project in python, you need to choose Tabs or Spaces and then shoot all offenders on sight.

How can I get the ID of an element using jQuery?

The jQuery way:

$('#test').attr('id')

In your example:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  console.log($('#test').attr('id'));_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="test"></div>
_x000D_
_x000D_
_x000D_

Or through the DOM:

$('#test').get(0).id;

or even :

$('#test')[0].id;

and reason behind usage of $('#test').get(0) in JQuery or even $('#test')[0] is that $('#test') is a JQuery selector and returns an array() of results not a single element by its default functionality

an alternative for DOM selector in jquery is

$('#test').prop('id')

which is different from .attr() and $('#test').prop('foo') grabs the specified DOM foo property, while $('#test').attr('foo') grabs the specified HTML foo attribute and you can find more details about differences here.

How to get jQuery to wait until an effect is finished?

You can specify a callback function:

$(selector).fadeOut('slow', function() {
    // will be called when the element finishes fading out
    // if selector matches multiple elements it will be called once for each
});

Documentation here.

Detecting when the 'back' button is pressed on a navbar

The best way is to use the UINavigationController delegate methods

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated

Using this you can know what controller is showing the UINavigationController.

if ([viewController isKindOfClass:[HomeController class]]) {
    NSLog(@"Show home controller");
}

.attr("disabled", "disabled") issue

Try

$(bla).click(function(){        
  if (something) {
     console.log("A:"+$target.prev("input")) // gives out the right object
     $target.toggleClass("open").prev("input").attr("disabled", "disabled");
  }else{
     console.log("A:"+$target.prev("input")) // any thing from there for a single click?
     $target.toggleClass("open").prev("input").removeAttr("disabled"); //this works
  }
});

Compare two files and write it to "match" and "nomatch" files

Since 12,200 people have looked at this question and not got an answer:

DFSORT and SyncSort are the predominant Mainframe sorting products. Their control cards have many similarities, and some differences.

JOINKEYS FILE=F1,FIELDS=(key1startpos,7,A)              
JOINKEYS FILE=F2,FIELDS=(key2startpos,7,A)              
JOIN UNPAIRED,F1,F2
REFORMAT FIELDS=(F1:1,5200,F2:1,5200)                         
SORT FIELDS=COPY    

A "JOINKEYS" is made of three Tasks. Sub-Task 1 is the first JOINKEYS. Sub-Task 2 is the second JOINKEYS. The Main Task follows and is where the joined data is processed. In the example above it is a simple COPY operation. The joined data will simply be written to SORTOUT.

The JOIN statement defines that as well as matched records, UNPAIRED F1 and F2 records are to be presented to the Main Task.

The REFORMAT statement defines the record which will be presented to the Main Task. A more efficient example, imagining that three fields are required from F2, is:

 REFORMAT FIELDS=(F1:1,5200,F2:1,10,30,1,5100,100)

Each of the fields on F2 is defined with a start position and a length.

The record which is then processed by the Main task is 5311 bytes long, and the fields from F2 can be referenced by 5201,10,5211,1,5212,100 with the F1 record being 1,5200.

A better way achieve the same thing is to reduce the size of F2 with JNF2CNTL.

//JNF2CNTL DD *
  INREC BUILD=(207,1,10,30,1,5100,100)

Some installations of SyncSort do not support JNF2CNTL, and even where supported (from Syncsort MFX for z/OS release 1.4.1.0 onwards), it is not documented by SyncSort. For users of 1.3.2 or 1.4.0 an update is available from SyncSort to provide JNFnCNTL support.

It should be noted that JOINKEYS by default SORTs the data, with option EQUALS. If the data for a JOINKEYS file is already in sequence, SORTED should be specified. For DFSORT NOSEQCHK can also be specified if sequence-checking is not required.

 JOINKEYS FILE=F1,FIELDS=(key1startpos,7,A),SORTED,NOSEQCHK

Although the request is strange, as the source file won't be able to be determined, all unmatched records are to go to a separate output file.

With DFSORT, there is a matching-marker, specified with ? in the REFORMAT:

 REFORMAT FIELDS=(F1:1,5200,F2:1,10,30,1,5100,100,?)

This increases the length of the REFORMAT record by one byte. The ? can be specified anywhere on the REFORMAT record, and need not be specified. The ? is resolved by DFSORT to: B, data sourced from Both files; 1, unmatched record from F1; 2, unmatched record from F2.

SyncSort does not have the match marker. The absence or presence of data on the REFORMAT record has to be determined by values. Pick a byte on both input records which cannot contain a particular value (for instance, within a number, decide on a non-numeric value). Then specify that value as the FILL character on the REFORMAT.

 REFORMAT FIELDS=(F1:1,5200,F2:1,10,30,1,5100,100),FILL=C'$'

If position 1 on F1 cannot naturally have "$" and position 20 on F2 cannot either, then those two positions can be used to establish the result of the match. The entire record can be tested if necessary, but sucks up more CPU time.

The apparent requirement is for all unmatched records, from either F1 or F2, to be written to one file. This will require a REFORMAT statement which includes both records in their entirety:

DFSORT, output unmatched records:

  REFORMAT FIELDS=(F1:1,5200,F2:1,5200,?)

  OUTFIL FNAMES=NOMATCH,INCLUDE=(10401,1,SS,EQ,C'1,2'),
        IFTHEN=(WHEN=(10401,1,CH,EQ,C'1'),
                    BUILD=(1,5200)),
        IFTHEN=(WHEN=NONE,
                    BUILD=(5201,5200))

SyncSort, output unmatched records:

  REFORMAT FIELDS=(F1:1,5200,F2:1,5200),FILL=C'$'

  OUTFIL FNAMES=NOMATCH,INCLUDE=(1,1,CH,EQ,C'$',
                          OR,5220,1,CH,EQ,C'$'),
        IFTHEN=(WHEN=(1,1,CH,EQ,C'$'),
                    BUILD=(1,5200)),
        IFTHEN=(WHEN=NONE,
                    BUILD=(5201,5200))

The coding for SyncSort will also work with DFSORT.

To get the matched records written is easy.

  OUTFIL FNAMES=MATCH,SAVE

SAVE ensures that all records not written by another OUTFIL will be written here.

There is some reformatting required, to mainly output data from F1, but to select some fields from F2. This will work for either DFSORT or SyncSort:

  OUTFIL FNAMES=MATCH,SAVE,
     BUILD=(1,50,10300,100,51,212,5201,10,263,8,5230,1,271,4929)

The whole thing, with arbitrary starts and lengths is:

DFSORT

  JOINKEYS FILE=F1,FIELDS=(1,7,A)              
  JOINKEYS FILE=F2,FIELDS=(20,7,A)    

  JOIN UNPAIRED,F1,F2

  REFORMAT FIELDS=(F1:1,5200,F2:1,5200,?)                         

  SORT FIELDS=COPY    

  OUTFIL FNAMES=NOMATCH,INCLUDE=(10401,1,SS,EQ,C'1,2'),
        IFTHEN=(WHEN=(10401,1,CH,EQ,C'1'),
                    BUILD=(1,5200)),
        IFTHEN=(WHEN=NONE,
                    BUILD=(5201,5200))

  OUTFIL FNAMES=MATCH,SAVE,
     BUILD=(1,50,10300,100,51,212,5201,10,263,8,5230,1,271,4929)

SyncSort

  JOINKEYS FILE=F1,FIELDS=(1,7,A)              
  JOINKEYS FILE=F2,FIELDS=(20,7,A)              

  JOIN UNPAIRED,F1,F2

  REFORMAT FIELDS=(F1:1,5200,F2:1,5200),FILL=C'$'                         

  SORT FIELDS=COPY    

  OUTFIL FNAMES=NOMATCH,INCLUDE=(1,1,CH,EQ,C'$',
                          OR,5220,1,CH,EQ,C'$'),
        IFTHEN=(WHEN=(1,1,CH,EQ,C'$'),
                    BUILD=(1,5200)),
        IFTHEN=(WHEN=NONE,
                    BUILD=(5201,5200))

  OUTFIL FNAMES=MATCH,SAVE,
     BUILD=(1,50,10300,100,51,212,5201,10,263,8,5230,1,271,4929)

Get all messages from Whatsapp

I'm not sure if WhatsApp really stores it's stuff in a sqlite database stored in the private app space but it may be worth a try to do the same I suggested here. You will need root access for this.

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

How to add/update child entities when updating a parent entity in EF

Here is my code that works just fine.

public async Task<bool> UpdateDeviceShutdownAsync(Guid id, DateTime shutdownAtTime, int areaID, decimal mileage,
        decimal motohours, int driverID, List<int> commission,
        string shutdownPlaceDescr, int deviceShutdownTypeID, string deviceShutdownDesc,
        bool isTransportation, string violationConditions, DateTime shutdownStartTime,
        DateTime shutdownEndTime, string notes, List<Guid> faultIDs )
        {
            try
            {
                using (var db = new GJobEntities())
                {
                    var isExisting = await db.DeviceShutdowns.FirstOrDefaultAsync(x => x.ID == id);

                    if (isExisting != null)
                    {
                        isExisting.AreaID = areaID;
                        isExisting.DriverID = driverID;
                        isExisting.IsTransportation = isTransportation;
                        isExisting.Mileage = mileage;
                        isExisting.Motohours = motohours;
                        isExisting.Notes = notes;                    
                        isExisting.DeviceShutdownDesc = deviceShutdownDesc;
                        isExisting.DeviceShutdownTypeID = deviceShutdownTypeID;
                        isExisting.ShutdownAtTime = shutdownAtTime;
                        isExisting.ShutdownEndTime = shutdownEndTime;
                        isExisting.ShutdownStartTime = shutdownStartTime;
                        isExisting.ShutdownPlaceDescr = shutdownPlaceDescr;
                        isExisting.ViolationConditions = violationConditions;

                        // Delete children
                        foreach (var existingChild in isExisting.DeviceShutdownFaults.ToList())
                        {
                            db.DeviceShutdownFaults.Remove(existingChild);
                        }

                        if (faultIDs != null && faultIDs.Any())
                        {
                            foreach (var faultItem in faultIDs)
                            {
                                var newChild = new DeviceShutdownFault
                                {
                                    ID = Guid.NewGuid(),
                                    DDFaultID = faultItem,
                                    DeviceShutdownID = isExisting.ID,
                                };

                                isExisting.DeviceShutdownFaults.Add(newChild);
                            }
                        }

                        // Delete all children
                        foreach (var existingChild in isExisting.DeviceShutdownComissions.ToList())
                        {
                            db.DeviceShutdownComissions.Remove(existingChild);
                        }

                        // Add all new children
                        if (commission != null && commission.Any())
                        {
                            foreach (var cItem in commission)
                            {
                                var newChild = new DeviceShutdownComission
                                {
                                    ID = Guid.NewGuid(),
                                    PersonalID = cItem,
                                    DeviceShutdownID = isExisting.ID,
                                };

                                isExisting.DeviceShutdownComissions.Add(newChild);
                            }
                        }

                        await db.SaveChangesAsync();

                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

            return false;
        }

how can I Update top 100 records in sql server

for those like me still stuck with SQL Server 2000, SET ROWCOUNT {number}; can be used before the UPDATE query

SET ROWCOUNT 100;
UPDATE Table SET ..;
SET ROWCOUNT 0;

will limit the update to 100 rows

It has been deprecated at least since SQL 2005, but as of SQL 2017 it still works. https://docs.microsoft.com/en-us/sql/t-sql/statements/set-rowcount-transact-sql?view=sql-server-2017

Algorithm for Determining Tic Tac Toe Game Over

a non-loop way to determine if the point was on the anti diag:

`if (x + y == n - 1)`

How do you convert an entire directory with ffmpeg?

The following script works well for me in a Bash on Windows (so it should work just as well on Linux and Mac). It addresses some problems I have had with some other solutions:

  • Processes files in subfolders
  • Replaces the source extension with the target extension instead of just appending it
  • Works with files with multiple spaces and multiple dots in the name (See this answer for details.)
  • Can be run when the target file exists, prompting before overwriting

ffmpeg-batch-convert.sh:

sourceExtension=$1 # e.g. "mp3"
targetExtension=$2 # e.g. "wav"
IFS=$'\n'; set -f
for sourceFile in $(find . -iname "*.$sourceExtension")
do
    targetFile="${sourceFile%.*}.$targetExtension"
    ffmpeg -i "$sourceFile" "$targetFile"
done
unset IFS; set +f

Example call:

$ sh ffmpeg-batch-convert.sh mp3 wav

As a bonus, if you want the source files deleted, you can modify the script like this:

sourceExtension=$1 # e.g. "mp3"
targetExtension=$2 # e.g. "wav"
deleteSourceFile=$3 # "delete" or omitted
IFS=$'\n'; set -f
for sourceFile in $(find . -iname "*.$sourceExtension")
do
    targetFile="${sourceFile%.*}.$targetExtension"
    ffmpeg -i "$sourceFile" "$targetFile"
    if [ "$deleteSourceFile" == "delete" ]; then
        if [ -f "$targetFile" ]; then
            rm "$sourceFile"
        fi
    fi
done
unset IFS; set +f

Example call:

$ sh ffmpeg-batch-convert.sh mp3 wav delete

How to parse XML to R data frame

Here's a partial solution using xml2. Breaking the solution up into smaller pieces generally makes it easier to ensure everything is lined up:

library(xml2)
data <- read_xml("http://forecast.weather.gov/MapClick.php?lat=29.803&lon=-82.411&FcstType=digitalDWML")

# Point locations
point <- data %>% xml_find_all("//point")
point %>% xml_attr("latitude") %>% as.numeric()
point %>% xml_attr("longitude") %>% as.numeric()

# Start time
data %>% 
  xml_find_all("//start-valid-time") %>% 
  xml_text()

# Temperature
data %>% 
  xml_find_all("//temperature[@type='hourly']/value") %>% 
  xml_text() %>% 
  as.integer()

SQL WHERE.. IN clause multiple columns

I founded easier this way

Select * 
from table1 
WHERE  (convert(VARCHAR,CM_PLAN_ID) + convert(VARCHAR,Individual_ID)) 
IN 
(
 Select convert(VARCHAR,CM_PLAN_ID) + convert(VARCHAR,Individual_ID)
 From CRM_VCM_CURRENT_LEAD_STATUS 
 Where Lead_Key = :_Lead_Key 
) 

Hope this help :)

jQuery selector regular expressions

These can be helpful.

If you're finding by Contains then it'll be like this

    $("input[id*='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you're finding by Starts With then it'll be like this

    $("input[id^='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you're finding by Ends With then it'll be like this

     $("input[id$='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which id is not a given string

    $("input[id!='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which name contains a given word, delimited by spaces

     $("input[name~='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

If you want to select elements which id is equal to a given string or starting with that string followed by a hyphen

     $("input[id|='DiscountType']").each(function (i, el) {
         //It'll be an array of elements
     });

Get column from a two dimensional array

Use Array.prototype.map() with an arrow function:

_x000D_
_x000D_
const arrayColumn = (arr, n) => arr.map(x => x[n]);_x000D_
_x000D_
const twoDimensionalArray = [_x000D_
  [1, 2, 3],_x000D_
  [4, 5, 6],_x000D_
  [7, 8, 9],_x000D_
];_x000D_
_x000D_
console.log(arrayColumn(twoDimensionalArray, 0));
_x000D_
_x000D_
_x000D_

Note: Array.prototype.map() and arrow functions are part of ECMAScript 6 and not supported everywhere, see ECMAScript 6 compatibility table.

Kubernetes Pod fails with CrashLoopBackOff

I ran into the same error.

NAME         READY   STATUS             RESTARTS   AGE
pod/webapp   0/1     CrashLoopBackOff   5          47h

My problem was that I was trying to run two different pods with the same metadata name.

kind: Pod metadata: name: webapp labels: ...

To find all the names of your pods run: kubectl get pods

NAME         READY   STATUS    RESTARTS   AGE
webapp       1/1     Running   15         47h

then I changed the conflicting pod name and everything worked just fine.

NAME                 READY   STATUS    RESTARTS   AGE
webapp               1/1     Running   17         2d
webapp-release-0-5   1/1     Running   0          13m

cut or awk command to print first field of first row

Specify the Line Number using NR built-in variable.

awk 'NR==1{print $1}' /etc/*release

Maven does not find JUnit tests to run

If you created a Spring Boot application using Spring Initializr, tests are running all right from Intellij Idea. But, if try to run tests from a command-line:

mvn clean test

You might have been surprised, that no tests were run at all. I tried to add surefire plugin with no luck. The answer was simple: pom.xml contained the following dependency:

     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
           <exclusion>
              <groupId>org.junit.vintage</groupId>
              <artifactId>junit-vintage-engine</artifactId>
           </exclusion>
        </exclusions>
     </dependency>

The exclusion, junit-vintage-engine, is dedicated for keeping backward compatibility with JUnit 4.x. So, new versions of Spring Boot Initializr do not support it by default. After I removed the exclusion, Maven started to see project's tests.

Run a Java Application as a Service on Linux

However once started I don't know how to access it to stop it

You can write a simple stop script that greps for your java process, extracts the PID and calls kill on it. It's not fancy, but it's straight forward. Something like that may be of help as a start:

#!/bin/bash
PID = ps ax | grep "name of your app" | cut -d ' ' -f 1
kill $PID

how to permit an array with strong parameters

This https://github.com/rails/strong_parameters seems like the relevant section of the docs:

The permitted scalar types are String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch::Http::UploadedFile and Rack::Test::UploadedFile.

To declare that the value in params must be an array of permitted scalar values map the key to an empty array:

params.permit(:id => [])

In my app, the category_ids are passed to the create action in an array

"category_ids"=>["", "2"],

Therefore, when declaring strong parameters, I explicitly set category_ids to be an array

params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids => [])

Works perfectly now!

(IMPORTANT: As @Lenart notes in the comments, the array declarations must be at the end of the attributes list, otherwise you'll get a syntax error.)

AngularJS - convert dates in controller

create a filter.js and you can make this as reusable

angular.module('yourmodule').filter('date', function($filter)
{
    return function(input)
    {
        if(input == null){ return ""; }
        var _date = $filter('date')(new Date(input), 'dd/MM/yyyy');
        return _date.toUpperCase();
    };
});

view

<span>{{ d.time | date }}</span>

or in controller

var filterdatetime = $filter('date')( yourdate );

Date filtering and formatting in Angular js.

Difference between static STATIC_URL and STATIC_ROOT on Django

STATIC_ROOT

The absolute path to the directory where ./manage.py collectstatic will collect static files for deployment. Example: STATIC_ROOT="/var/www/example.com/static/"

now the command ./manage.py collectstatic will copy all the static files(ie in static folder in your apps, static files in all paths) to the directory /var/www/example.com/static/. now you only need to serve this directory on apache or nginx..etc.

STATIC_URL

The URL of which the static files in STATIC_ROOT directory are served(by Apache or nginx..etc). Example: /static/ or http://static.example.com/

If you set STATIC_URL = 'http://static.example.com/', then you must serve the STATIC_ROOT folder (ie "/var/www/example.com/static/") by apache or nginx at url 'http://static.example.com/'(so that you can refer the static file '/var/www/example.com/static/jquery.js' with 'http://static.example.com/jquery.js')

Now in your django-templates, you can refer it by:

{% load static %}
<script src="{% static "jquery.js" %}"></script>

which will render:

<script src="http://static.example.com/jquery.js"></script>

Export DataTable to Excel with Open Xml SDK in c#

You can have a look at my library here. Under the documentation section, you will find how to import a data table.

You just have to write

using (var doc = new SpreadsheetDocument(@"C:\OpenXmlPackaging.xlsx")) {
    Worksheet sheet1 = doc.Worksheets.Add("My Sheet");
    sheet1.ImportDataTable(ds.Tables[0], "A1", true);
}

Hope it helps!

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

To replace with dashes, do the following:

text.replace(/[\W_-]/g,' ');

FtpWebRequest Download File

I had the same issue!

My solution was to insert the public_html folder into the download URL.

Real file location on the server:

myhost.com/public_html/myimages/image.png

Web URL:

www.myhost.com/myimages/image.png

Round up double to 2 decimal places

Consider using NumberFormatter for this purpose, it provides more flexibility if you want to print the percentage sign of the ratio or if you have things like currency and large numbers.

let amount = 10.000001
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 2
let formattedAmount = formatter.string(from: amount as NSNumber)! 
print(formattedAmount) // 10

Android: ScrollView vs NestedScrollView

I think one Benefit of using Nested Scroll view is that the cooridinator layout only listens for nested scroll events. So if for ex. you want the toolbar to scroll down when you scroll you content of activity, it will only scroll down when you are using nested scroll view in your layout. If you use a normal scroll view in your layout, the toolbar wont scroll when the user scrolls the content.

Checking if any elements in one list are in another

Your original approach can work with a list comprehension:

def listCompare():
  list1 = [1, 2, 3, 4, 5]
  list2 = [5, 6, 7, 8, 9]
  if [item for item in list1 if item in list2]:
    print("Number was found")
  else:
    print("Number not in list")

SQL, How to Concatenate results?

It depends on the database you are using. MySQL for example supports the (non-standard) group_concat function. So you could write:

SELECT GROUP_CONCAT(ModuleValue) FROM Table_X WHERE ModuleID=@ModuleID

Group-concat is not available at all database servers though.

How do you copy the contents of an array to a std::vector in C++ without looping?

In addition to the methods presented above, you need to make sure you use either std::Vector.reserve(), std::Vector.resize(), or construct the vector to size, to make sure your vector has enough elements in it to hold your data. if not, you will corrupt memory. This is true of either std::copy() or memcpy().

This is the reason to use vector.push_back(), you can't write past the end of the vector.

How can I get the root domain URI in ASP.NET?

To get the entire request URL string:

HttpContext.Current.Request.Url

To get the www.foo.com portion of the request:

HttpContext.Current.Request.Url.Host

Note that you are, to some degree, at the mercy of factors outside your ASP.NET application. If IIS is configured to accept multiple or any host header for your application, then any of those domains which resolved to your application via DNS may show up as the Request Url, depending on which one the user entered.

How to determine device screen size category (small, normal, large, xlarge) using code?

Try this function isLayoutSizeAtLeast(int screenSize)

To check small screen, atleast 320x426 dp and above getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_SMALL);

To check normal screen, atleast 320x470 dp and above getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_NORMAL);

To check large screen, atleast 480x640 dp and above getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_LARGE);

To check extra large screen, atleast 720x960 dp and above getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_XLARGE);

How to convert PDF files to images

I used PDFiumSharp and ImageSharp in a .NET Standard 2.1 class library.

/// <summary>
/// Saves a thumbnail (jpg) to the same folder as the PDF file, using dimensions 300x423,
/// which corresponds to the aspect ratio of 'A' paper sizes like A4 (ratio h/w=sqrt(2))
/// </summary>
/// <param name="pdfPath">Source path of the pdf file.</param>
/// <param name="thumbnailPath">Target path of the thumbnail file.</param>
/// <param name="width"></param>
/// <param name="height"></param>
public static void SaveThumbnail(string pdfPath, string thumbnailPath = "", int width = 300, int height = 423)
{
    using var pdfDocument = new PdfDocument(pdfPath);
    var firstPage = pdfDocument.Pages[0];

    using var pageBitmap = new PDFiumBitmap(width, height, true);

    firstPage.Render(pageBitmap);

    var imageJpgPath = string.IsNullOrWhiteSpace(thumbnailPath)
        ? Path.ChangeExtension(pdfPath, "jpg")
        : thumbnailPath;
    var image = Image.Load(pageBitmap.AsBmpStream());

    // Set the background to white, otherwise it's black. https://github.com/SixLabors/ImageSharp/issues/355#issuecomment-333133991
    image.Mutate(x => x.BackgroundColor(Rgba32.White));

    image.Save(imageJpgPath, new JpegEncoder());
}

Editing specific line in text file in Python

If your text contains only one individual:

import re

# creation
with open('pers.txt','wb') as g:
    g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 ')

with open('pers.txt','rb') as h:
    print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt before treatment:\n',h.read()


# treatment
def roplo(file_name,what):
    patR = re.compile('^([^\r\n]+[\r\n]+)[^\r\n]+')
    with open(file_name,'rb+') as f:
        ch = f.read()
        f.seek(0)
        f.write(patR.sub('\\1'+what,ch))
roplo('pers.txt','Mage')


# after treatment
with open('pers.txt','rb') as h:
    print '\nexact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt after treatment:\n',h.read()

If your text contains several individuals:

import re

# creation
with open('pers.txt','wb') as g:
    g.write('Dan \n Warrior \n 500 \r\n 1 \r 0 \n Jim  \n  dragonfly\r300\r2\n10\r\nSomo\ncosmonaut\n490\r\n3\r65')

with open('pers.txt','rb') as h:
    print 'exact content of pers.txt before treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt before treatment:\n',h.read()


# treatment
def ripli(file_name,who,what):
    with open(file_name,'rb+') as f:
        ch = f.read()
        x,y = re.search('^\s*'+who+'\s*[\r\n]+([^\r\n]+)',ch,re.MULTILINE).span(1)
        f.seek(x)
        f.write(what+ch[y:])
ripli('pers.txt','Jim','Wizard')


# after treatment
with open('pers.txt','rb') as h:
    print 'exact content of pers.txt after treatment:\n',repr(h.read())
with open('pers.txt','rU') as h:
    print '\nrU-display of pers.txt after treatment:\n',h.read()

If the “job“ of an individual was of a constant length in the texte, you could change only the portion of texte corresponding to the “job“ the desired individual: that’s the same idea as senderle’s one.

But according to me, better would be to put the characteristics of individuals in a dictionnary recorded in file with cPickle:

from cPickle import dump, load

with open('cards','wb') as f:
    dump({'Dan':['Warrior',500,1,0],'Jim':['dragonfly',300,2,10],'Somo':['cosmonaut',490,3,65]},f)

with open('cards','rb') as g:
    id_cards = load(g)
print 'id_cards before change==',id_cards

id_cards['Jim'][0] = 'Wizard'

with open('cards','w') as h:
    dump(id_cards,h)

with open('cards') as e:
    id_cards = load(e)
print '\nid_cards after change==',id_cards

How to convert byte[] to InputStream?

Check out java.io.ByteArrayInputStream

Choosing a jQuery datagrid plugin?

You should look here: https://stackoverflow.com/questions/159025/jquery-grid-recommendations

Update

The link above takes to a question that was closed and then deleted. Here are the original suggestions that were on the most voted answer:

Spring Boot REST API - request timeout?

The @Transactional annotation takes a timeout parameter where you can specify timeout in seconds for a specific method in the @RestController

@RequestMapping(value = "/method",
    method = RequestMethod.POST,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional(timeout = 120)

TABLOCK vs TABLOCKX

Big difference, TABLOCK will try to grab "shared" locks, and TABLOCKX exclusive locks.

If you are in a transaction and you grab an exclusive lock on a table, EG:

SELECT 1 FROM TABLE WITH (TABLOCKX)

No other processes will be able to grab any locks on the table, meaning all queries attempting to talk to the table will be blocked until the transaction commits.

TABLOCK only grabs a shared lock, shared locks are released after a statement is executed if your transaction isolation is READ COMMITTED (default). If your isolation level is higher, for example: SERIALIZABLE, shared locks are held until the end of a transaction.


Shared locks are, hmmm, shared. Meaning 2 transactions can both read data from the table at the same time if they both hold a S or IS lock on the table (via TABLOCK). However, if transaction A holds a shared lock on a table, transaction B will not be able to grab an exclusive lock until all shared locks are released. Read about which locks are compatible with which at msdn.


Both hints cause the db to bypass taking more granular locks (like row or page level locks). In principle, more granular locks allow you better concurrency. So for example, one transaction could be updating row 100 in your table and another row 1000, at the same time from two transactions (it gets tricky with page locks, but lets skip that).

In general granular locks is what you want, but sometimes you may want to reduce db concurrency to increase performance of a particular operation and eliminate the chance of deadlocks.

In general you would not use TABLOCK or TABLOCKX unless you absolutely needed it for some edge case.

pip is not able to install packages correctly: Permission denied error

It looks like you're having a permissions error, based on this message in your output: error: could not create '/lib/python2.7/site-packages/lxml': Permission denied.

One thing you can try is doing a user install of the package with pip install lxml --user. For more information on how that works, check out this StackOverflow answer. (Thanks to Ishaan Taylor for the suggestion)

You can also run pip install as a superuser with sudo pip install lxml but it is not generally a good idea because it can cause issues with your system-level packages.

Finding row index containing maximum value using R

See ?order. You just need the last index (or first, in decreasing order), so this should do the trick:

order(matrix[,2],decreasing=T)[1]

Proxies with Python 'Requests' module

I share some code how to fetch proxies from the site "https://free-proxy-list.net" and store data to a file compatible with tools like "Elite Proxy Switcher"(format IP:PORT):

##PROXY_UPDATER - get free proxies from https://free-proxy-list.net/

from lxml.html import fromstring
import requests
from itertools import cycle
import traceback
import re

######################FIND PROXIES#########################################
def get_proxies():
    url = 'https://free-proxy-list.net/'
    response = requests.get(url)
    parser = fromstring(response.text)
    proxies = set()
    for i in parser.xpath('//tbody/tr')[:299]:   #299 proxies max
        proxy = ":".join([i.xpath('.//td[1]/text()') 
        [0],i.xpath('.//td[2]/text()')[0]])
        proxies.add(proxy)
    return proxies



######################write to file in format   IP:PORT######################
try:
    proxies = get_proxies()
    f=open('proxy_list.txt','w')
    for proxy in proxies:
        f.write(proxy+'\n')
    f.close()
    print ("DONE")
except:
    print ("MAJOR ERROR")

Override element.style using CSS

Of course the !important trick is decisive here, but targeting more specifically may help not only to have your override actually applied (weight criteria can rule over !important) but also to avoid overriding unintended elements.

With the developer tools of your browser, identify the exact value of the offending style attribute; e.g.:

"font-family: arial, helvetica, sans-serif;"

or

"display: block;"

Then, decide which branch of selectors you will override; you can broaden or narrow your choice to fit your needs, e.g.:

p span

or

section.article-into.clearfix p span

Finally, in your custom.css, use the [attribute^=value] selector and the !important declaration:

p span[style^="font-family: arial"] {
  font-family: "Times New Roman", Times, serif !important;
}

Note you don't have to quote the whole style attribute value, just enough to unambigously match the string.

How do I completely remove root password

Did you try passwd -d root? Most likely, this will do what you want.


You can also manually edit /etc/shadow: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to

root:$X$SK5xfLB1ZW:0:0...

There, delete the second field (everything between the first and second colon):

root::0:0...

Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)

root:*:0:0...

Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd, and use mkpasswd to create the second field for the /etc/shadow.)

Convert char to int in C and C++

For char or short to int, you just need to assign the value.

char ch = 16;
int in = ch;

Same to int64.

long long lo = ch;

All values will be 16.

What are the main differences between JWT and OAuth authentication?

It looks like everybody who answered here missed the moot point of OAUTH

From Wikipedia

OAuth is an open standard for access delegation, commonly used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords.[1] This mechanism is used by companies such as Google, Facebook, Microsoft and Twitter to permit the users to share information about their accounts with third party applications or websites.

The key point here is access delegation. Why would anyone create OAUTH when there is an id/pwd based authentication, backed by multifactored auth like OTPs and further can be secured by JWTs which are used to secure the access to the paths (like scopes in OAUTH) and set the expiry of the access

There's no point of using OAUTH if consumers access their resources(your end points) only through their trusted websites(or apps) which are your again hosted on your end points

You can go OAUTH authentication only if you are an OAUTH provider in the cases where the resource owners (users) want to access their(your) resources (end-points) via a third-party client(external app). And it is exactly created for the same purpose though you can abuse it in general

Another important note:
You're freely using the word authentication for JWT and OAUTH but neither provide the authentication mechanism. Yes one is a token mechanism and the other is protocol but once authenticated they are only used for authorization (access management). You've to back OAUTH either with OPENID type authentication or your own client credentials

AddTransient, AddScoped and AddSingleton Services Differences

Which one to use

Transient

  • since they are created every time they will use more memory & Resources and can have the negative impact on performance
  • use this for the lightweight service with little or no state.

Scoped

  • better option when you want to maintain state within a request.

Singleton

  • memory leaks in these services will build up over time.
  • also memory efficient as they are created once reused everywhere.

Use Singletons where you need to maintain application wide state. Application configuration or parameters, Logging Service, caching of data is some of the examples where you can use singletons.

Injecting service with different lifetimes into another

  1. Never inject Scoped & Transient services into Singleton service. ( This effectively converts the transient or scoped service into the singleton.)
  2. Never inject Transient services into scoped service ( This converts the transient service into the scoped. )

How to find if a given key exists in a C++ std::map

C++17 simplified this a bit more with an If statement with initializer. This way you can have your cake and eat it too.

if ( auto it{ m.find( "key" ) }; it != std::end( m ) ) 
{
    // Use `structured binding` to get the key
    // and value.
    auto[ key, value ] { *it };

    // Grab either the key or value stored in the pair.
    // The key is stored in the 'first' variable and
    // the 'value' is stored in the second.
    auto mkey{ it->first };
    auto mvalue{ it->second };

    // That or just grab the entire pair pointed
    // to by the iterator.
    auto pair{ *it };
} 
else 
{
   // Key was not found..
}

How to properly ignore exceptions

It's generally considered best-practice to only catch the errors you are interested in. In the case of shutil.rmtree it's probably OSError:

>>> shutil.rmtree("/fake/dir")
Traceback (most recent call last):
    [...]
OSError: [Errno 2] No such file or directory: '/fake/dir'

If you want to silently ignore that error, you would do:

try:
    shutil.rmtree(path)
except OSError:
    pass

Why? Say you (somehow) accidently pass the function an integer instead of a string, like:

shutil.rmtree(2)

It will give the error "TypeError: coercing to Unicode: need string or buffer, int found" - you probably don't want to ignore that, which can be difficult to debug.

If you definitely want to ignore all errors, catch Exception rather than a bare except: statement. Again, why?

Not specifying an exception catches every exception, including the SystemExit exception which for example sys.exit() uses:

>>> try:
...     sys.exit(1)
... except:
...     pass
... 
>>>

Compare this to the following, which correctly exits:

>>> try:
...     sys.exit(1)
... except Exception:
...     pass
... 
shell:~$ 

If you want to write ever better behaving code, the OSError exception can represent various errors, but in the example above we only want to ignore Errno 2, so we could be even more specific:

import errno

try:
    shutil.rmtree(path)
except OSError as e:
    if e.errno != errno.ENOENT:
        # ignore "No such file or directory", but re-raise other errors
        raise

How can I get a list of all open named pipes in Windows?

You can view these with Process Explorer from sysinternals. Use the "Find -> Find Handle or DLL..." option and enter the pattern "\Device\NamedPipe\". It will show you which processes have which pipes open.

Do you need to dispose of objects and set them to null?

Objects will be cleaned up when they are no longer being used and when the garbage collector sees fit. Sometimes, you may need to set an object to null in order to make it go out of scope (such as a static field whose value you no longer need), but overall there is usually no need to set to null.

Regarding disposing objects, I agree with @Andre. If the object is IDisposable it is a good idea to dispose it when you no longer need it, especially if the object uses unmanaged resources. Not disposing unmanaged resources will lead to memory leaks.

You can use the using statement to automatically dispose an object once your program leaves the scope of the using statement.

using (MyIDisposableObject obj = new MyIDisposableObject())
{
    // use the object here
} // the object is disposed here

Which is functionally equivalent to:

MyIDisposableObject obj;
try
{
    obj = new MyIDisposableObject();
}
finally
{
    if (obj != null)
    {
        ((IDisposable)obj).Dispose();
    }
}

Delete everything in a MongoDB database

  1. List out all available dbs show dbs
  2. Choose the necessary db use
  3. Drop the database db.dropDatabase() //Few additional commands
  4. List all collections available in a db show collections
  5. Remove a specification collection db.collection.drop()

Hope that helps

How to generate a range of numbers between two numbers?

The best option I have used is as follows:

DECLARE @min bigint, @max bigint
SELECT @Min=919859000000 ,@Max=919859999999

SELECT TOP (@Max-@Min+1) @Min-1+row_number() over(order by t1.number) as N
FROM master..spt_values t1 
    CROSS JOIN master..spt_values t2

I have generated millions of records using this and it works perfect.

correct way to define class variables in Python

Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:

  • Elements outside the __init__ method are static elements; they belong to the class.
  • Elements inside the __init__ method are elements of the object (self); they don't belong to the class.

You'll see it more clearly with some code:

class MyClass:
    static_elem = 123

    def __init__(self):
        self.object_elem = 456

c1 = MyClass()
c2 = MyClass()

# Initial values of both elements
>>> print c1.static_elem, c1.object_elem 
123 456
>>> print c2.static_elem, c2.object_elem
123 456

# Nothing new so far ...

# Let's try changing the static element
MyClass.static_elem = 999

>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456

# Now, let's try changing the object element
c1.object_elem = 888

>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456

As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.

How to change the default docker registry from docker.io to my private registry?

Haven't tried, but maybe hijacking the DNS resolution process by adding a line in /etc/hosts for hub.docker.com or something similar (docker.io?) could work?

SQL: Alias Column Name for Use in CASE Statement

@OMG Ponies - One of my reasons of not using the following code

SELECT t.col1 as a, 
     CASE WHEN t.col1 = 'test' THEN 'yes' END as value 
FROM TABLE t;

can be that the t.col1 is not an actual column in the table. For example, it can be a value from a XML column like

Select XMLColumnName.value('(XMLPathOfTag)[1]', 'varchar(max)') 
as XMLTagAlias from Table

NGINX to reverse proxy websockets AND enable SSL (wss://)?

A good, concise article by Pankaj Malhotra discusses how to do this with NGINX and is available here.

The basic NGINX configuration is reproduced below:

map $http_upgrade $connection_upgrade {
    default upgrade;
    '' close;
}

upstream appserver {
    server 192.168.100.10:9222; # appserver_ip:ws_port
}

server {
    listen 8888; // client_wss_port

    ssl on;
    ssl_certificate /path/to/crt;
    ssl_certificate_key /path/to/key;


    location / {
        proxy_pass http://appserver;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }
}

Detect changed input text box

Text inputs do not fire the change event until they lose focus. Click outside of the input and the alert will show.

If the callback should fire before the text input loses focus, use the .keyup() event.

Mailto links do nothing in Chrome but work in Firefox?

In my case, chrome was associated as MAILTO protocol in Windows 10.

I changed the association to Outlook using "Default Programs" -> "Associate a file type or protocol with a program".

MAILTO is way below in the list. This screenshot may help.

enter image description here

`col-xs-*` not working in Bootstrap 4

I just wondered, why col-xs-6 did not work for me but then I found the answer in the Bootstrap 4 documentation. The class prefix for extra small devices is now col- while in the previous versions it was col-xs.

https://getbootstrap.com/docs/4.1/layout/grid/#grid-options

Bootstrap 4 dropped all col-xs-* classes, so use col-* instead. For example col-xs-6 replaced by col-6.

Cannot open local file - Chrome: Not allowed to load local resource

This issue come when I am using PHP as server side language and the work around was to generate base64 enconding of my image before sending the result to client

$path = 'E:/pat/rwanda.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

I think may give someone idea to create his own work around

Thanks

Delete specific line number(s) from a text file using sed?

$ cat foo
1
2
3
4
5
$ sed -e '2d;4d' foo
1
3
5
$ 

NuGet: 'X' already has a dependency defined for 'Y'

In a project using vs 2010, I was only able to solve the problem by installing an older version of the package that I needed via Package Manager Console.

This command worked:

PM> Install-Package EPPlus -Version 4.5.3.1

This command did not work:

PM> Install-Package EPPlus -Version 4.5.3.2

Java - how do I write a file to a specified directory

Use:

File file = new File("Z:\\results\\results.txt");

You need to double the backslashes in Windows because the backslash character itself is an escape in Java literal strings.

For POSIX system such as Linux, just use the default file path without doubling the forward slash. this is because forward slash is not a escape character in Java.

File file = new File("/home/userName/Documents/results.txt");

Anaconda / Python: Change Anaconda Prompt User Path

Just Type the Drive Location you want to work with: This worked for me! For example you want to change to D drive in windows:

D:\

If you want to change to particular folder in the drive:

cd D:\Newfolder

mysql update query with sub query

Thanks, I didn't have the idea of an UPDATE with INNER JOIN.

In the original query, the mistake was to name the subquery, which must return a value and can't therefore be aliased.

UPDATE Competition
SET Competition.NumberOfTeams =
(SELECT count(*) -- no column alias
  FROM PicksPoints
  WHERE UserCompetitionID is not NULL
  -- put the join condition INSIDE the subquery :
  AND CompetitionID =  Competition.CompetitionID
  group by CompetitionID
) -- no table alias

should do the trick for every record of Competition.

To be noticed :

The effect is NOT EXACTLY the same as the query proposed by mellamokb, which won't update Competition records with no corresponding PickPoints.

Since SELECT id, COUNT(*) GROUP BY id will only count for existing values of ids,

whereas a SELECT COUNT(*) will always return a value, being 0 if no records are selected.

This may, or may not, be a problem for you.

0-aware version of mellamokb query would be :

Update Competition as C
LEFT join (
  select CompetitionId, count(*) as NumberOfTeams
  from PicksPoints as p
  where UserCompetitionID is not NULL
  group by CompetitionID
) as A on C.CompetitionID = A.CompetitionID
set C.NumberOfTeams = IFNULL(A.NumberOfTeams, 0)

In other words, if no corresponding PickPoints are found, set Competition.NumberOfTeams to zero.

How do I count cells that are between two numbers in Excel?

If you have Excel 2007 or later use COUNTIFS with an "S" on the end, i.e.

=COUNTIFS(B2:B292,">10",B2:B292,"<10000")

You may need to change commas , to semi-colons ;

In earlier versions of excel use SUMPRODUCT like this

=SUMPRODUCT((B2:B292>10)*(B2:B292<10000))

Note: if you want to include exactly 10 change > to >= - similarly with 10000, change < to <=

Debug JavaScript in Eclipse

I tried to get aptana running on my ubuntu 10.4. Unfortunately I didn't succeed. Chrome on the other hand, has an eclipse plugin that lets you debug javascript that's running in a chrome instance. Works very well. YOu'll have to install the eclipse plugin you'll find here:

http://code.google.com/p/chromedevtools/

Set Breakpoints in the javascript sources you edit in eclipse and browser your page in chrome. As soon as a javascript breakpoint is hit, the eclipse debugger halts and lets you step into, step over, browse the variables etc. Very nice!

MySQL user DB does not have password columns - Installing MySQL on OSX

This error happens if you did not set the password on install, in this case the mysql using unix-socket plugin.

But if delete the plugin link from settings (table mysql.user) will other problem. This does not fix the problem and creates another problem. To fix the deleted link and set password ("PWD") do:

1) Run with --skip-grant-tables as said above.

If it doesnt works then add the string skip-grant-tables in section [mysqld] of /etc/mysql/mysql.conf.d/mysqld.cnf. Then do sudo service mysql restart.

2) Run mysql -u root -p, then (change "PWD"):

update mysql.user 
    set authentication_string=PASSWORD("PWD"), plugin="mysql_native_password" 
    where User='root' and Host='localhost';    
flush privileges;

quit

then sudo service mysql restart. Check: mysql -u root -p.

Before restart remove that string from file mysqld.cnf, if you set it there.

SELECT using 'CASE' in SQL

which platform ?

SELECT 
  CASE 
    WHEN FRUIT = 'A' THEN 'APPLE' 
    ELSE FRUIT ='B' THEN 'BANANA' 
   END AS FRUIT     
FROM FRUIT_TABLE;

How to compare two date values with jQuery

var startDt=document.getElementById("startDateId").value;
var endDt=document.getElementById("endDateId").value;

if( (new Date(startDt).getTime() > new Date(endDt).getTime()))
{
    ----------------------------------
}

What is the default username and password in Tomcat?

If your apache tomcat asking for password,then just follow these steps: go to the home directory of apache then go to webapps folder open the META-INF inside that you will find an xml file named context.xml--open it in edit mode

and REMOVE THE COMMENT FROM the VALVE tag.

After that you dont need any user name and password.

How to pass parameters using ui-sref in ui-router to controller

You simply misspelled $stateParam, it should be $stateParams (with an s). That's why you get undefined ;)

Why does CSS not support negative padding?

I recently answered a different question where I discussed why the box model is the way it is.

There are specific reasons for each part of the box model. Padding is meant to extend the background beyond its contents. If you need to shrink the background of the container, you should make the parent container the correct size and give the child element some negative margins. In this case the content is not being padded, it's overflowing.

Compare two data.frames to find the rows in data.frame 1 that are not present in data.frame 2

You could use the daff package (which wraps the daff.js library using the V8 package):

library(daff)

diff_data(data_ref = a2,
          data = a1)

produces the following difference object:

Daff Comparison: ‘a2’ vs. ‘a1’ 
  First 6 and last 6 patch lines:
   @@   a   b
1 ... ... ...
2       3   c
3 +++   4   d
4 +++   5   e
5 ... ... ...
6 ... ... ...
7       3   c
8 +++   4   d
9 +++   5   e

The tabular diff format is described here and should be pretty self-explanatory. The lines with +++ in the first column @@ are the ones which are new in a1 and not present in a2.

The difference object can be used to patch_data(), to store the difference for documentation purposes using write_diff() or to visualize the difference using render_diff():

render_diff(
    diff_data(data_ref = a2,
              data = a1)
)

generates a neat HTML output:

enter image description here

Count the cells with same color in google spreadsheet

The previous functions didn't work for me, so I've made another function that use the same logic of one of the answers above: parse the formula in the cell to find the referenced range of cells to examine and than look for the coloured cells. You can find a detailed description here: Google Script count coloured with reference, but the code is below:

function countColoured(reference) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var formula = SpreadsheetApp.getActiveRange().getFormula();
  var args = formula.match(/=\w+\((.*)\)/i)[1].split('!');
  try {
    if (args.length == 1) {
      var range = sheet.getRange(args[0]);
    }
    else {
      sheet = ss.getSheetByName(args[0].replace(/'/g, ''));
      range = sheet.getRange(args[1]);
    }
  }
  catch(e) {
    throw new Error(args.join('!') + ' is not a valid range');
  }
  var c = 0;
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();
  for (var i = 1; i <= numRows; i++) {
    for (var j = 1; j <= numCols; j++) {
      c = c + ( range.getCell(i,j).getBackground() == "#ffffff" ? 0 : 1 );
    }
  }
  return c > 0 ? c : "" ;
}

PySpark: multiple conditions in when clause

when in pyspark multiple conditions can be built using &(for and) and | (for or).

Note:In pyspark t is important to enclose every expressions within parenthesis () that combine to form the condition

%pyspark
dataDF = spark.createDataFrame([(66, "a", "4"), 
                                (67, "a", "0"), 
                                (70, "b", "4"), 
                                (71, "d", "4")],
                                ("id", "code", "amt"))
dataDF.withColumn("new_column",
       when((col("code") == "a") | (col("code") == "d"), "A")
      .when((col("code") == "b") & (col("amt") == "4"), "B")
      .otherwise("A1")).show()

In Spark Scala code (&&) or (||) conditions can be used within when function

//scala
val dataDF = Seq(
      (66, "a", "4"), (67, "a", "0"), (70, "b", "4"), (71, "d", "4"
      )).toDF("id", "code", "amt")
dataDF.withColumn("new_column",
       when(col("code") === "a" || col("code") === "d", "A")
      .when(col("code") === "b" && col("amt") === "4", "B")
      .otherwise("A1")).show()

=======================

Output:
+---+----+---+----------+
| id|code|amt|new_column|
+---+----+---+----------+
| 66|   a|  4|         A|
| 67|   a|  0|         A|
| 70|   b|  4|         B|
| 71|   d|  4|         A|
+---+----+---+----------+

This code snippet is copied from sparkbyexamples.com

changing permission for files and folder recursively using shell command in mac

The issue is that the * is getting interpreted by your shell and is expanding to a file named TEST_FILE that happens to be in your current working directory, so you're telling find to execute the command named TEST_FILE which doesn't exist. I'm not sure what you're trying to accomplish with that *, you should just remove it.

Furthermore, you should use the idiom -exec program '{}' \+ instead of -exec program '{}' \; so that find doesn't fork a new process for each file. With ;, a new process is forked for each file, whereas with +, it only forks one process and passes all of the files on a single command line, which for simple programs like chmod is much more efficient.

Lastly, chmod can do recursive changes on its own with the -R flag, so unless you need to search for specific files, just do this:

chmod -R 777 /Users/Test/Desktop/PATH

What's the difference between compiled and interpreted language?

Java and JavaScript are a fairly bad example to demonstrate this difference, because both are interpreted languages. Java (interpreted) and C (or C++) (compiled) might have been a better example.

Why the striked-through text? As this answer correctly points out, interpreted/compiled is about a concrete implementation of a language, not about the language per se. While statements like "C is a compiled language" are generally true, there's nothing to stop someone from writing a C language interpreter. In fact, interpreters for C do exist.

Basically, compiled code can be executed directly by the computer's CPU. That is, the executable code is specified in the CPU's "native" language (assembly language).

The code of interpreted languages however must be translated at run-time from any format to CPU machine instructions. This translation is done by an interpreter.

Another way of putting it is that interpreted languages are code is translated to machine instructions step-by-step while the program is being executed, while compiled languages have code has been translated before program execution.

Android "elevation" not showing a shadow

one other thing that you should be aware of, shadows will not show if you have this line in the manifest:

android:hardwareAccelerated="false"

I tried all of the suggested stuff but it only worked for me when i removed the line, the reason i had the line was because my app works with a number of bitmap images and they were causing the app to crash.

MySQL - force not to use cache for testing speed of query

Whilst some of the answers are good, there is a major caveat.

The mysql queries may be prevented from being cached, but it won't prevent your underlying O.S caching disk accesses into memory. This can be a major slowdown for some queries especially if they need to pull data from spinning disks.

So whilst it's good to use the methods above, I would also try and test with a different set of data/range each time, that's likely not been pulled from disk into disk/memory cache.

CSS selector for "foo that contains bar"?

Is there any way you could programatically apply a class to the object?

<object class="hasparams">

then do

object.hasparams

How to split a dos path into its components in Python

I've been bitten loads of times by people writing their own path fiddling functions and getting it wrong. Spaces, slashes, backslashes, colons -- the possibilities for confusion are not endless, but mistakes are easily made anyway. So I'm a stickler for the use of os.path, and recommend it on that basis.

(However, the path to virtue is not the one most easily taken, and many people when finding this are tempted to take a slippery path straight to damnation. They won't realise until one day everything falls to pieces, and they -- or, more likely, somebody else -- has to work out why everything has gone wrong, and it turns out somebody made a filename that mixes slashes and backslashes -- and some person suggests that the answer is "not to do that". Don't be any of these people. Except for the one who mixed up slashes and backslashes -- you could be them if you like.)

You can get the drive and path+file like this:

drive, path_and_file = os.path.splitdrive(path)

Get the path and the file:

path, file = os.path.split(path_and_file)

Getting the individual folder names is not especially convenient, but it is the sort of honest middling discomfort that heightens the pleasure of later finding something that actually works well:

folders = []
while 1:
    path, folder = os.path.split(path)

    if folder != "":
        folders.append(folder)
    elif path != "":
        folders.append(path)

        break

folders.reverse()

(This pops a "\" at the start of folders if the path was originally absolute. You could lose a bit of code if you didn't want that.)

Command to change the default home directory of a user

Found out that this breaks some applications, the better way to do it is

In addition to symlink, on more recent distros and filesystems, as root you can also use bind-mount:

mkdir /home/username 
mount --bind --verbose /extra-home/username /home/username

This is useful for allowing access "through" the /home directory to subdirs via daemons that are otherwise configured to avoid pathing through symlinks (apache, ftpd, etc.).

You have to remember (or init script) to bind upon restarts, of course.

An example init script in /etc/fstab is

/extra-home/username /home/username none defaults,bind 0 0

How to compile without warnings being treated as errors?

Remove -Werror from your Make or CMake files, as suggested in this post

Maven is not working in Java 8 when Javadoc tags are incomplete

I'm not sure if this is going to help, but even i faced the exact same problem very recently with oozie-4.2.0 version. After reading through the above answers i have just added the maven option through command line and it worked for me. So, just sharing here.

I'm using java 1.8.0_77, haven't tried with java 1.7

bin/mkdistro.sh -DskipTests -Dmaven.javadoc.opts='-Xdoclint:-html'

Open URL in new window with JavaScript

Use window.open():

<a onclick="window.open(document.URL, '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes');">
  Share Page
</a>

This will create a link titled Share Page which opens the current url in a new window with a height of 570 and width of 520.

How to make HTML element resizable using pure Javascript?

There are very good examples here to start trying with, but all of them are based on adding some extra or external element like a "div" as a reference element to drag it, and calculate the new dimensions or position of the original element.

Here's an example that doesn't use any extra elements. We could add borders, padding or margin without affecting its operation. In this example we have not added color, nor any visual reference to the borders nor to the lower right corner as a clue where you can enlarge or reduce dimensions, but using the cursor around the resizable elements the clues appears!

let resizerForCenter = new Resizer('center')  
resizerForCenter.initResizer()

See it in action with CodeSandbox:

In this example we use ES6, and a module that exports a class called Resizer. An example is worth a thousand words:

Edit boring-snow-qz1sd

Or with the code snippet:

_x000D_
_x000D_
const html = document.querySelector('html')_x000D_
_x000D_
class Resizer {_x000D_
 constructor(elemId) {_x000D_
  this._elem = document.getElementById(elemId)_x000D_
  /**_x000D_
   * Stored binded context handlers for method passed to eventListeners!_x000D_
   * _x000D_
   * See: https://stackoverflow.com/questions/9720927/removing-event-listeners-as-class-prototype-functions_x000D_
   */_x000D_
  this._checkBorderHandler = this._checkBorder.bind(this)_x000D_
  this._doResizeHandler  = this._doResize.bind(this)_x000D_
  this._initResizerHandler = this.initResizer.bind(this)_x000D_
  this._onResizeHandler  = this._onResize.bind(this)_x000D_
 }_x000D_
_x000D_
 initResizer() {_x000D_
  this.stopResizer()_x000D_
  this._beginResizer()_x000D_
 }_x000D_
_x000D_
 _beginResizer() {_x000D_
  this._elem.addEventListener('mousemove', this._checkBorderHandler, false)_x000D_
 }_x000D_
_x000D_
 stopResizer() {_x000D_
  html.style.cursor = 'default'_x000D_
  this._elem.style.cursor = 'default'_x000D_
  _x000D_
  window.removeEventListener('mousemove', this._doResizeHandler, false)_x000D_
  window.removeEventListener('mouseup', this._initResizerHandler, false)_x000D_
_x000D_
  this._elem.removeEventListener('mousedown', this._onResizeHandler, false)_x000D_
  this._elem.removeEventListener('mousemove', this._checkBorderHandler, false)_x000D_
 }_x000D_
_x000D_
 _doResize(e) {_x000D_
  let elem = this._elem_x000D_
_x000D_
  let boxSizing = getComputedStyle(elem).boxSizing_x000D_
  let borderRight = 0_x000D_
  let borderLeft = 0_x000D_
  let borderTop = 0_x000D_
  let borderBottom = 0_x000D_
_x000D_
  let paddingRight = 0_x000D_
  let paddingLeft = 0_x000D_
  let paddingTop = 0_x000D_
  let paddingBottom = 0_x000D_
_x000D_
  switch (boxSizing) {_x000D_
   case 'content-box':_x000D_
     paddingRight = parseInt(getComputedStyle(elem).paddingRight)_x000D_
     paddingLeft = parseInt(getComputedStyle(elem).paddingLeft)_x000D_
     paddingTop = parseInt(getComputedStyle(elem).paddingTop)_x000D_
     paddingBottom = parseInt(getComputedStyle(elem).paddingBottom)_x000D_
    break_x000D_
   case 'border-box':_x000D_
     borderRight = parseInt(getComputedStyle(elem).borderRight)_x000D_
     borderLeft = parseInt(getComputedStyle(elem).borderLeft)_x000D_
     borderTop = parseInt(getComputedStyle(elem).borderTop)_x000D_
     borderBottom = parseInt(getComputedStyle(elem).borderBottom)_x000D_
    break_x000D_
   default: break_x000D_
  }_x000D_
_x000D_
  let horizontalAdjustment = (paddingRight + paddingLeft) - (borderRight + borderLeft)_x000D_
  let verticalAdjustment  = (paddingTop + paddingBottom) - (borderTop + borderBottom)_x000D_
_x000D_
  let newWidth = elem.clientWidth  + e.movementX - horizontalAdjustment + 'px'_x000D_
  let newHeight = elem.clientHeight + e.movementY - verticalAdjustment   + 'px'_x000D_
  _x000D_
  let cursorType = getComputedStyle(elem).cursor_x000D_
  switch (cursorType) {_x000D_
   case 'all-scroll':_x000D_
     elem.style.width = newWidth_x000D_
     elem.style.height = newHeight_x000D_
    break_x000D_
   case 'col-resize':_x000D_
     elem.style.width = newWidth_x000D_
    break_x000D_
   case 'row-resize':_x000D_
     elem.style.height = newHeight_x000D_
    break_x000D_
   default: break_x000D_
  }_x000D_
 }_x000D_
_x000D_
 _onResize(e) {_x000D_
  // On resizing state!_x000D_
  let elem = e.target_x000D_
  let newCursorType = undefined_x000D_
  let cursorType = getComputedStyle(elem).cursor_x000D_
  switch (cursorType) {_x000D_
   case 'nwse-resize':_x000D_
    newCursorType = 'all-scroll'_x000D_
    break_x000D_
   case 'ew-resize':_x000D_
    newCursorType = 'col-resize'_x000D_
    break_x000D_
   case 'ns-resize':_x000D_
    newCursorType = 'row-resize'_x000D_
    break_x000D_
   default: break_x000D_
  }_x000D_
  _x000D_
  html.style.cursor = newCursorType // Avoid cursor's flickering _x000D_
  elem.style.cursor = newCursorType_x000D_
  _x000D_
  // Remove what is not necessary, and could have side effects!_x000D_
  elem.removeEventListener('mousemove', this._checkBorderHandler, false);_x000D_
  _x000D_
  // Events on resizing state_x000D_
  /**_x000D_
   * We do not apply the mousemove event on the elem to resize it, but to the window to prevent the mousemove from slippe out of the elem to resize. This work bc we calculate things based on the mouse position_x000D_
   */_x000D_
  window.addEventListener('mousemove', this._doResizeHandler, false);_x000D_
  window.addEventListener('mouseup', this._initResizerHandler, false);_x000D_
 }_x000D_
_x000D_
 _checkBorder(e) {_x000D_
  const elem = e.target_x000D_
  const borderSensitivity = 5_x000D_
  const coor = getCoordenatesCursor(e)_x000D_
  const onRightBorder  = ((coor.x + borderSensitivity) > elem.scrollWidth)_x000D_
  const onBottomBorder = ((coor.y + borderSensitivity) > elem.scrollHeight)_x000D_
  const onBottomRightCorner = (onRightBorder && onBottomBorder)_x000D_
  _x000D_
  if (onBottomRightCorner) {_x000D_
   elem.style.cursor = 'nwse-resize'_x000D_
  } else if (onRightBorder) {_x000D_
   elem.style.cursor = 'ew-resize'_x000D_
  } else if (onBottomBorder) {_x000D_
   elem.style.cursor = 'ns-resize'_x000D_
  } else {_x000D_
   elem.style.cursor = 'auto'_x000D_
  }_x000D_
  _x000D_
  if (onRightBorder || onBottomBorder) {_x000D_
   elem.addEventListener('mousedown', this._onResizeHandler, false)_x000D_
  } else {_x000D_
   elem.removeEventListener('mousedown', this._onResizeHandler, false)_x000D_
  }_x000D_
 }_x000D_
}_x000D_
_x000D_
function getCoordenatesCursor(e) {_x000D_
 let elem = e.target;_x000D_
 _x000D_
 // Get the Viewport-relative coordinates of cursor._x000D_
 let viewportX = e.clientX_x000D_
 let viewportY = e.clientY_x000D_
 _x000D_
 // Viewport-relative position of the target element._x000D_
 let elemRectangle = elem.getBoundingClientRect()_x000D_
 _x000D_
 // The  function returns the largest integer less than or equal to a given number._x000D_
 let x = Math.floor(viewportX - elemRectangle.left) // - elem.scrollWidth_x000D_
 let y = Math.floor(viewportY - elemRectangle.top) // - elem.scrollHeight_x000D_
 _x000D_
 return {x, y}_x000D_
}_x000D_
_x000D_
let resizerForCenter = new Resizer('center')_x000D_
resizerForCenter.initResizer()_x000D_
_x000D_
let resizerForLeft = new Resizer('left')_x000D_
resizerForLeft.initResizer()_x000D_
_x000D_
setTimeout(handler, 10000, true); // 10s_x000D_
_x000D_
function handler() {_x000D_
  resizerForCenter.stopResizer()_x000D_
}
_x000D_
body {_x000D_
 background-color: white;_x000D_
}_x000D_
_x000D_
#wrapper div {_x000D_
 /* box-sizing: border-box; */_x000D_
 position: relative;_x000D_
 float:left;_x000D_
 overflow: hidden;_x000D_
 height: 50px;_x000D_
 width: 50px;_x000D_
 padding: 3px;_x000D_
}_x000D_
_x000D_
#left {_x000D_
 background-color: blueviolet;_x000D_
}_x000D_
#center {_x000D_
 background-color:lawngreen ;_x000D_
}_x000D_
#right {_x000D_
 background: blueviolet;_x000D_
}_x000D_
#wrapper {_x000D_
 border: 5px solid hotpink;_x000D_
 display: inline-block;_x000D_
 _x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
 <meta charset="UTF-8">_x000D_
 <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
 <meta http-equiv="X-UA-Compatible" content="ie=edge">_x000D_
 <title>Resizer v0.0.1</title>_x000D_
</head>_x000D_
  <body>_x000D_
    <div id="wrapper">_x000D_
      <div id="left">Left</div>_x000D_
      <div id="center">Center</div>_x000D_
      <div id="right">Right</div>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Overwriting txt file in java

Your code works fine for me. It replaced the text in the file as expected and didn't append.

If you wanted to append, you set the second parameter in

new FileWriter(fnew,false);

to true;

How to add a new row to an empty numpy array

The way to "start" the array that you want is:

arr = np.empty((0,3), int)

Which is an empty array but it has the proper dimensionality.

>>> arr
array([], shape=(0, 3), dtype=int64)

Then be sure to append along axis 0:

arr = np.append(arr, np.array([[1,2,3]]), axis=0)
arr = np.append(arr, np.array([[4,5,6]]), axis=0)

But, @jonrsharpe is right. In fact, if you're going to be appending in a loop, it would be much faster to append to a list as in your first example, then convert to a numpy array at the end, since you're really not using numpy as intended during the loop:

In [210]: %%timeit
   .....: l = []
   .....: for i in xrange(1000):
   .....:     l.append([3*i+1,3*i+2,3*i+3])
   .....: l = np.asarray(l)
   .....: 
1000 loops, best of 3: 1.18 ms per loop

In [211]: %%timeit
   .....: a = np.empty((0,3), int)
   .....: for i in xrange(1000):
   .....:     a = np.append(a, 3*i+np.array([[1,2,3]]), 0)
   .....: 
100 loops, best of 3: 18.5 ms per loop

In [214]: np.allclose(a, l)
Out[214]: True

The numpythonic way to do it depends on your application, but it would be more like:

In [220]: timeit n = np.arange(1,3001).reshape(1000,3)
100000 loops, best of 3: 5.93 µs per loop

In [221]: np.allclose(a, n)
Out[221]: True

How to force Chrome's script debugger to reload javascript?

For Google chrome it is not Ctrl+F5. It's Shift+F5 to clear the current cache! It works for me !

How can I use getSystemService in a non-activity class (LocationManager)?

For some non-activity classes, like Worker, you're already given a Context object in the public constructor.

Worker(Context context, WorkerParameters workerParams)

You can just use that, e.g., save it to a private Context variable in the class (say, mContext), and then, for example

mContext.getSystenService(Context.ACTIVITY_SERVICE)

What is the purpose of Node.js module.exports and how do you use it?

module.exports is the object that's actually returned as the result of a require call.

The exports variable is initially set to that same object (i.e. it's a shorthand "alias"), so in the module code you would usually write something like this:

let myFunc1 = function() { ... };
let myFunc2 = function() { ... };
exports.myFunc1 = myFunc1;
exports.myFunc2 = myFunc2;

to export (or "expose") the internally scoped functions myFunc1 and myFunc2.

And in the calling code you would use:

const m = require('./mymodule');
m.myFunc1();

where the last line shows how the result of require is (usually) just a plain object whose properties may be accessed.

NB: if you overwrite exports then it will no longer refer to module.exports. So if you wish to assign a new object (or a function reference) to exports then you should also assign that new object to module.exports


It's worth noting that the name added to the exports object does not have to be the same as the module's internally scoped name for the value that you're adding, so you could have:

let myVeryLongInternalName = function() { ... };
exports.shortName = myVeryLongInternalName;
// add other objects, functions, as required

followed by:

const m = require('./mymodule');
m.shortName(); // invokes module.myVeryLongInternalName

HTML embed autoplay="false", but still plays automatically

Chrome doesn't seem to understand true and false. Use autostart="1" and autostart="0" instead.


Source: (Google Groups: https://productforums.google.com/forum/#!topic/chrome/LkA8FoBoleU)

Invoking modal window in AngularJS Bootstrap UI using JavaScript

Open modal windows with passing data to dialog

In case if someone interests to pass data to dialog:

app.controller('ModalCtrl', function($scope,  $modal) {
      
      $scope.name = 'theNameHasBeenPassed';

      $scope.showModal = function() {
        
        $scope.opts = {
        backdrop: true,
        backdropClick: true,
        dialogFade: false,
        keyboard: true,
        templateUrl : 'modalContent.html',
        controller : ModalInstanceCtrl,
        resolve: {} // empty storage
          };
          
        
        $scope.opts.resolve.item = function() {
            return angular.copy(
                                {name: $scope.name}
                          ); // pass name to resolve storage
        }
        
          var modalInstance = $modal.open($scope.opts);
          
          modalInstance.result.then(function(){
            //on ok button press 
          },function(){
            //on cancel button press
            console.log("Modal Closed");
          });
      };                   
})

var ModalInstanceCtrl = function($scope, $modalInstance, $modal, item) {
    
     $scope.item = item;
    
      $scope.ok = function () {
        $modalInstance.close();
      };
      
      $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
      };
}

Demo Plunker

Add a column to existing table and uniquely number them on MS SQL Server

for oracle you could do something like below

alter table mytable add (myfield integer);

update mytable set myfield = rownum;

How do I change the select box arrow

CSS

select.inpSelect {
  //Remove original arrows
  -webkit-appearance: none; 
  //Use png at assets/selectArrow.png for the arrow on the right
  //Set the background color to a BadAss Green color 
  background: url(assets/selectArrow.png) no-repeat right #BADA55;
}

How do SO_REUSEADDR and SO_REUSEPORT differ?

Mecki's answer is absolutly perfect, but it's worth adding that FreeBSD also supports SO_REUSEPORT_LB, which mimics Linux' SO_REUSEPORT behaviour - it balances the load; see setsockopt(2)

How to var_dump variables in twig templates?

If you are using Twig in your application as a component you can do this:

$twig = new Twig_Environment($loader, array(
    'autoescape' => false
));

$twig->addFilter('var_dump', new Twig_Filter_Function('var_dump'));

Then in your templates:

{{ my_variable | var_dump }}

How to set an environment variable only for the duration of the script?

Just put

export HOME=/blah/whatever

at the point in the script where you want the change to happen. Since each process has its own set of environment variables, this definition will automatically cease to have any significance when the script terminates (and with it the instance of bash that has a changed environment).

How to add image for button in android?

Rather humorously, considering your tags, just use the ImageButton widget.

Prevent Sequelize from outputting SQL to the console on execution of query?

When you create your Sequelize object, pass false to the logging parameter:

var sequelize = new Sequelize('database', 'username', 'password', {
  
  // disable logging; default: console.log
  logging: false

});

For more options, check the docs.

How to create a service running a .exe file on Windows 2012 Server?

You can use PowerShell.

New-Service -Name "TestService" -BinaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"

Refer - https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-service?view=powershell-3.0

How to remove youtube branding after embedding video in web page?

The only way to remove the YouTube branding (while keeping the video clickable) is to place the embed iFrame inside a container that has overflow set to hidden and has a slightly smaller height than the iFrame.

Of course this means the bottom of your video gets chopped off.

Also, you will be most likely breaching YouTube's Terms of Service.

CSS:

.videoWrapper {
  width: 550px;
  height: 250px;
  overflow: hidden;
}

HTML:

<div class="videoWrapper">
  <iframe width="550" height="314" src="https://www.youtube.com/embed/vidid?modestbranding=1&amp;rel=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>
</div>

How to make System.out.println() shorter

In Java 8 :

    List<String> players = new ArrayList<>();
     players.forEach(System.out::println);

Change the "From:" address in Unix "mail"

echo "body" | mail -S [email protected] "Hello"

-S lets you specify lots of string options, by far the easiest way to modify headers and such.

Filezilla FTP Server Fails to Retrieve Directory Listing

When you send the port command to your server, you are asking the server to connect to you (on the remote network). If the remote network also has a NAT router, and you have not port-forwarded the port you are sending with your PORT command, the server will not be able reach you.

The most common solution would be to send the PASV command to the server instead of the PORT command. The PASV command will ask the server to create a listening socket and accept a connection from the remote machine to establish the data connection.

For the PASV command to work, you will also need to port-forward a range of ports for the passive data connections. The passive connection ports (which need to be forwarded) should be listed in the FileZilla documentation.

MySQL Sum() multiple columns

SELECT student, SUM(mark1+mark2+mark3+....+markn) AS Total FROM your_table

How to configure the web.config to allow requests of any length

I had to add [AllowAnonymous] to the ActionResult functions in my login page because the user was not authenticated yet.

Python integer division yields float

Hope it might help someone instantly.

Behavior of Division Operator in Python 2.7 and Python 3

In Python 2.7: By default, division operator will return integer output.

to get the result in double multiple 1.0 to "dividend or divisor"

100/35 => 2 #(Expected is 2.857142857142857)
(100*1.0)/35 => 2.857142857142857
100/(35*1.0) => 2.857142857142857

In Python 3

// => used for integer output
/ => used for double output

100/35 => 2.857142857142857
100//35 => 2
100.//35 => 2.0    # floating-point result if divsor or dividend real

How can I use interface as a C# generic type constraint?

What you have settled for is the best you can do:

public bool Foo<T>() where T : IBase;

relative path in require_once doesn't work

Use

__DIR__

to get the current path of the script and this should fix your problem.

So:

require_once(__DIR__.'/../class/user.php');

This will prevent cases where you can run a PHP script from a different folder and therefore the relatives paths will not work.

Edit: slash problem fixed

Iterating over each line of ls -l output

So, why didn't anybody suggest just using options that eliminate the parts he doesn't want to process.

On modern Debian you just get your file with:

ls --format=single-column 

Further more, you don't have to pay attention to what directory you are running it in if you use the full directory:

ls --format=single-column /root/dir/starting/point/to/target/dir/

This last command I am using the above and I get the following output:

bot@dev:~/downloaded/Daily# ls --format=single-column /home/bot/downloaded/Daily/*.gz
/home/bot/downloaded/Daily/Liq_DailyManifest_V3_US_20141119_IENT1.txt.gz
/home/bot/downloaded/Daily/Liq_DailyManifest_V3_US_20141120_IENT1.txt.gz
/home/bot/downloaded/Daily/Liq_DailyManifest_V3_US_20141121_IENT1.txt.gz

How to save a new sheet in an existing excel file, using Pandas?

You can read existing sheets of your interests, for example, 'x1', 'x2', into memory and 'write' them back prior to adding more new sheets (keep in mind that sheets in a file and sheets in memory are two different things, if you don't read them, they will be lost). This approach uses 'xlsxwriter' only, no openpyxl involved.

import pandas as pd
import numpy as np

path = r"C:\Users\fedel\Desktop\excelData\PhD_data.xlsx"

# begin <== read selected sheets and write them back
df1 = pd.read_excel(path, sheet_name='x1', index_col=0) # or sheet_name=0
df2 = pd.read_excel(path, sheet_name='x2', index_col=0) # or sheet_name=1
writer = pd.ExcelWriter(path, engine='xlsxwriter')
df1.to_excel(writer, sheet_name='x1')
df2.to_excel(writer, sheet_name='x2')
# end ==>

# now create more new sheets
x3 = np.random.randn(100, 2)
df3 = pd.DataFrame(x3)

x4 = np.random.randn(100, 2)
df4 = pd.DataFrame(x4)

df3.to_excel(writer, sheet_name='x3')
df4.to_excel(writer, sheet_name='x4')
writer.save()
writer.close()

If you want to preserve all existing sheets, you can replace above code between begin and end with:

# read all existing sheets and write them back
writer = pd.ExcelWriter(path, engine='xlsxwriter')
xlsx = pd.ExcelFile(path)
for sheet in xlsx.sheet_names:
    df = xlsx.parse(sheet_name=sheet, index_col=0)
    df.to_excel(writer, sheet_name=sheet)

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 

Java for loop syntax: "for (T obj : objects)"

public class ForEachLoopExample {

    public static void main(String[] args) {

        System.out.println("For Each Loop Example: ");

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

        //Here iteration starts from index 0 to last index
        for(int i : intArray)
            System.out.println(i);
    }

}

Remove all non-"word characters" from a String in Java, leaving accented characters?

At times you do not want to simply remove the characters, but just remove the accents. I came up with the following utility class which I use in my Java REST web projects whenever I need to include a String in an URL:

import java.text.Normalizer;
import java.text.Normalizer.Form;

import org.apache.commons.lang.StringUtils;

/**
 * Utility class for String manipulation.
 * 
 * @author Stefan Haberl
 */
public abstract class TextUtils {
    private static String[] searchList = { "Ä", "ä", "Ö", "ö", "Ü", "ü", "ß" };
    private static String[] replaceList = { "Ae", "ae", "Oe", "oe", "Ue", "ue",
            "sz" };

    /**
     * Normalizes a String by removing all accents to original 127 US-ASCII
     * characters. This method handles German umlauts and "sharp-s" correctly
     * 
     * @param s
     *            The String to normalize
     * @return The normalized String
     */
    public static String normalize(String s) {
        if (s == null)
            return null;

        String n = null;

        n = StringUtils.replaceEachRepeatedly(s, searchList, replaceList);
        n = Normalizer.normalize(n, Form.NFD).replaceAll("[^\\p{ASCII}]", "");

        return n;
    }

    /**
     * Returns a clean representation of a String which might be used safely
     * within an URL. Slugs are a more human friendly form of URL encoding a
     * String.
     * <p>
     * The method first normalizes a String, then converts it to lowercase and
     * removes ASCII characters, which might be problematic in URLs:
     * <ul>
     * <li>all whitespaces
     * <li>dots ('.')
     * <li>(semi-)colons (';' and ':')
     * <li>equals ('=')
     * <li>ampersands ('&')
     * <li>slashes ('/')
     * <li>angle brackets ('<' and '>')
     * </ul>
     * 
     * @param s
     *            The String to slugify
     * @return The slugified String
     * @see #normalize(String)
     */
    public static String slugify(String s) {

        if (s == null)
            return null;

        String n = normalize(s);
        n = StringUtils.lowerCase(n);
        n = n.replaceAll("[\\s.:;&=<>/]", "");

        return n;
    }
}

Being a German speaker I've included proper handling of German umlauts as well - the list should be easy to extend for other languages.

HTH

EDIT: Note that it may be unsafe to include the returned String in an URL. You should at least HTML encode it to prevent XSS attacks.

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

Jason Bunting's last index of does not work. Mine is not optimal, but it works.

//Jason Bunting's
String.prototype.regexIndexOf = function(regex, startpos) {
var indexOf = this.substring(startpos || 0).search(regex);
return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}

String.prototype.regexLastIndexOf = function(regex, startpos) {
var lastIndex = -1;
var index = this.regexIndexOf( regex );
startpos = startpos === undefined ? this.length : startpos;

while ( index >= 0 && index < startpos )
{
    lastIndex = index;
    index = this.regexIndexOf( regex, index + 1 );
}
return lastIndex;
}

In vb.net, how to get the column names from a datatable

You can loop through the columns collection of the datatable.

VB

Dim dt As New DataTable()
For Each column As DataColumn In dt.Columns
    Console.WriteLine(column.ColumnName)
Next

C#

DataTable dt = new DataTable();
foreach (DataColumn column in dt.Columns)
{
Console.WriteLine(column.ColumnName);
}

Hope this helps!

How to restrict SSH users to a predefined set of commands after login?

You can also restrict keys to permissible commands (in the authorized_keys file).

I.e. the user would not log in via ssh and then have a restricted set of commands but rather would only be allowed to execute those commands via ssh (e.g. "ssh somehost bin/showlogfile")

How does a PreparedStatement avoid or prevent SQL injection?

I guess it will be a string. But the input parameters will be sent to the database & appropriate cast/conversions will be applied prior to creating an actual SQL statement.

To give you an example, it might try and see if the CAST/Conversion works.
If it works, it could create a final statement out of it.

   SELECT * From MyTable WHERE param = CAST('10; DROP TABLE Other' AS varchar(30))

Try an example with a SQL statement accepting a numeric parameter.
Now, try passing a string variable (with numeric content that is acceptable as numeric parameter). Does it raise any error?

Now, try passing a string variable (with content that is not acceptable as numeric parameter). See what happens?

Finding and removing non ascii characters from an Oracle Varchar2

You can try something like following to search for the column containing non-ascii character :

select * from your_table where your_col <> asciistr(your_col);

Export tables to an excel spreadsheet in same directory

For people who find this via search engines, you do not need VBA. You can just:

1.) select the query or table with your mouse
2.) click export data from the ribbon
3.) click excel from the export subgroup
4.) follow the wizard to select the output file and location.

How can one check to see if a remote file exists using PHP?

If you are dealing with images, use getimagesize. Unlike file_exists, this built-in function supports remote files. It will return an array that contains the image information (width, height, type..etc). All you have to do is to check the first element in the array (the width). use print_r to output the content of the array

$imageArray = getimagesize("http://www.example.com/image.jpg");
if($imageArray[0])
{
    echo "it's an image and here is the image's info<br>";
    print_r($imageArray);
}
else
{
    echo "invalid image";
}

How to install node.js as windows service?

From this blog

Next up, I wanted to host node as a service, just like IIS. This way it’d start up with my machine, run in the background, restart automatically if it crashes and so forth.

This is where nssm, the non-sucking service manager, enters the picture. This tool lets you host a normal .exe as a Windows service.

Here are the commands I used to setup an instance of the your node application as a service, open your cmd like administrator and type following commands:

nssm.exe install service_name c:\your_nodejs_directory\node.exe c:\your_application_directory\server.js
net start service_name

In Python, how do I create a string of n characters in one line of code?

If you can use repeated letters, you can use the * operator:

>>> 'a'*5

'aaaaa'

How to use regex with find command?

Try to use single quotes (') to avoid shell escaping of your string. Remember that the expression needs to match the whole path, i.e. needs to look like:

 find . -regex '\./[a-f0-9-]*.jpg'

Apart from that, it seems that my find (GNU 4.4.2) only knows basic regular expressions, especially not the {36} syntax. I think you'll have to make do without it.

Application Installation Failed in Android Studio

At me such error arose after renaming of a folder with the project.

Disabling Instance Run helped, but what if you do not need to disable it?

I deleted all the tags mentioning the old folder name from the file myproject\app\build\intermediates\restart-dex\debug\build-info.xml

The error has disappeared.

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

You have 3 options:

1) Get default value

dt = datetime??DateTime.Now;

it will assign DateTime.Now (or any other value which you want) if datetime is null

2) Check if datetime contains value and if not return empty string

if(!datetime.HasValue) return "";
dt = datetime.Value;

3) Change signature of method to

public string ConvertToPersianToShow(DateTime  datetime)

It's all because DateTime? means it's nullable DateTime so before assigning it to DateTime you need to check if it contains value and only then assign.

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

Blockquote

I then modified the php.ini file to use it (commented out the other lines):

[mail function]
; For Win32 only.
; SMTP = smtp.gmail.com
; smtp_port = 25

; For Win32 only.
; sendmail_from = <e-mail username>@gmail.com

; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

Ignore the "For Unix only" comment, as this version of sendmail works for Windows.

You then have to configure the "sendmail.ini" file in the directory where sendmail was installed:

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
auth_username=<username>
auth_password=<password>
force_sender=<e-mail username>@gmail.com

http://byitcurious.blogspot.com.br/2009/04/solving-must-issue-starttls-command.html

> Blockquote

Set background image according to screen resolution

Pure CSS approaches that work very well are discussed here. Two techniques are examined in particular and I personally prefer the second as it not CSS3 dependent, which suits my own needs better.

If most/all of your traffic has a CSS3 capable browser, the first method is quicker and cleaner to implement (copy/pasted by Mr. Zoidberg in another answer here for convenience, though I'd visit the source for further background on why it works).

An alternative method to CSS is to use the JavaScript library jQuery to detect resolution changes and adjust the image size accordingly. This article covers the jQuery technique and provides a live demo.

Supersized is a dedicated JavaScript library designed for static full screen images as well as full sized slideshows.

A good tip for full-screen images is to scale them with a correct ratio beforehand. I normally aim for a size of 1500x1000 when using supersized.js or 1680x1050 for other methods, setting the jpg quality for photographs to between 60-80% resulting in a file size in the region of 100kb or less if possible without compromising quality too much.

How to mock private method for testing using PowerMock?

A generic solution that will work with any testing framework (if your class is non-final) is to manually create your own mock.

  1. Change your private method to protected.
  2. In your test class extend the class
  3. override the previously-private method to return whatever constant you want

This doesn't use any framework so its not as elegant but it will always work: even without PowerMock. Alternatively, you can use Mockito to do steps #2 & #3 for you, if you've done step #1 already.

To mock a private method directly, you'll need to use PowerMock as shown in the other answer.

How to play videos in android from assets folder or raw folder?

  1. Use the MediaPlayer API and the sample code.

  2. Put the media file in raw folder.

  3. Get the file descriptor to the file.

  4. mediaplayer.setDataSource(fd,offset,length); - its a three argument constructor.

  5. Then when onPreared , mediaplayer.start();

How to increment a letter N times per iteration and store in an array?

Here is your solution for the problem,

$letter = array();
for ($i = 'A'; $i !== 'ZZ'; $i++){
        if(ord($i) % 2 != 0)
           $letter[] .= $i;
}
print_r($letter);

You need to get the ASCII value for that character which will solve your problem.

Here is ord doc and working code.

For your requirement, you can do like this,

for ($i = 'A'; $i !== 'ZZ'; ord($i)+$x){
  $letter[] .= $i;
}
print_r($letter);

Here set $x as per your requirement.

IPython Notebook save location

Just cd to your working folder and then start the IPython notebook server. This way you can be mobile.

How to determine if .NET Core is installed

The following commands are available with .NET Core SDK 2.1 (v2.1.300):

To list all installed .NET Core SDKs use: dotnet --list-sdks

To list all installed .NET Core runtimes use dotnet --list-runtimes

(tested on Windows as of writing, 03 Jun 2018, and again on 23 Aug 2018)

Update as of 24 Oct 2018: Better option is probably now dotnet --info in a terminal or PowerShell window as already mentioned in other answers.

How are "mvn clean package" and "mvn clean install" different?

What clean does (common in both the commands) - removes all files generated by the previous build


Coming to the difference between the commands package and install, you first need to understand the lifecycle of a maven project


These are the default life cycle phases in maven

  • validate - validate the project is correct and all necessary information is available
  • compile - compile the source code of the project
  • test - test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package - take the compiled code and package it in its distributable format, such as a JAR.
  • verify - run any checks on results of integration tests to ensure quality criteria are met
  • install - install the package into the local repository, for use as a dependency in other projects locally
  • deploy - done in the build environment, copies the final package to the remote repository for sharing with other developers and projects.

How Maven works is, if you run a command for any of the lifecycle phases, it executes each default life cycle phase in order, before executing the command itself.

order of execution

validate >> compile >> test (optional) >> package >> verify >> install >> deploy

So when you run the command mvn package, it runs the commands for all lifecycle phases till package

validate >> compile >> test (optional) >> package

And as for mvn install, it runs the commands for all lifecycle phases till install, which includes package as well

validate >> compile >> test (optional) >> package >> verify >> install


So, effectively what it means is, install commands does everything that package command does and some more (install the package into the local repository, for use as a dependency in other projects locally)

Source: Maven lifecycle reference

How to specify a editor to open crontab file? "export EDITOR=vi" does not work

To quote the man:

The -e option is used to edit the current crontab using the editor specified by the VISUAL or EDITOR environment variables

Most often if you run crontab -e from X, you have VISUAL set; that's what is used. Try this:

VISUAL=vi crontab -e

It just worked for me :)

Adding Http Headers to HttpClient

Create a HttpRequestMessage, set the Method to GET, set your headers and then use SendAsync instead of GetAsync.

var client = new HttpClient();
var request = new HttpRequestMessage() {
    RequestUri = new Uri("http://www.someURI.com"),
    Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
var task = client.SendAsync(request)
    .ContinueWith((taskwithmsg) =>
    {
        var response = taskwithmsg.Result;

        var jsonTask = response.Content.ReadAsAsync<JsonObject>();
        jsonTask.Wait();
        var jsonObject = jsonTask.Result;
    });
task.Wait();

Complex nesting of partials and templates

I too was struggling with nested views in Angular.

Once I got a hold of ui-router I knew I was never going back to angular default routing functionality.

Here is an example application that uses multiple levels of views nesting

app.config(function ($stateProvider, $urlRouterProvider,$httpProvider) {
// navigate to view1 view by default
$urlRouterProvider.otherwise("/view1");

$stateProvider
    .state('view1', {
        url: '/view1',
        templateUrl: 'partials/view1.html',
        controller: 'view1.MainController'
    })
    .state('view1.nestedViews', {
        url: '/view1',
        views: {
            'childView1': { templateUrl: 'partials/view1.childView1.html' , controller: 'childView1Ctrl'},
            'childView2': { templateUrl: 'partials/view1.childView2.html', controller: 'childView2Ctrl' },
            'childView3': { templateUrl: 'partials/view1.childView3.html', controller: 'childView3Ctrl' }
        }
    })

    .state('view2', {
        url: '/view2',
    })

    .state('view3', {
        url: '/view3',
    })

    .state('view4', {
        url: '/view4',
    });
});

As it can be seen there are 4 main views (view1,view2,view3,view4) and view1 has 3 child views.

What is an application binary interface (ABI)?

The best way to differentiate between ABI and API is to know why and what is it used for:

For x86-64 there is generally one ABI (and for x86 32-bit there is another set):

http://www.x86-64.org/documentation/abi.pdf

https://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptual/LowLevelABI/140-x86-64_Function_Calling_Conventions/x86_64.html

http://people.freebsd.org/~obrien/amd64-elf-abi.pdf

Linux + FreeBSD + MacOSX follow it with some slight variations. And Windows x64 have its own ABI:

http://eli.thegreenplace.net/2011/09/06/stack-frame-layout-on-x86-64/

Knowing the ABI and assuming other compiler follows it as well, then the binaries theoretically know how to call each other (libraries API in particular) and pass parameters over the stack or by registers etc. Or what registers will be changed upon calling the functions etc. Essentially these knowledge will help software to integrate with one another. Knowing the order of the registers / stack layout I can easily piece together different software written in assemblies together without much problem.

But API are different:

It is a high level functions names, with argument defined, such that if different software pieces build using these API, MAY be able to call into one another. But an additional requirement of SAME ABI must be adhered to.

For example, Windows used to be POSIX API compliant:

https://en.wikipedia.org/wiki/Windows_Services_for_UNIX

https://en.wikipedia.org/wiki/POSIX

And Linux is POSIX compliant as well. But the binaries cannot be just moved over and run immediately. But because they used the same NAMES in the POSIX compliant API, you can take the same software in C, recompile it in the different OS, and immediately get it running.

API are meant to ease integration of software - pre-compilation stage. So after compilation the software can look totally different - if the ABI are different.

ABI are meant to define exact integration of software at the binary / assembly level.

Remove last item from array

var stack = [1,2,3,4,5,6];

stack.reverse().shift();

stack.push(0);

Output will be: Array[0,1,2,3,4,5]. This will allow you to keep the same amount of array elements as you push a new value in.

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

I know the question is aimed at the direct escaping of the apostrophe character but I assume that usually this is going to be triggered by some sort of program providing the input.

What I have done universally in the scripts and programs I have worked with is to substitute it with a ` character when processing the formatting of the text being input.

Now I know that in some cases, the backtick character may in fact be part of what you might be trying to save (such as on a forum like this) but if you're simply saving text input from users it's a possible solution.

Going into the SQL database

$newval=~s/\'/`/g;

Then, when coming back out for display, filtered again like this:

$showval=~s/`/\'/g;

This example was when PERL/CGI is being used but it can apply to PHP and other bases as well. I have found it works well because I think it helps prevent possible injection attempts, because all ' are removed prior to attempting an insertion of a record.

How to scanf only integer?

  1. You take scanf().
  2. You throw it in the bin.
  3. You use fgets() to get an entire line.
  4. You use strtol() to parse the line as an integer, checking if it consumed the entire line.
char *end;
char buf[LINE_MAX];

do {
     if (!fgets(buf, sizeof buf, stdin))
        break;

     // remove \n
     buf[strlen(buf) - 1] = 0;

     int n = strtol(buf, &end, 10);
} while (end != buf + strlen(buf));

how to define variable in jquery

in jquery we have to use selector($) to declare variables

var test=$("<%=ddl.ClientId%>");

here we can get the id of drop down to j query variable

org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android

I had the similar issue, then I found out that wifi was not connected in my smartphone. After I turned on the wifi and connected to the similar network (with my laptop), there was another issue - laptop's firewall was blocking incoming connections. Once I fixed the firewall, I was able to communicate from my android app with the web service running on the laptop.

What is Teredo Tunneling Pseudo-Interface?

Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.

If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)

Plotting time in Python with Matplotlib

I had trouble with this using matplotlib version: 2.0.2. Running the example from above I got a centered stacked set of bubbles.

graph with centered stack of bubbles

I "fixed" the problem by adding another line:

plt.plot([],[])

The entire code snippet becomes:

import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates


# make up some data
x = [datetime.datetime.now() + datetime.timedelta(minutes=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.plot([],[])
plt.scatter(x,y)

# beautify the x-labels
plt.gcf().autofmt_xdate()
myFmt = mdates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(myFmt)

plt.show()
plt.close()

This produces an image with the bubbles distributed as desired.

graph with bubbles distributed over time

How to print a groupby object

you cannot see the groupBy data directly by print statement but you can see by iterating over the group using for loop try this code to see the group by data

group = df.groupby('A') #group variable contains groupby data
for A,A_df in group: # A is your column and A_df is group of one kind at a time
  print(A)
  print(A_df)

you will get an output after trying this as a groupby result

I hope it helps