Programs & Examples On #Resource dll

Lightweight workflow engine for Java

The question is what you really want to achieve when you asking for a workflow engine.

The general goal which you would like to achieve by using a workflow engine, is to become more flexible in changing your business logic during runtime. The modelling part is surely one of the most important here. BPMN 2.0 is a de-facto standard in this area and all of the discussed engines support this standard.

The second goal is to control the business process in the way of describing the 'what should happen when...' questions. And this part has a lot to do with the business requirements you are confronted within your project.

Some of the workflow engines (Activity, JBPM) can help you to answer this requirement by 'coding' your processes. This means that you model the 'what should happen when..' paradigm in a way, where you decide which part of your code (e.g a task or an event) should be executed by the workflow engine in various situations. A lot of discussion is going about this concept. And developers naturally ask whether this may not even be implemented by themselves. (It is in fact not so easy as it seems at the first glance)

Some other workflow engines (Imixs-Workflow, Bonita) can help you to answer the 'what should happen when...' requirement in a more user-centric way. This is the area of Human-centric business process management, which supports human skills and activities by a task orientated workflow-engine. The focus is more on the distribution of tasks and processes inside an organisation. The workflow engine helps you to distribute a task to a certain user or user group and to secure, log and monitor a long running business process. Maybe these are the things you do not really want to implement by yourself.

So my advice is, not to mix things that need to be considered separately, because workflow covers a very wide area.

How can I transition height: 0; to height: auto; using CSS?

Check out my post on a somewhat related question.

Basically, start at height: 0px;, and let it transition to an exact height computed by JavaScript.

function setInfoHeight() {
  $(window).on('load resize', function() {
    $('.info').each(function () {
      var current = $(this);
      var closed = $(this).height() == 0;
      current.show().height('auto').attr('h', current.height() );
      current.height(closed ? '0' : current.height());
    });
  });

Whenever the page loads/resized, the element with class info will get its h attribute updated. Then a button triggers the style="height: __" to set it to that previously set h value.

function moreInformation() {
  $('.icon-container').click(function() {
    var info = $(this).closest('.dish-header').next('.info'); // Just the one info
    var icon = $(this).children('.info-btn'); // Select the logo

    // Stop any ongoing animation loops. Without this, you could click button 10
    // times real fast, and watch an animation of the info showing and closing
    // for a few seconds after
    icon.stop();
    info.stop();

    // Flip icon and hide/show info
    icon.toggleClass('flip');

    // Metnod 1, animation handled by JS
    // info.slideToggle('slow');

    // Method 2, animation handled by CSS, use with setInfoheight function
    info.toggleClass('active').height(icon.is('.flip') ? info.attr('h') : '0');

  });
};

Here's the styling for the info class.

.info {
  padding: 0 1em;
  line-height: 1.5em;
  display: inline-block;
  overflow: hidden;
  height: 0px;
  transition: height 0.6s, padding 0.6s;
  &.active {
    border-bottom: $thin-line;
    padding: 1em;
  }
}

Styling might not be supported cross-browser. Here is the live example for this code:

CodePen

Angular redirect to login page

Refer this code, auth.ts file

import { CanActivate } from '@angular/router';
import { Injectable } from '@angular/core';
import {  } from 'angular-2-local-storage';
import { Router } from '@angular/router';

@Injectable()
export class AuthGuard implements CanActivate {
constructor(public localStorageService:LocalStorageService, private router: Router){}
canActivate() {
// Imaginary method that is supposed to validate an auth token
// and return a boolean
var logInStatus         =   this.localStorageService.get('logInStatus');
if(logInStatus == 1){
    console.log('****** log in status 1*****')
    return true;
}else{
    console.log('****** log in status not 1 *****')
    this.router.navigate(['/']);
    return false;
}


}

}
// *****And the app.routes.ts file is as follow ******//
      import {  Routes  } from '@angular/router';
      import {  HomePageComponent   } from './home-page/home- page.component';
      import {  WatchComponent  } from './watch/watch.component';
      import {  TeachersPageComponent   } from './teachers-page/teachers-page.component';
      import {  UserDashboardComponent  } from './user-dashboard/user- dashboard.component';
      import {  FormOneComponent    } from './form-one/form-one.component';
      import {  FormTwoComponent    } from './form-two/form-two.component';
      import {  AuthGuard   } from './authguard';
      import {  LoginDetailsComponent } from './login-details/login-details.component';
      import {  TransactionResolver } from './trans.resolver'
      export const routes:Routes    =   [
    { path:'',              component:HomePageComponent                                                 },
    { path:'watch',         component:WatchComponent                                                },
    { path:'teachers',      component:TeachersPageComponent                                         },
    { path:'dashboard',     component:UserDashboardComponent,       canActivate: [AuthGuard],   resolve: { dashboardData:TransactionResolver } },
    { path:'formone',       component:FormOneComponent,                 canActivate: [AuthGuard],   resolve: { dashboardData:TransactionResolver } },
    { path:'formtwo',       component:FormTwoComponent,                 canActivate: [AuthGuard],   resolve: { dashboardData:TransactionResolver } },
    { path:'login-details', component:LoginDetailsComponent,            canActivate: [AuthGuard]    },

]; 

jQuery multiple conditions within if statement

i == 'InvKey' && i == 'PostDate' will never be true, since i can never equal two different things at once.

You're probably trying to write

if (i !== 'InvKey' && i !== 'PostDate')) 

How do I use Safe Area Layout programmatically?

Here is sample code (Ref from: Safe Area Layout Guide):
If you create your constraints in code use the safeAreaLayoutGuide property of UIView to get the relevant layout anchors. Let’s recreate the above Interface Builder example in code to see how it looks:

Assuming we have the green view as a property in our view controller:

private let greenView = UIView()

We might have a function to set up the views and constraints called from viewDidLoad:

private func setupView() {
  greenView.translatesAutoresizingMaskIntoConstraints = false
  greenView.backgroundColor = .green
  view.addSubview(greenView)
}

Create the leading and trailing margin constraints as always using the layoutMarginsGuide of the root view:

 let margins = view.layoutMarginsGuide
 NSLayoutConstraint.activate([
    greenView.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
    greenView.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
 ])

Now, unless you are targeting iOS 11 and later, you will need to wrap the safe area layout guide constraints with #available and fall back to top and bottom layout guides for earlier iOS versions:

if #available(iOS 11, *) {
  let guide = view.safeAreaLayoutGuide
  NSLayoutConstraint.activate([
   greenView.topAnchor.constraintEqualToSystemSpacingBelow(guide.topAnchor, multiplier: 1.0),
   guide.bottomAnchor.constraintEqualToSystemSpacingBelow(greenView.bottomAnchor, multiplier: 1.0)
   ])
} else {
   let standardSpacing: CGFloat = 8.0
   NSLayoutConstraint.activate([
   greenView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: standardSpacing),
   bottomLayoutGuide.topAnchor.constraint(equalTo: greenView.bottomAnchor, constant: standardSpacing)
   ])
}

Result:

enter image description here

enter image description here


Here is Apple Developer Official Documentation for Safe Area Layout Guide


Safe Area is required to handle user interface design for iPhone-X. Here is basic guideline for How to design user interface for iPhone-X using Safe Area Layout

Create a .csv file with values from a Python list

For another approach, you can use DataFrame in pandas: And it can easily dump the data to csv just like the code below:

import pandas
df = pandas.DataFrame(data={"col1": list_1, "col2": list_2})
df.to_csv("./file.csv", sep=',',index=False)

How to split a string in two and store it in a field

I would suggest the following:

String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2

Gmail: OAuth

  • Goto the link
  • Login with your gmail username password
  • Click on the google menu at the top left
  • Click API Manager
  • Click on Credentials
  • Click Create Credentials and select OAuth Client
  • Select Web Application as Application type and Enter the Name-> Enter Authorised Redirect URL (Eg: http://localhost:53922/signin-google) ->Click on Create button. This will create the credentials. Pls make a note of Client ID and Secret ID. Finally click OK to close the credentials pop up.
  • Next important step is to enable the Google API. Click on Overview in the left pane.
  • Click on the Google API under Social APIs section.
  • Click Enable.

That’s all from the Google part.

Come back to your application, open App_start/Startup.Auth.cs and uncomment the following snippet

        app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = "",
            ClientSecret = ""
        });

Update the ClientId and ClientSecret with the values from Google API credentials which you have created already.

  • Run your application
  • Click Login
  • You will see the Google button under ‘Use Another Section to log in’ section
  • Click on the Google button
  • Application will prompt you to enter the username and password
  • Enter the gmail username and password and click Sign In
  • This will perform the OAuth and come back to your application and prompting you to register with the Gmail id.
  • Click register to register the Gmail id into your application database.
  • You will see the Identity details appear in the top as normal registration
  • Try logout and login again thru Gmail. This will automatically logs you into the app.

Rounding to two decimal places in Python 2.7?

print "financial return of outcome 1 = $%.2f" % (out1)

What is the Java equivalent for LINQ?

As on 2014, I can finally say that LINQ is finally there in java 8.So no need to find an alternative of LINQ anymore.

Android Room - simple select query - Cannot access database on the main thread

An elegant RxJava/Kotlin solution is to use Completable.fromCallable, which will give you an Observable which does not return a value, but can observed and subscribed on a different thread.

public Completable insert(Event event) {
    return Completable.fromCallable(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            return database.eventDao().insert(event)
        }
    }
}

Or in Kotlin:

fun insert(event: Event) : Completable = Completable.fromCallable {
    database.eventDao().insert(event)
}

You can the observe and subscribe as you would usually:

dataManager.insert(event)
    .subscribeOn(scheduler)
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(...)

Deep copy vs Shallow Copy

Shallow copy:

Some members of the copy may reference the same objects as the original:

class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(copy.pi)
    { }
};

Here, the pi member of the original and copied X object will both point to the same int.


Deep copy:

All members of the original are cloned (recursively, if necessary). There are no shared objects:

class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(new int(*copy.pi))  // <-- note this line in particular!
    { }
};

Here, the pi member of the original and copied X object will point to different int objects, but both of these have the same value.


The default copy constructor (which is automatically provided if you don't provide one yourself) creates only shallow copies.

Correction: Several comments below have correctly pointed out that it is wrong to say that the default copy constructor always performs a shallow copy (or a deep copy, for that matter). Whether a type's copy constructor creates a shallow copy, or deep copy, or something in-between the two, depends on the combination of each member's copy behaviour; a member's type's copy constructor can be made to do whatever it wants, after all.

Here's what section 12.8, paragraph 8 of the 1998 C++ standard says about the above code examples:

The implicitly defined copy constructor for class X performs a memberwise copy of its subobjects. [...] Each subobject is copied in the manner appropriate to its type: [...] [I]f the subobject is of scalar type, the builtin assignment operator is used.

How to get current PHP page name

$_SERVER["PHP_SELF"]; will give you the current filename and its path, but basename(__FILE__) should give you the filename that it is called from.

So

if(basename(__FILE__) == 'file_name.php') {
  //Hide
} else {
  //show
}

should do it.

Conversion failed when converting the nvarchar value ... to data type int

I got this error when I used a where clause which looked at a nvarchar field but didn't use single quotes.

My invalid SQL query looked like this:

SELECT * FROM RandomTable WHERE Id IN (SELECT Id FROM RandomTable WHERE [Number] = 13028533)

This didn't work since the Number column had the data type nvarchar. It wasn't an int as I first thought.

I changed it to:

SELECT * FROM RandomTable WHERE Id IN (SELECT Id FROM RandomTable WHERE [Number] = '13028533')

And it worked.

UnicodeEncodeError: 'charmap' codec can't encode characters

Even I faced the same issue with the encoding that occurs when you try to print it, read/write it or open it. As others mentioned above adding .encoding="utf-8" will help if you are trying to print it.

soup.encode("utf-8")

If you are trying to open scraped data and maybe write it into a file, then open the file with (......,encoding="utf-8")

with open(filename_csv , 'w', newline='',encoding="utf-8") as csv_file:

Select a date from date picker using Selenium webdriver

Here's a tidy solution where you provide the target date as a Calendar object.

// Used to translate the Month value of a JQuery calendar to the month value expected by a Calendar.
private static final Map<String,Integer> MONTH_TO_CALENDAR_INDEX = new HashMap<String,Integer>();
static {
    MONTH_TO_CALENDAR_INDEX.put("January",  0);
    MONTH_TO_CALENDAR_INDEX.put("February",1);
    MONTH_TO_CALENDAR_INDEX.put("March",2);
    MONTH_TO_CALENDAR_INDEX.put("April",3);
    MONTH_TO_CALENDAR_INDEX.put("May",4);
    MONTH_TO_CALENDAR_INDEX.put("June",5);
    MONTH_TO_CALENDAR_INDEX.put("July",6);
    MONTH_TO_CALENDAR_INDEX.put("August",7);
    MONTH_TO_CALENDAR_INDEX.put("September",8);
    MONTH_TO_CALENDAR_INDEX.put("October",9);
    MONTH_TO_CALENDAR_INDEX.put("November",10);
    MONTH_TO_CALENDAR_INDEX.put("December",11);
}

        // ====================================================================================================
        // setCalendarPicker
        // ====================================================================================================

        /**
         * Sets the value of specified web element while assuming the element is a JQuery calendar.
         * @param byOpen The By phrase that locates the control that opens the JQuery calendar when clicked.
         * @param byPicker The By phrase that locates the JQuery calendar.
         * @param targetDate The target date that you want set.
         * @throws AssertionError if the method is unable to set the date.
         */

        public void setCalendarPicker(By byOpen, By byPicker, Calendar targetDate) {

            // Open the JQuery calendar.
            WebElement opener = driver.findElement(byOpen);
            opener.click();

            // Locate the JQuery calendar.
            WebElement picker = driver.findElement(byPicker);

            // Calculate the target and current year-and-month as an integer where value = year*12+month.
            // The difference between the two is the number of months we have to move ahead or backward.
            int targetYearMonth = targetDate.get(Calendar.YEAR) * 12 + targetDate.get(Calendar.MONTH);
            int currentYearMonth = Integer.valueOf(picker.findElement(By.className("ui-datepicker-year")).getText()) * 12
                    + Integer.valueOf(MONTH_TO_CALENDAR_INDEX.get(picker.findElement(By.className("ui-datepicker-month")).getText()));
            // Calculate the number of months we need to move the JQuery calendar.
            int delta = targetYearMonth - currentYearMonth;
            // As a sanity check, let's not allow more than 10 years so that we don't inadvertently spin in a loop for zillions of months.
            if (Math.abs(delta) > 120) throw new AssertionError("Target date is more than 10 years away");

            // Push the JQuery calendar forward or backward as appropriate.
            if (delta > 0) {
                while (delta-- > 0) picker.findElement(By.className("ui-icon-circle-triangle-e")).click();
            } else if (delta < 0 ){
                while (delta++ < 0) picker.findElement(By.className("ui-icon-circle-triangle-w")).click();
            }

            // Select the day within the month.
            String dayOfMonth = String.valueOf(targetDate.get(Calendar.DAY_OF_MONTH));
            WebElement tableOfDays = picker.findElement(By.cssSelector("tbody:nth-child(2)"));
            for (WebElement we : tableOfDays.findElements(By.tagName("td"))) {
                if (dayOfMonth.equals(we.getText())) {
                    we.click();

                    // Send a tab to completely leave this control.  If the next control the user will access is another CalendarPicker,
                    // the picker might not get selected properly if we stay on the current control.
                    opener.sendKeys("\t");

                    return;
                }
            }

            throw new AssertionError(String.format("Unable to select specified day"));
        }

difference between new String[]{} and new String[] in java

String array[]=new String[]; and String array[]=new String[]{};

No difference,these are just different ways of declaring array

String array=new String[10]{}; got error why ?

This is because you can not declare the size of the array in this format.

right way is

String array[]=new String[]{"a","b"};

Add more than one parameter in Twig path

Consider making your route:

_files_manage:
    pattern: /files/management/{project}/{user}
    defaults: { _controller: AcmeTestBundle:File:manage }

since they are required fields. It will make your url's prettier, and be a bit easier to manage.

Your Controller would then look like

 public function projectAction($project, $user)

How to run single test method with phpunit?

The reason your tests are all being run is that you have the --filter flag after the file name. PHPUnit is not reading the options at all and so is running all the test cases.

From the help screen:

 Usage: phpunit [options] UnitTest [UnitTest.php]
        phpunit [options] <directory>

So move the --filter argument before the test file that you want as mentioned in @Alex and @Ferid Mövsümov answers. And you should only have the test that you want run.

Reading specific columns from a text file in python

You have a space delimited file, so use the module designed for reading delimited values files, csv.

import csv

with open('path/to/file.txt') as inf:
    reader = csv.reader(inf, delimiter=" ")
    second_col = list(zip(*reader))[1]
    # In Python2, you can omit the `list(...)` cast

The zip(*iterable) pattern is useful for converting rows to columns or vice versa. If you're reading a file row-wise...

>>> testdata = [[1, 2, 3],
                [4, 5, 6],
                [7, 8, 9]]

>>> for line in testdata:
...     print(line)

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

...but need columns, you can pass each row to the zip function

>>> testdata_columns = zip(*testdata)
# this is equivalent to zip([1,2,3], [4,5,6], [7,8,9])

>>> for line in testdata_columns:
...     print(line)

[1, 4, 7]
[2, 5, 8]
[3, 6, 9]

Define variable to use with IN operator (T-SQL)

DECLARE @StatusList varchar(MAX);
SET @StatusList='1,2,3,4';
DECLARE @Status SYS_INTEGERS;
INSERT INTO  @Status 
SELECT Value 
FROM dbo.SYS_SPLITTOINTEGERS_FN(@StatusList, ',');
SELECT Value From @Status;

Laravel 5 Carbon format datetime

just use

Carbon::createFromFormat('Y-m-d H:i:s', $item['created_at'])->format('M d Y');

React JS get current date

Your problem is that you are naming your component class Date. When you call new Date() within your class, it won't create an instance of the Date you expect it to create (which is likely this Date)- it will try to create an instance of your component class. Then the constructor will try to create another instance, and another instance, and another instance... Until you run out of stack space and get the error you're seeing.

If you want to use Date within your class, try naming your class something different such as Calendar or DateComponent.

The reason for this is how JavaScript deals with name scope: Whenever you create a new named entity, if there is already an entity with that name in scope, that name will stop referring to the previous entity and start referring to your new entity. So if you use the name Date within a class named Date, the name Date will refer to that class and not to any object named Date which existed before the class definition started.

jQuery table sort

I love this accepted answer, however, rarely do you get requirements to sort html and not have to add icons indicating the sorting direction. I took the accept answer's usage example and fixed that quickly by simply adding bootstrap to my project, and adding the following code:

<div></div>

inside each <th> so that you have a place to set the icon.

setIcon(this, inverse);

from the accepted answer's Usage, below the line:

th.click(function () {

and by adding the setIcon method:

function setIcon(element, inverse) {

        var iconSpan = $(element).find('div');

        if (inverse == false) {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('icon-white icon-arrow-up');
        } else {
            $(iconSpan).removeClass();
            $(iconSpan).addClass('icon-white icon-arrow-down');
        }
        $(element).siblings().find('div').removeClass();
    }

Here is a demo. --You need to either run the demo in Firefox or IE, or disable Chrome's MIME-type checking for the demo to work. It depends on the sortElements Plugin, linked by the accepted answer, as an external resource. Just a heads up!

SQL server stored procedure return a table

Here's an example of a SP that both returns a table and a return value. I don't know if you need the return the "Return Value" and I have no idea about MATLAB and what it requires.

CREATE PROCEDURE test
AS 
BEGIN

    SELECT * FROM sys.databases

    RETURN 27
END

--Use this to test
DECLARE @returnval int

EXEC @returnval = test 

SELECT @returnval

How to move up a directory with Terminal in OS X

Let's make it even more simple. Type the below after the $ sign to go up one directory:

../

How to convert Base64 String to javascript file object like as from file input form?

This is the latest async/await pattern solution.

export async function dataUrlToFile(dataUrl: string, fileName: string): Promise<File> {

    const res: Response = await fetch(dataUrl);
    const blob: Blob = await res.blob();
    return new File([blob], fileName, { type: 'image/png' });
}

Memcached vs. Redis?

It would not be wrong, if we say that redis is combination of (cache + data structure) while memcached is just a cache.

How do I update zsh to the latest version?

As far as I'm aware, you've got three options to install zsh on Mac OS X:

  • Pre-built binary. The only one I know of is the one that ships with OS X; this is probably what you're running now.
  • Use a package system (Ports, Homebrew).
  • Install from source. Last time I did this it wasn't too difficult (./configure, make, make install).

How to run python script on terminal (ubuntu)?

Set the PATH as below:


In the csh shell - type setenv PATH "$PATH:/usr/local/bin/python" and press Enter.

In the bash shell (Linux) - type export PATH="$PATH:/usr/local/bin/python" and press Enter.

In the sh or ksh shell - type PATH="$PATH:/usr/local/bin/python" and press Enter.

Note - /usr/local/bin/python is the path of the Python directory


now run as below:

-bash-4.2$ python test.py

Hello, Python!

How to increase IDE memory limit in IntelliJ IDEA on Mac?

Current version: Help | Change Memory Settings:

Change memory settings

Since IntelliJ IDEA 15.0.4 you can also use: Help | Edit Custom VM Options...:

This will automatically create a copy of the .vmoptions file in the config folder and open a dialog to edit it.


Older versions:

IntelliJ IDEA 12 is a signed application, therefore changing options in Info.plist is no longer recommended, as the signature will not match and you will get issues depending on your system security settings (app will either not run, or firewall will complain on every start, or the app will not be able to use the system keystore to save passwords).

As a result of addressing IDEA-94050 a new way to supply JVM options was introduced in IDEA 12:

Now it can take VM options from ~/Library/Preferences/<appFolder>/idea.vmoptions and system properties from ~/Library/Preferences/<appFolder>/idea.properties.

For example, to use -Xmx2048m option you should copy the original .vmoptions file from /Applications/IntelliJ IDEA.app/bin/idea.vmoptions to ~/Library/Preferences/IntelliJIdea12/idea.vmoptions, then modify the -Xmx setting.

The final file should look like:

-Xms128m
-Xmx2048m
-XX:MaxPermSize=350m
-XX:ReservedCodeCacheSize=64m
-XX:+UseCodeCacheFlushing
-XX:+UseCompressedOops

Copying the original file is important, as options are not added, they are replaced.

This way your custom options will be preserved between updates and application files will remain unmodified making signature checker happy.


Community Edition: ~/Library/Preferences/IdeaIC12/idea.vmoptions file is used instead.

How to show android checkbox at right side?

I can't think of a way with the styling, but you could just set the text of the checkbox to nothing, and put a TextView to the left of the checkbox with your desired text.

How to list the properties of a JavaScript object?

As slashnick pointed out, you can use the "for in" construct to iterate over an object for its attribute names. However you'll be iterating over all attribute names in the object's prototype chain. If you want to iterate only over the object's own attributes, you can make use of the Object#hasOwnProperty() method. Thus having the following.

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        /* useful code here */
    }
}

How to set initial size of std::vector?

std::vector<CustomClass *> whatever(20000);

or:

std::vector<CustomClass *> whatever;
whatever.reserve(20000);

The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.

At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.

read file from assets

Using Kotlin, you can do the following to read a file from assets in Android:

try {
    val inputStream:InputStream = assets.open("helloworld.txt")
    val inputString = inputStream.bufferedReader().use{it.readText()}
    Log.d(TAG,inputString)
} catch (e:Exception){
    Log.d(TAG, e.toString())
}

What does if __name__ == "__main__": do?

Create a file, a.py:

print(__name__) # It will print out __main__

__name__ is always equal to __main__ whenever that file is run directly showing that this is the main file.

Create another file, b.py, in the same directory:

import a  # Prints a

Run it. It will print a, i.e., the name of the file which is imported.

So, to show two different behavior of the same file, this is a commonly used trick:

# Code to be run when imported into another python file

if __name__ == '__main__':
    # Code to be run only when run directly

Find Process Name by its Process ID

The basic one, ask tasklist to filter its output and only show the indicated process id information

tasklist /fi "pid eq 4444" 

To only get the process name, the line must be splitted

for /f "delims=," %%a in ('
    tasklist /fi "pid eq 4444" /nh /fo:csv
') do echo %%~a

In this case, the list of processes is retrieved without headers (/nh) in csv format (/fo:csv). The commas are used as token delimiters and the first token in the line is the image name

note: In some windows versions (one of them, my case, is the spanish windows xp version), the pid filter in the tasklist does not work. In this case, the filter over the list of processes must be done out of the command

for /f "delims=," %%a in ('
    tasklist /fo:csv /nh ^| findstr /b /r /c:"[^,]*,\"4444\","
') do echo %%~a

This will generate the task list and filter it searching for the process id in the second column of the csv output.

edited: alternatively, you can suppose what has been made by the team that translated the OS to spanish. I don't know what can happen in other locales.

tasklist /fi "idp eq 4444" 

What is the bit size of long on 64-bit Windows?

The easiest way to get to know it for your compiler/platform:

#include <iostream>

int main() {
  std::cout << sizeof(long)*8 << std::endl;
}

Themultiplication by 8 is to get bits from bytes.

When you need a particular size, it is often easiest to use one of the predefined types of a library. If that is undesirable, you can do what often happens with autoconf software and have the configuration system determine the right type for the needed size.

How to make sure that string is valid JSON using JSON.NET

Here is a TryParse extension method based on Habib's answer:

public static bool TryParse(this string strInput, out JToken output)
{
    if (String.IsNullOrWhiteSpace(strInput))
    {
        output = null;
        return false;
    }
    strInput = strInput.Trim();
    if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
        (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
    {
        try
        {
            output = JToken.Parse(strInput);
            return true;
        }
        catch (JsonReaderException jex)
        {
            //Exception in parsing json
            //optional: LogError(jex);
            output = null;
            return false;
        }
        catch (Exception ex) //some other exception
        {
            //optional: LogError(ex);
            output = null;
            return false;
        }
    }
    else
    {
        output = null;
        return false;
    }
}

Usage:

JToken jToken;
if (strJson.TryParse(out jToken))
{
    // work with jToken
}
else
{
    // not valid json
}

How to create many labels and textboxes dynamically depending on the value of an integer variable?

Here is a simple example that should let you keep going add somethink that would act as a placeholder to your winform can be TableLayoutPanel

and then just add controls to it

   for ( int i = 0; i < COUNT; i++ ) {


    Label lblTitle = new Label();
    lblTitle.Text = i+"Your Text";
    youlayOut.Controls.Add( lblTitle, 0, i );

    TextBox txtValue = new TextBox();
    youlayOut.Controls.Add( txtValue, 2, i );
}

Change UITextField and UITextView Cursor / Caret Color

It is only possible by accessing a private property and therefore may cause an Apple AppStore app rejection.

take a look at this Stackoverflow question

Warning: X may be used uninitialized in this function

one has not been assigned so points to an unpredictable location. You should either place it on the stack:

Vector one;
one.a = 12;
one.b = 13;
one.c = -11

or dynamically allocate memory for it:

Vector* one = malloc(sizeof(*one))
one->a = 12;
one->b = 13;
one->c = -11
free(one);

Note the use of free in this case. In general, you'll need exactly one call to free for each call made to malloc.

Set Response Status Code

As written before, but for beginner like me don't forget to include the return.

$this->response->statusCode(200);
return $this->response;

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

How to build minified and uncompressed bundle with webpack?

Maybe i am late here, but i have the same issue, so i wrote a unminified-webpack-plugin for this purpose.

Installation

npm install --save-dev unminified-webpack-plugin

Usage

var path = require('path');
var webpack = require('webpack');
var UnminifiedWebpackPlugin = require('unminified-webpack-plugin');

module.exports = {
    entry: {
        index: './src/index.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'library.min.js'
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new UnminifiedWebpackPlugin()
    ]
};

By doing as above, you will get two files library.min.js and library.js. No need execute webpack twice, it just works!^^

How to reset (clear) form through JavaScript?

You could use the following:

$('[element]').trigger('reset')

Is it possible to specify proxy credentials in your web.config?

Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though.

Create an assembly called SomeAssembly.dll with this class :

namespace SomeNameSpace
{
    public class MyProxy : IWebProxy
    {
        public ICredentials Credentials
        {
            get { return new NetworkCredential("user", "password"); }
            //or get { return new NetworkCredential("user", "password","domain"); }
            set { }
        }

        public Uri GetProxy(Uri destination)
        {
            return new Uri("http://my.proxy:8080");
        }

        public bool IsBypassed(Uri host)
        {
            return false;
        }
    }
}

Add this to your config file :

<defaultProxy enabled="true" useDefaultCredentials="false">
  <module type = "SomeNameSpace.MyProxy, SomeAssembly" />
</defaultProxy>

This "injects" a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application.

This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own ConfigurationSection, or add some information in the AppSettings, which is far more easier.

How to select specific form element in jQuery?

although it is invalid html but you can use selector context to limit your selector in your case it would be like :

$("input[name='name']" , "#form2").val("Hello World! ");

http://api.jquery.com/jquery/#selector-context

How to create a pivot query in sql server without aggregate function

SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
    MAX([Value])
    FOR [Period] IN ([2000], [2001], [2002])
) as pvt

Another way,

SELECT ACCOUNT,
      MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
      MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
      MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account

Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL

Be sure to configure the 'default' key in app/config/database.php

For postgres, this would be 'default' => 'postgres',

If you are receiving a [PDOException] could not find driver error, check to see if you have the correct PHP extensions installed. You need pdo_pgsql.so and pgsql.so installed and enabled. Instructions on how to do this vary between operating systems.

For Windows, the pgsql extensions should come pre-downloaded with the official PHP distribution. Just edit your php.ini and uncomment the lines extension=pdo_pgsql.so and extension=pgsql.so

Also, in php.ini, make sure extension_dir is set to the proper directory. It should be a folder called extensions or ext or similar inside your PHP install directory.

Finally, copy libpq.dll from C:\wamp\bin\php\php5.*\ into C:\wamp\bin\apache*\bin and restart all services through the WampServer interface.

If you still get the exception, you may need to add the postgres \bin directory to your PATH:

  1. System Properties -> Advanced tab -> Environment Variables
  2. In 'System variables' group on lower half of window, scroll through and find the PATH entry.
  3. Select it and click Edit
  4. At the end of the existing entry, put the full path to your postgres bin directory. The bin folder should be located in the root of your postgres installation directory.
  5. Restart any open command prompts, or to be certain, restart your computer.

This should hopefully resolve any problems. For more information see:

Odd behavior when Java converts int to byte?

often in books you will find the explanation of casting from int to byte as being performed by modulus division. this is not strictly correct as shown below what actually happens is the 24 most significant bits from the binary value of the int number are discarded leaving confusion if the remaining leftmost bit is set which designates the number as negative

public class castingsample{

public static void main(String args[]){

    int i;
    byte y;
    i = 1024;
    for(i = 1024; i > 0; i-- ){

      y = (byte)i;
      System.out.print(i + " mod 128 = " + i%128 + " also ");
      System.out.println(i + " cast to byte " + " = " + y);

    }

}

}

How do I detect a page refresh using jquery?

$('body').bind('beforeunload',function(){
   //do something
});

But this wont save any info for later, unless you were planning on saving that in a cookie somewhere (or local storage) and the unload event does not always fire in all browsers.


Example: http://jsfiddle.net/maniator/qpK7Y/

Code:

$(window).bind('beforeunload',function(){

     //save info somewhere

    return 'are you sure you want to leave?';

});

How to check if running in Cygwin, Mac or Linux?

To build upon Albert's answer, I like to use $COMSPEC for detecting Windows:

#!/bin/bash

if [ "$(uname)" == "Darwin" ]
then
 echo Do something under Mac OS X platform
elif [ "$(expr substr $(uname -s) 1 5)" == "Linux" ]
then
  echo Do something under Linux platform
elif [ -n "$COMSPEC" -a -x "$COMSPEC" ]
then 
  echo $0: this script does not support Windows \:\(
fi

This avoids parsing variants of Windows names for $OS, and parsing variants of uname like MINGW, Cygwin, etc.

Background: %COMSPEC% is a Windows environmental variable specifying the full path to the command processor (aka the Windows shell). The value of this variable is typically %SystemRoot%\system32\cmd.exe, which typically evaluates to C:\Windows\system32\cmd.exe .

Bootstrap Columns Not Working

While this does not address the OP's question, I had trouble with my bootstrap rows / columns while trying to use them in conjunction with Kendo ListView (even with the bootstrap-kendo css).

Adding the following css fixed the problem for me:

#myListView.k-widget, #catalog-items.k-widget * {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

Can I open a dropdownlist using jQuery

You can easily simulate a click on an element, but a click on a <select> won’t open up the dropdown.

Using multiple selects can be problematic. Perhaps you should consider radio buttons inside a container element which you can expand and contract as needed.

how do you insert null values into sql server

If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.

asp.net validation to make sure textbox has integer values

http://msdn.microsoft.com/en-us/library/ad548tzy%28VS.71%29.aspx

When using Server validator controls you have to be careful about fact that any one can disable javascript in their browser. So you should use Page.IsValid Property always at server side.

click() event is calling twice in jquery

I had the same problem, but you can try changing this code

$("#link_button")
.button()
.click(function () {
   $("#attachmentForm").slideToggle("fast");
});

to this:

$("#link_button").button();
$("#link_button").unbind("click").click(function () {
   $("#attachmentForm").slideToggle("fast");
});

For me, this code solved the problem. But take care not to accidentally include your script twice in your HTML page. I think that if you are doing these two things correctly, your code will work correctly. Thanks

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

I solved this error

A connection attempt failed with "ECONNREFUSED - Connection refused by server"

by changing my port to 22 that was successful

Hibernate Query By Example and Projections

Can I see your User class? This is just using restrictions below. I don't see why Restrictions would be really any different than Examples (I think null fields get ignored by default in examples though).

getCurrentSession().createCriteria(User.class)
.setProjection( Projections.distinct( Projections.projectionList()
.add( Projections.property("name"), "name")
.add( Projections.property("city"), "city")))
.add( Restrictions.eq("city", "TEST")))
.setResultTransformer(Transformers.aliasToBean(User.class))
.list();

I've never used the alaistToBean, but I just read about it. You could also just loop over the results..

List<Object> rows = criteria.list();
for(Object r: rows){
  Object[] row = (Object[]) r;
  Type t = ((<Type>) row[0]);
}

If you have to you can manually populate User yourself that way.

Its sort of hard to look into the issue without some more information to diagnose the issue.

How can I determine if a .NET assembly was built for x86 or x64?

Look at System.Reflection.AssemblyName.GetAssemblyName(string assemblyFile)

You can examine assembly metadata from the returned AssemblyName instance:

Using PowerShell:

[36] C:\> [reflection.assemblyname]::GetAssemblyName("${pwd}\Microsoft.GLEE.dll") | fl

Name                  : Microsoft.GLEE
Version               : 1.0.0.0
CultureInfo           :
CodeBase              : file:///C:/projects/powershell/BuildAnalyzer/...
EscapedCodeBase       : file:///C:/projects/powershell/BuildAnalyzer/...
ProcessorArchitecture : MSIL
Flags                 : PublicKey
HashAlgorithm         : SHA1
VersionCompatibility  : SameMachine
KeyPair               :
FullName              : Microsoft.GLEE, Version=1.0.0.0, Culture=neut... 

Here, ProcessorArchitecture identifies target platform.

  • Amd64: A 64-bit processor based on the x64 architecture.
  • Arm: An ARM processor.
  • IA64: A 64-bit Intel Itanium processor only.
  • MSIL: Neutral with respect to processor and bits-per-word.
  • X86: A 32-bit Intel processor, either native or in the Windows on Windows environment on a 64-bit platform (WOW64).
  • None: An unknown or unspecified combination of processor and bits-per-word.

I'm using PowerShell in this example to call the method.

Remove the string on the beginning of an URL

Another way:

Regex.Replace(urlString, "www.(.+)", "$1");

How to install OpenSSL for Python

SSL development libraries have to be installed

CentOS:

$ yum install openssl-devel libffi-devel

Ubuntu:

$ apt-get install libssl-dev libffi-dev

OS X (with Homebrew installed):

$ brew install openssl

What exactly is RESTful programming?

REST stands for Representational state transfer.

It relies on a stateless, client-server, cacheable communications protocol -- and in virtually all cases, the HTTP protocol is used.

REST is often used in mobile applications, social networking Web sites, mashup tools and automated business processes. The REST style emphasizes that interactions between clients and services is enhanced by having a limited number of operations (verbs). Flexibility is provided by assigning resources (nouns) their own unique universal resource indicators (URIs).

Introduction about Rest

How to add include and lib paths to configure/make cycle?

You want a config.site file. Try:

$ mkdir -p ~/local/share
$ cat << EOF > ~/local/share/config.site
CPPFLAGS=-I$HOME/local/include
LDFLAGS=-L$HOME/local/lib
...
EOF

Whenever you invoke an autoconf generated configure script with --prefix=$HOME/local, the config.site will be read and all the assignments will be made for you. CPPFLAGS and LDFLAGS should be all you need, but you can make any other desired assignments as well (hence the ... in the sample above). Note that -I flags belong in CPPFLAGS and not in CFLAGS, as -I is intended for the pre-processor and not the compiler.

Take a char input from the Scanner

Try this: char c=S.nextLine().charAt(0);

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

I had the same problem but from IIS in visual studio, I went to project properties -> Web -> and project url change http to https

Loop through files in a directory using PowerShell

If you need to loop inside a directory recursively for a particular kind of file, use the below command, which filters all the files of doc file type

$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc

If you need to do the filteration on multiple types, use the below command.

$fileNames = Get-ChildItem -Path $scriptPath -Recurse -Include *.doc,*.pdf

Now $fileNames variable act as an array from which you can loop and apply your business logic.

"SELECT ... IN (SELECT ...)" query in CodeIgniter

Note that these solutions use the Code Igniter Active Records Class

This method uses sub queries like you wish but you should sanitize $countryId yourself!

$this->db->select('username')
         ->from('user')
         ->where('`locationId` in', '(select `locationId` from `locations` where `countryId` = '.$countryId.')', false)
         ->get();

Or this method would do it using joins and will sanitize the data for you (recommended)!

$this->db->select('username')
         ->from('users')
         ->join('locations', 'users.locationid = locations.locationid', 'inner')
         ->where('countryid', $countryId)
         ->get();

How to check if a Unix .tar.gz file is a valid file without uncompressing?

What about just getting a listing of the tarball and throw away the output, rather than decompressing the file?

tar -tzf my_tar.tar.gz >/dev/null

Edited as per comment. Thanks zrajm!

Edit as per comment. Thanks Frozen Flame! This test in no way implies integrity of the data. Because it was designed as a tape archival utility most implementations of tar will allow multiple copies of the same file!

How can I align two divs horizontally?

Add a class to each of the divs:

_x000D_
_x000D_
.source, .destination {_x000D_
    float: left;_x000D_
    width: 48%;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
.source {_x000D_
    margin-right: 4%;_x000D_
}
_x000D_
<div class="source">_x000D_
    <span>source list</span>_x000D_
    <select size="10">_x000D_
        <option />_x000D_
        <option />_x000D_
        <option />_x000D_
    </select>_x000D_
</div>_x000D_
<div class="destination">_x000D_
    <span>destination list</span>_x000D_
    <select size="10">_x000D_
        <option />_x000D_
        <option />_x000D_
        <option />_x000D_
    </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

That's a generic percentages solution - using pixel-based widths is usually much more reliable. You'll probably want to change the various margin/padding sizes too.

You can also optionally wrap the HTML in a container div, and use this CSS:

.container {
  overflow: hidden;
}

This will ensure subsequent content does not wrap around the floated elements.

GridView Hide Column by code

GridView.Columns.Count will always be 0 when your GridView has its AutoGenerateColumns property set to true (default is true).

You can explicitly declare your columns and set the AutoGenerateColumns property to false, or you can use this in your codebehind:

GridView.Rows[0].Cells.Count

to get the column count once your GridView data has been bound, or this:

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    e.Row.Cells[index].Visible = false;
}

to set a column invisible using your GridView's RowDataBound event.

Setting environment variables for accessing in PHP when using Apache

If your server is Ubuntu and Apache version is 2.4

Server version: Apache/2.4.29 (Ubuntu)

Then you export variables in "/etc/apache2/envvars" location.

Just like this below line, you need to add an extra line in "/etc/apache2/envvars" export GOROOT=/usr/local/go

Get string character by index - Java

Like this:

String a ="hh1hhhhhhhh";
char s = a.charAt(3);

Running Windows batch file commands asynchronously

I could not get anything to work I ended up just using powershell to start bat scripts .. sometimes even start cmd /c does not work not sure why .. I even tried stuff like start cmd /c notepad & exit

start-Process "c:\BACKUP\PRIVATE\MobaXterm_Portable\MobaXterm_Portable.bat" -WindowStyle Hidden

How to center content in a bootstrap column?

Use:

<!-- unsupported by HTML5 -->
<div class="col-xs-1" align="center">

instead of

<div class="col-xs-1 center-block">

You can also use bootstrap 3 css:

<!-- recommended method -->
<div class="col-xs-1 text-center">

Bootstrap 4 now has flex classes that will center the content:

<div class="d-flex justify-content-center">
   <div>some content</div>
</div>

Note that by default it will be x-axis unless flex-direction is column

Recursive file search using PowerShell

Use the Get-ChildItem cmdlet with the -Recurse switch:

Get-ChildItem -Path V:\Myfolder -Filter CopyForbuild.bat -Recurse -ErrorAction SilentlyContinue -Force

How do I convert datetime to ISO 8601 in PHP

Object Oriented

This is the recommended way.

$datetime = new DateTime('2010-12-30 23:21:46');

echo $datetime->format(DateTime::ATOM); // Updated ISO8601

Procedural

For older versions of PHP, or if you are more comfortable with procedural code.

echo date(DATE_ISO8601, strtotime('2010-12-30 23:21:46'));

How to get a single value from FormGroup

Dot notation will break the type checking, switch to bracket notation. You might also try using the get() method. It also keeps AOT compilation in tact I've read.

this.form.get('controlName').value // safer
this.form.controlName.value // triggers type checking and breaks AOT

In Typescript, How to check if a string is Numeric

My simple solution here is:

const isNumeric = (val: string) : boolean => {
   return !isNaN(Number(val));
}

// isNumberic("2") => true
// isNumeric("hi") => false;

How do I compare two string variables in an 'if' statement in Bash?

Bash 4+ examples. Note: not using quotes will cause issues when words contain spaces, etc. Always quote in Bash IMO.

Here are some examples Bash 4+:

Example 1, check for 'yes' in string (case insensitive):

if [[ "${str,,}" == *"yes"* ]] ;then

Example 2, check for 'yes' in string (case insensitive):

if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then

Example 3, check for 'yes' in string (case sensitive):

 if [[ "${str}" == *"yes"* ]] ;then

Example 4, check for 'yes' in string (case sensitive):

 if [[ "${str}" =~ "yes" ]] ;then

Example 5, exact match (case sensitive):

 if [[ "${str}" == "yes" ]] ;then

Example 6, exact match (case insensitive):

 if [[ "${str,,}" == "yes" ]] ;then

Example 7, exact match:

 if [ "$a" = "$b" ] ;then

Simple way to calculate median with MySQL

Takes care about an odd value count - gives the avg of the two values in the middle in that case.

SELECT AVG(val) FROM
  ( SELECT x.id, x.val from data x, data y
      GROUP BY x.id, x.val
      HAVING SUM(SIGN(1-SIGN(IF(y.val-x.val=0 AND x.id != y.id, SIGN(x.id-y.id), y.val-x.val)))) IN (ROUND((COUNT(*))/2), ROUND((COUNT(*)+1)/2))
  ) sq

What does the red exclamation point icon in Eclipse mean?

I found another scenario in which the red exclamation mark might appear. I copied a directory from one project to another. This directory included a hidden .svn directory (the original project had been committed to version control). When I checked my new project into SVN, the copied directory still contained the old SVN information, incorrectly identifying itself as an element in its original project.

I discovered the problem by looking at the Properties for the directory, selecting SVN Info, and reviewing the Resource URL. I fixed the problem by deleting the hidden .svn directory for my copied directory and refreshing my project. The red exclamation mark disappeared, and I was able to check in the directory and its contents correctly.

How to select rows where column value IS NOT NULL using CodeIgniter's ActiveRecord?

You can do (if you want to test NULL)

$this->db->where_exec('archived IS NULL) 

If you want to test NOT NULL

$this->db->where_exec('archived IS NOT NULL) 

Pick images of root folder from sub-folder

Your index.html can just do src="images/logo.png" and from sub.html you would do src="../images/logo.png"

how to set value of a input hidden field through javascript?

It seems to work fine in Google Chrome. Which browser are you using? Here the proof http://jsfiddle.net/CN8XL/

Anyhow you can also access to the input value parameter through the document.FormName.checkyear.value. You have to wrap in the input in a <form> tag like with the proper name attribute, like shown below:

<form name="FormName">
    <input type="hidden" name="checkyear" id="checkyear" value="">
</form>

Have you considered using the jQuery Library? Here are the docs for .val() function.

How do I find out which settings.xml file maven is using

Use the Maven debug option, ie mvn -X :

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
Maven home: /usr/java/apache-maven-3.0.3
Java version: 1.6.0_12, vendor: Sun Microsystems Inc.
Java home: /usr/java/jdk1.6.0_12/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "2.6.32-32-generic", arch: "i386", family: "unix"
[INFO] Error stacktraces are turned on.
[DEBUG] Reading global settings from /usr/java/apache-maven-3.0.3/conf/settings.xml
[DEBUG] Reading user settings from /home/myhome/.m2/settings.xml
...

In this output, you can see that the settings.xml is loaded from /home/myhome/.m2/settings.xml.

How do I do logging in C# without using 3rd party libraries?

If you want to stay close to .NET check out Enterprise Library Logging Application Block. Look here. Or for a quickstart tutorial check this. I have used the Validation application Block from the Enterprise Library and it really suits my needs and is very easy to "inherit" (install it and refrence it!) in your project.

When is a language considered a scripting language?

Paraphrasing Robert Sebesta in Concepts of Programming Languages:

A scripting language is used by putting a list of commands, called a script, in a file to be executed. The first of these languages, named sh (for shell), began as a small collection of commands that were interpreted as calls to system sub-programs that performed utility funcions, such as file management and simple file filtering. To this basis were added variables, control flow statemens, functions, and various other capabilities, and the result is a complete programming language.

And then you have examples like AWK, Tcl/Tk, Perl (which says that initially was a combination between sh and AWK, but it became so powerful that he considers it an "odd but full-fledged programming language"). Other examples include CGI and JavaScript.

Is there a way to remove unused imports and declarations from Angular 2+?

Since VSCode v.1.24 and TypeScript v.2.9:

For Mac: option+Shift+O

For Win: Alt+Shift+O

how to generate web service out of wsdl

You can generate the WS proxy classes using WSCF (Web Services Contract First) tool from thinktecture.com. So essentially, YOU CAN create webservices from wsdl's. Creating the asmx's, maybe not, but that's the easy bit isn't it? This tool integrates brilliantly into VS2005-8 (new version for 2010/WCF called WSCF-blue). I've used it loads and always found it to be really good.

How to Lazy Load div background images

It's been a moment that this question is asked, but this doesn't mean that we can't share other answers in 2020. Here is an awesome plugin with jquery:jQuery Lazy

The basic usage of Lazy:

HTML

<!-- load background images of other element types -->
<div class="lazy" data-src="path/to/image.jpg"></div>
enter code here

JS

 $('.lazy').Lazy({
    // your configuration goes here
    scrollDirection: 'vertical',
    effect: 'fadeIn',
    visibleOnly: true,
    onError: function(element) {
        console.log('error loading ' + element.data('src'));
    }
});

and your background images are lazy loading. That's all!

To see real examples and more details check this link lazy-doc.

node.js execute system command synchronously

Use ShellJS module.

exec function without providing callback.

Example:

var version = exec('node -v').output;

JUNIT testing void methods

You can still unit test a void method by asserting that it had the appropriate side effect. In your method1 example, your unit test might look something like:

public void checkIfValidElementsWithDollarSign() {
    checkIfValidElement("$",19);
    assert ErrorFile.errorMessages.contains("There is a dollar sign in the specified parameter");
}

How to re-enable right click so that I can inspect HTML elements in Chrome?

You could use javascript:void(document.oncontextmenu=null); open Browser console and run the code above. It will turn off blockin' of mouse right button

Making an iframe responsive

The best solution to make an "iframe" responsive and fit with all device screens , simply apply this code (working great with Games sites):

iframe::-webkit-scrollbar{display:none}
.iframe{background:#fff;overflow:hidden}
.iframe iframe{width:100%;height:540px;border:0;display:block}
.iframe-content{position:absolute;width:100%;height:540px;overflow:auto;top:0;bottom:0;-webkit-overflow-scrolling:touch}

@media screen and (max-width:992px){.iframe iframe{height:720px}}
@media screen and (max-width:768px){.iframe iframe{height:720px}}
@media screen and (max-width:720px){.iframe iframe{height:720px}}
@media screen and (max-width:479px){.iframe iframe{height:480px}}
@media screen and (max-height:400px){.iframe iframe{height:360px}}

If you're looking for a responsive games container fit with all devices apply this code which uses advanced CSS @media queries.

Using 'make' on OS X

In addition, if you have migrated your user files and applications from one mac to another, you need to install Apple Developer Tools all over again. The migration assistant does not account for the developer tools installation.

How to use Java property files?

in my opinion other ways are deprecated when we can do it very simple as below:

@PropertySource("classpath:application.properties")
public class SomeClass{

    @Autowired
    private Environment env;

    public void readProperty() {
        env.getProperty("language");
    }

}

it is so simple but i think that's the best way!! Enjoy

Permanently add a directory to PYTHONPATH?

The add a new path to PYTHONPATH is doing in manually by:

adding the path to your ~/.bashrc profile, in terminal by:

vim ~/.bashrc

paste the following to your profile

export PYTHONPATH="${PYTHONPATH}:/User/johndoe/pythonModule"

then, make sure to source your bashrc profile when ever you run your code in terminal:

source ~/.bashrc 

Hope this helps.

Convert String to Integer in XSLT 1.0

Adding to jelovirt's answer, you can use number() to convert the value to a number, then round(), floor(), or ceiling() to get a whole integer.

Example

<xsl:variable name="MyValAsText" select="'5.14'"/>
<xsl:value-of select="number($MyValAsText) * 2"/> <!-- This outputs 10.28 -->
<xsl:value-of select="floor($MyValAsText)"/> <!-- outputs 5 -->
<xsl:value-of select="ceiling($MyValAsText)"/> <!-- outputs 6 -->
<xsl:value-of select="round($MyValAsText)"/> <!-- outputs 5 -->

GitHub README.md center image

You can also resize the image to the desired width and height. For example:

<p align="center">
  <img src="https://anyserver.com/image.png" width="750px" height="300px"/></p>

To add a centered caption to the image, just one more line:

<p align="center">This is a centered caption for the image<p align="center">

Fortunately, this works both for README.md and the GitHub Wiki pages.

Override valueof() and toString() in Java enum

You can try out this code. Since you cannot override valueOf method you have to define a custom method (getEnum in the sample code below) which returns the value that you need and change your client to use this method instead.

public enum RandomEnum {

    StartHere("Start Here"),
    StopHere("Stop Here");

    private String value;

    RandomEnum(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        return this.getValue();
    }

    public static RandomEnum getEnum(String value) {
        for(RandomEnum v : values())
            if(v.getValue().equalsIgnoreCase(value)) return v;
        throw new IllegalArgumentException();
    }
}

How to execute two mysql queries as one in PHP/MYSQL?

As others have answered, the mysqli API can execute multi-queries with the msyqli_multi_query() function.

For what it's worth, PDO supports multi-query by default, and you can iterate over the multiple result sets of your multiple queries:

$stmt = $dbh->prepare("
    select sql_calc_found_rows * from foo limit 1 ; 
    select found_rows()");
$stmt->execute();
do {
  while ($row = $stmt->fetch()) {
    print_r($row);
  }
} while ($stmt->nextRowset());

However, multi-query is pretty widely considered a bad idea for security reasons. If you aren't careful about how you construct your query strings, you can actually get the exact type of SQL injection vulnerability shown in the classic "Little Bobby Tables" XKCD cartoon. When using an API that restrict you to single-query, that can't happen.

How do I force my .NET application to run as administrator?

The detailed steps are as follow.

  1. Add application manifest file to solution
  2. Change application setting to "app.manifest"
  3. Update tag of "requestedExecutionLevel" to requireAdministrator.

Adding file in Solution

Select Application Manifest File

Select Manifest option

Update Manifest file

Note that using this code you need to turn off the security settings of ClickOnce, for do this, go inside Properties -> Security -> ClickOnce Security

Use querystring variables in MVC controller

My problem was overwriting my query string parameters with default values:

routes.MapRoute(
    "apiRoute", 
    "api/{action}/{key}", 
    new { controller = "Api", action = "Prices", key = ""}
);

No matter what I plugged into query string or how only key="" results.

Then got rid of default overwrites using UrlParameter.Optional:

routes.MapRoute(
    "apiRoute", 
    "api/{action}/{key}", 
    new { controller = "Api", action = "Prices", key = UrlParameter.Optional }
);

now

prices/{key} 

or

prices?key={key} 

both work fine.

How to read/write arbitrary bits in C/C++

You have to do a shift and mask (AND) operation. Let b be any byte and p be the index (>= 0) of the bit from which you want to take n bits (>= 1).

First you have to shift right b by p times:

x = b >> p;

Second you have to mask the result with n ones:

mask = (1 << n) - 1;
y = x & mask;

You can put everything in a macro:

#define TAKE_N_BITS_FROM(b, p, n) ((b) >> (p)) & ((1 << (n)) - 1)

Detect click event inside iframe

The tinymce API takes care of many events in the editors iframe. I strongly suggest to use them. Here is an example for the click handler

// Adds an observer to the onclick event using tinyMCE.init
tinyMCE.init({
   ...
   setup : function(ed) {
      ed.onClick.add(function(ed, e) {
           console.debug('Iframe clicked:' + e.target);
      });
   }
});

How to add a new column to an existing sheet and name it?

For your question as asked

Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))

If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

You may need to handle javax.persistence.RollbackException

What's the difference between SHA and AES encryption?

SHA doesn't require anything but an input to be applied, while AES requires at least 3 things - what you're encrypting/decrypting, an encryption key, and the initialization vector.

How to alter a column and change the default value?

If you want to add a default value for the already created column, this works for me:

ALTER TABLE Persons
ALTER credit SET DEFAULT 0.0;

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

While this question has been answered already (it's a bug that causes bottomLeftRadius and bottomRightRadius to be reversed), the bug has been fixed in android 3.1 (api level 12 - tested on the emulator).

So to make sure your drawables look correct on all platforms, you should put "corrected" versions of the drawables (i.e. where bottom left/right radii are actually correct in the xml) in the res/drawable-v12 folder of your app. This way all devices using an android version >= 12 will use the correct drawable files, while devices using older versions of android will use the "workaround" drawables that are located in the res/drawables folder.

Iterating each character in a string using Python

Just to make a more comprehensive answer, the C way of iterating over a string can apply in Python, if you really wanna force a square peg into a round hole.

i = 0
while i < len(str):
    print str[i]
    i += 1

But then again, why do that when strings are inherently iterable?

for i in str:
    print i

How to convert Calendar to java.sql.Date in Java?

Did you try cal.getTime()? This gets the date representation.

You might also want to look at the javadoc.

Pass all variables from one shell script to another?

You have basically two options:

  1. Make the variable an environment variable (export TESTVARIABLE) before executing the 2nd script.
  2. Source the 2nd script, i.e. . test2.sh and it will run in the same shell. This would let you share more complex variables like arrays easily, but also means that the other script could modify variables in the source shell.

UPDATE:

To use export to set an environment variable, you can either use an existing variable:

A=10
# ...
export A

This ought to work in both bash and sh. bash also allows it to be combined like so:

export A=10

This also works in my sh (which happens to be bash, you can use echo $SHELL to check). But I don't believe that that's guaranteed to work in all sh, so best to play it safe and separate them.

Any variable you export in this way will be visible in scripts you execute, for example:

a.sh:

#!/bin/sh

MESSAGE="hello"
export MESSAGE
./b.sh

b.sh:

#!/bin/sh

echo "The message is: $MESSAGE"

Then:

$ ./a.sh
The message is: hello

The fact that these are both shell scripts is also just incidental. Environment variables can be passed to any process you execute, for example if we used python instead it might look like:

a.sh:

#!/bin/sh

MESSAGE="hello"
export MESSAGE
./b.py

b.py:

#!/usr/bin/python

import os

print 'The message is:', os.environ['MESSAGE']

Sourcing:

Instead we could source like this:

a.sh:

#!/bin/sh

MESSAGE="hello"

. ./b.sh

b.sh:

#!/bin/sh

echo "The message is: $MESSAGE"

Then:

$ ./a.sh
The message is: hello

This more or less "imports" the contents of b.sh directly and executes it in the same shell. Notice that we didn't have to export the variable to access it. This implicitly shares all the variables you have, as well as allows the other script to add/delete/modify variables in the shell. Of course, in this model both your scripts should be the same language (sh or bash). To give an example how we could pass messages back and forth:

a.sh:

#!/bin/sh

MESSAGE="hello"

. ./b.sh

echo "[A] The message is: $MESSAGE"

b.sh:

#!/bin/sh

echo "[B] The message is: $MESSAGE"

MESSAGE="goodbye"

Then:

$ ./a.sh
[B] The message is: hello
[A] The message is: goodbye

This works equally well in bash. It also makes it easy to share more complex data which you could not express as an environment variable (at least without some heavy lifting on your part), like arrays or associative arrays.

Is there a way to override class variables in Java?

It indeed prints 'dad', since the field is not overridden but hidden. There are three approaches to make it print 'son':

Approach 1: override printMe

class Dad
{
    protected static String me = "dad";

    public void printMe()
    {
        System.out.println(me);
    }
}

class Son extends Dad
{
    protected static String me = "son";

    @override
    public void printMe()
    {
        System.out.println(me);
    }
}

public void doIt()
{
    new Son().printMe();
}

Approach 2: don't hide the field and initialize it in the constructor

class Dad
{
    protected static String me = "dad";

    public void printMe()
    {
        System.out.println(me);
    }
}

class Son extends Dad
{
    public Son()
    {
        me = "son";
    }
}

public void doIt()
{
    new Son().printMe();
}

Approach 3: use the static value to initialize a field in the constructor

class Dad
{
    private static String meInit = "Dad";

    protected String me;

    public Dad() 
    {
       me = meInit;
    }

    public void printMe()
    {
        System.out.println(me);
    }
}

class Son extends Dad
{
    private static String meInit = "son";

    public Son()
    {
        me = meInit;
    }

}

public void doIt()
{
    new Son().printMe();
}

C# Threading - How to start and stop a thread

Thread th = new Thread(function1);
th.Start();
th.Abort();

void function1(){
//code here
}

Blur the edges of an image or background image with CSS

If you set the image in div, you also must set both height and width. This may cause the image to lose its proportion. In addition, you must set the image URL in CSS instead of HTML.

Instead, you can set the image using the IMG tag. In the container class you can only set the width in percent or pixel and the height will automatically maintain proportion.

This is also more effective for accessibility of search engines and reading engines to define an image using an IMG tag.

_x000D_
_x000D_
.container {_x000D_
 margin: auto;_x000D_
 width: 200px;_x000D_
 position: relative;_x000D_
}_x000D_
_x000D_
img {_x000D_
 width: 100%;_x000D_
}_x000D_
_x000D_
.block {_x000D_
 width: 100%;_x000D_
 position: absolute;_x000D_
 bottom: 0px;_x000D_
 top: 0px;_x000D_
 box-shadow: inset 0px 0px 10px 20px white;_x000D_
}
_x000D_
<div class="container">_x000D_
 <img src="http://lorempixel.com/200/200/city">_x000D_
 <div class="block"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Apache Spark: map vs mapPartitions?

Map:

Map transformation.

The map works on a single Row at a time.

Map returns after each input Row.

The map doesn’t hold the output result in Memory.

Map no way to figure out then to end the service.

// map example

val dfList = (1 to 100) toList

val df = dfList.toDF()

val dfInt = df.map(x => x.getInt(0)+2)

display(dfInt)

MapPartition:

MapPartition transformation.

MapPartition works on a partition at a time.

MapPartition returns after processing all the rows in the partition.

MapPartition output is retained in memory, as it can return after processing all the rows in a particular partition.

MapPartition service can be shut down before returning.

// MapPartition example

Val dfList = (1 to 100) toList

Val df = dfList.toDF()

Val df1 = df.repartition(4).rdd.mapPartition((int) => Iterator(itr.length))

Df1.collec()

//display(df1.collect())

For more details, please refer to the Spark map vs mapPartitions transformation article.

Hope this is helpful!

Uses of Action delegate in C#

We use a lot of Action delegate functionality in tests. When we need to build some default object and later need to modify it. I made little example. To build default person (John Doe) object we use BuildPerson() function. Later we add Jane Doe too, but we modify her birthdate and name and height.

public class Program
{
        public static void Main(string[] args)
        {
            var person1 = BuildPerson();

            Console.WriteLine(person1.Firstname);
            Console.WriteLine(person1.Lastname);
            Console.WriteLine(person1.BirthDate);
            Console.WriteLine(person1.Height);

            var person2 = BuildPerson(p =>
            {
                p.Firstname = "Jane";
                p.BirthDate = DateTime.Today;
                p.Height = 1.76;
            });

            Console.WriteLine(person2.Firstname);
            Console.WriteLine(person2.Lastname);
            Console.WriteLine(person2.BirthDate);
            Console.WriteLine(person2.Height);

            Console.Read();
        }

        public static Person BuildPerson(Action<Person> overrideAction = null)
        {
            var person = new Person()
            {
                Firstname = "John",
                Lastname = "Doe",
                BirthDate = new DateTime(2012, 2, 2)
            };

            if (overrideAction != null)
                overrideAction(person);

            return person;
        }
    }

    public class Person
    {
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public DateTime BirthDate { get; set; }
        public double Height { get; set; }
    }

Adding machineKey to web.config on web-farm sites

If you are using IIS 7.5 or later you can generate the machine key from IIS and save it directly to your web.config, within the web farm you then just copy the new web.config to each server.

  1. Open IIS manager.
  2. If you need to generate and save the MachineKey for all your applications select the server name in the left pane, in that case you will be modifying the root web.config file (which is placed in the .NET framework folder). If your intention is to create MachineKey for a specific web site/application then select the web site / application from the left pane. In that case you will be modifying the web.config file of your application.
  3. Double-click the Machine Key icon in ASP.NET settings in the middle pane:
  4. MachineKey section will be read from your configuration file and be shown in the UI. If you did not configure a specific MachineKey and it is generated automatically you will see the following options:
  5. Now you can click Generate Keys on the right pane to generate random MachineKeys. When you click Apply, all settings will be saved in the web.config file.

Full Details can be seen @ Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS and .NET development…

Checking for a null int value from a Java ResultSet

Another nice way of checking, if you have control the SQL, is to add a default value in the query itself for your int column. Then just check for that value.

e.g for an Oracle database, use NVL

SELECT NVL(ID_PARENT, -999) FROM TABLE_NAME;

then check

if (rs.getInt('ID_PARENT') != -999)
{
}

Of course this also is under the assumption that there is a value that wouldn't normally be found in the column.

Unpacking a list / tuple of pairs into two lists / tuples

>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')

Edit: Note that zip(*iterable) is its own inverse:

>>> list(source_list) == zip(*zip(*source_list))
True

When unpacking into two lists, this becomes:

>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True

Addition suggested by rocksportrocker.

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

1.3.1 fixed it.

Just update your extension and you should be good to go

How to declare a global variable in php?

This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.

define("myconstant", "value"); 

class globalVars {

    static $a = false;

    static $b = 0;

    static $c = array('first' => 2, 'second' => 5);

}


function test($num) {

    if (!globalVars::$a) {

        $returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';

        globalVars::$a = true;

    } else {

        $returnVal = 'I forgot';

    }

    return $returnVal;

}

echo test(9); ---> The value of 9 + 0 + 5 is 14.

echo "<br>";

echo globalVars::$a; ----> 1

The static keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.

Java: How to Indent XML Generated by Transformer

Neither of the suggested solutions worked for me. So I kept on searching for an alternative solution, which ended up being a mixture of the two before mentioned and a third step.

  1. set the indent-number into the transformerfactory
  2. enable the indent in the transformer
  3. wrap the otuputstream with a writer (or bufferedwriter)
//(1)
TransformerFactory tf = TransformerFactory.newInstance();
tf.setAttribute("indent-number", new Integer(2));

//(2)
Transformer t = tf.newTransformer();
t.setOutputProperty(OutputKeys.INDENT, "yes");

//(3)
t.transform(new DOMSource(doc),
new StreamResult(new OutputStreamWriter(out, "utf-8"));

You must do (3) to workaround a "buggy" behavior of the xml handling code.

Source: johnnymac75 @ http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446

(If I have cited my source incorrectly please let me know)

What would be the best method to code heading/title for <ul> or <ol>, Like we have <caption> in <table>?

I like to make use of the css :before and a data-* attribute for the list

HTML:

<ul data-header="heading"> 
<li>list item </li>
<li>list item </li>
<li>list item </li>
</ul>

CSS:

ul:before{
    content:attr(data-header);
    font-size:120%;
    font-weight:bold;
    margin-left:-15px;
}

This will make a list with the header on it that is whatever text is specified as the list's data-header attribute. You can then easily style it to your needs.

How do you make an element "flash" in jQuery

If including a library is overkill here is a solution that is guaranteed to work.

$('div').click(function() {
    $(this).css('background-color','#FFFFCC');
    setTimeout(function() { $(this).fadeOut('slow').fadeIn('slow'); } , 1000); 
    setTimeout(function() { $(this).css('background-color','#FFFFFF'); } , 1000); 
});
  1. Setup event trigger

  2. Set the background color of block element

  3. Inside setTimeout use fadeOut and fadeIn to create a little animation effect.

  4. Inside second setTimeout reset default background color

    Tested in a few browsers and it works nicely.

How to capitalize the first letter of text in a TextView in an Android Application

The accepted answer is good, but if you are using it to get values from a textView in android, it would be good to check if the string is empty. If the string is empty it would throw an exception.

private String capitizeString(String name){
    String captilizedString="";
    if(!name.trim().equals("")){
       captilizedString = name.substring(0,1).toUpperCase() + name.substring(1);
    }
    return captilizedString;
}

React.js: onChange event for contentEditable

This is the is simplest solution that worked for me.

<div
  contentEditable='true'
  onInput={e => console.log('Text inside div', e.currentTarget.textContent)}
>
Text inside div
</div>

AttributeError: Module Pip has no attribute 'main'

If python -m pip install --upgrade pip==9.0.3 doesn't work, and you're using Windows,

  1. Navigate to this directory and move the pip folders elsewhere.

enter image description here

  1. Close your IDE if you have it open.

  2. Press 'Repair' on Python 3.

enter image description here

  1. Your IDE should cease to detect pip packages and prompt you to install them. Install and keep the last stable pip version by blocking automatic updates. enter image description here

sql: check if entry in table A exists in table B

The classical answer that works in almost every environment is

SELECT ID, Name, blah, blah
FROM TableB TB
LEFT JOIN TableA TA
ON TB.ID=TA.ID
WHERE TA.ID IS NULL

sometimes NOT EXISTS may be not implemented (not working).

Bootstrap 3: Text overlay on image

Set the position to absolute; to move the caption area in the correct position

CSS

.post-content {
    background: none repeat scroll 0 0 #FFFFFF;
    opacity: 0.5;
    margin: -54px 20px 12px; 
    position: absolute;
}

Bootply

Alternate output format for psql

Also be sure to check out \H, which toggles HTML output on/off. Not necessarily easy to read at the console, but interesting for dumping into a file (see \o) or pasting into an editor/browser window for viewing, especially with multiple rows of relatively complex data.

What is the iPad user agent?

It seems to be general consensus that every mobile apple device, iphone, ipad, or ipod uses a user agent that contains both 'Mobile' and 'Safari'.

However, using the latest SDK (4.0.1) and reading the user agent on my rails server (using request.env["HTTP_USER_AGENT"]), we never get the 'Safari' part.

No matter whether the request is being made from the simulator or a real device, debug or release, it always looks something like this:

Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_1_2 like Mac OS X; de-de) AppleWebKit/528.18 (KHTML, like Gecko) Mobile/7D11"

Just no 'Safari'. :-( So we have to use the 'iPhone' part to be sure. That is something apple does not recommend doing.

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

For me changing compile to implementation fixed it

Before

compile 'androidx.recyclerview:recyclerview:1.0.0'
compile 'androidx.cardview:cardview:1.0.0'
//Retrofit Dependencies
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

After

implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.cardview:cardview:1.0.0'
//Retrofit Dependencies
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'

How do I use method overloading in Python?

Python 3.x includes standard typing library which allows for method overloading with the use of @overload decorator. Unfortunately, this is to make the code more readable, as the @overload decorated methods will need to be followed by a non-decorated method that handles different arguments. More can be found here here but for your example:

from typing import overload
from typing import Any, Optional
class A(object):
    @overload
    def stackoverflow(self) -> None:    
        print('first method')
    @overload
    def stackoverflow(self, i: Any) -> None:
        print('second method', i)
    def stackoverflow(self, i: Optional[Any] = None) -> None:
        if not i:
            print('first method')
        else:
            print('second method', i)

ob=A()
ob.stackoverflow(2)

How to use WinForms progress bar?

Since .NET 4.5 you can use combination of async and await with Progress for sending updates to UI thread:

private void Calculate(int i)
{
    double pow = Math.Pow(i, i);
}

public void DoWork(IProgress<int> progress)
{
    // This method is executed in the context of
    // another thread (different than the main UI thread),
    // so use only thread-safe code
    for (int j = 0; j < 100000; j++)
    {
        Calculate(j);

        // Use progress to notify UI thread that progress has
        // changed
        if (progress != null)
            progress.Report((j + 1) * 100 / 100000);
    }
}

private async void button1_Click(object sender, EventArgs e)
{
    progressBar1.Maximum = 100;
    progressBar1.Step = 1;

    var progress = new Progress<int>(v =>
    {
        // This lambda is executed in context of UI thread,
        // so it can safely update form controls
        progressBar1.Value = v;
    });

    // Run operation in another thread
    await Task.Run(() => DoWork(progress));

    // TODO: Do something after all calculations
}

Tasks are currently the preferred way to implement what BackgroundWorker does.

Tasks and Progress are explained in more detail here:

UL or DIV vertical scrollbar

Sometimes it is not eligible to set height to pixel values. However, it is possible to show vertical scrollbar through setting height of div to 100% and overflow to auto.

Let me show an example:

<div id="content" style="height: 100%; overflow: auto">
  <p>some text</p>
  <ul>
    <li>text</li>
    .....
    <li>text</li>
</div>

How to write JUnit test with Spring Autowire?

Make sure you have imported the correct package. If I remeber correctly there are two different packages for Autowiring. Should be :org.springframework.beans.factory.annotation.Autowired;

Also this looks wierd to me :

@ContextConfiguration("classpath*:conf/components.xml")

Here is an example that works fine for me :

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/applicationContext_mock.xml" })
public class OwnerIntegrationTest {

    @Autowired
    OwnerService ownerService;

    @Before
    public void setup() {

        ownerService.cleanList();

    }

    @Test
    public void testOwners() {

        Owner owner = new Owner("Bengt", "Karlsson", "Ankavägen 3");
        owner = ownerService.createOwner(owner);
        assertEquals("Check firstName : ", "Bengt", owner.getFirstName());
        assertTrue("Check that Id exist: ", owner.getId() > 0);

        owner.setLastName("Larsson");
        ownerService.updateOwner(owner);
        owner = ownerService.getOwner(owner.getId());
        assertEquals("Name is changed", "Larsson", owner.getLastName());

    }

#pragma mark in Swift?

Confirmed with an Apple Engineer in the Swift lab this morning at WWDC that there currently aren't any #pragma or equivalent at the moment, they consider this a bug, and it will arrive soon, so I am guessing beta 2, I hope.

Anyway, it's on it's way.


Xcode now supports //MARK:, //TODO: and //FIXME landmarks to annotate your code and lists them in the jump bar

How to obtain the chat_id of a private Telegram channel?

No need to convert the channel to public then make it private.

  1. find the id of your private channel. (There are numerous methods to do this, for example see this SO answer)

  2. curl -X POST "https://api.telegram.org/botxxxxxx:yyyyyyyyyyy/sendMessage" -d "chat_id=-100CHAT_ID&text=my sample text"

    replace xxxxxx:yyyyyyyyyyy with your bot id, and replace CHAT_ID with the channel id found in step 1. So if channel id is 1234 it would be chat_id=-1001234.

All done!

Get month name from number

Calendar API

From that you can see that calendar.month_name[3] would return March, and the array index of 0 is the empty string, so there's no need to worry about zero-indexing either.

Check that a input to UITextField is numeric only

   #import "NSString+Extension.h"

//@interface NSString (Extension)
//
//- (BOOL) isAnEmail;
//- (BOOL) isNumeric;
//
//@end

@implementation NSString (Extension)
 - (BOOL) isNumeric
    {
        NSString *emailRegex = @"[0-9]+";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

        return [emailTest evaluateWithObject:self];

    //    NSString *localDecimalSymbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];
    //    NSMutableCharacterSet *decimalCharacterSet = [NSMutableCharacterSet characterSetWithCharactersInString:localDecimalSymbol];
    //    [decimalCharacterSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
    //    
    //    NSCharacterSet* nonNumbers = [decimalCharacterSet invertedSet];
    //    NSRange r = [self rangeOfCharacterFromSet: nonNumbers];
    //    
    //    if (r.location == NSNotFound)
    //    {
    //        // check to see how many times the decimal symbol appears in the string. It should only appear once for the number to be numeric.
    //        int numberOfOccurances = [[self componentsSeparatedByString:localDecimalSymbol] count]-1;
    //        return (numberOfOccurances > 1) ? NO : YES;
    //    }
    //    else return NO;
    }

html5 audio player - jquery toggle click play/pause?

Here is my solution using jQuery

<script type="text/javascript">
    $('#mtoogle').toggle(
        function () {
            document.getElementById('playTune').pause();
        },
        function () {
            document.getElementById('playTune').play();
        }
    );
</script>

And the working demo

http://demo.ftutorials.com/html5-audio/

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

In my case the solution was quite simple. I added this header and the browsers opened the file in every test. header('Content-Disposition: attachment; filename="filename.pdf"');

Squash my last X commits together using Git

Based on this article I found this method easier for my usecase.

My 'dev' branch was ahead of 'origin/dev' by 96 commits (so these commits were not pushed to the remote yet).

I wanted to squash these commits into one before pushing the change. I prefere to reset the branch to the state of 'origin/dev' (this will leave all changes from the 96 commits unstaged) and then commit the changes at once:

git reset origin/dev
git add --all
git commit -m 'my commit message'

Python 3 - Encode/Decode vs Bytes/Str

To add to Lennart Regebro's answer There is even the third way that can be used:

encoded3 = str.encode(original, 'utf-8')
print(encoded3)

Anyway, it is actually exactly the same as the first approach. It may also look that the second way is a syntactic sugar for the third approach.


A programming language is a means to express abstract ideas formally, to be executed by the machine. A programming language is considered good if it contains constructs that one needs. Python is a hybrid language -- i.e. more natural and more versatile than pure OO or pure procedural languages. Sometimes functions are more appropriate than the object methods, sometimes the reverse is true. It depends on mental picture of the solved problem.

Anyway, the feature mentioned in the question is probably a by-product of the language implementation/design. In my opinion, this is a nice example that show the alternative thinking about technically the same thing.

In other words, calling an object method means thinking in terms "let the object gives me the wanted result". Calling a function as the alternative means "let the outer code processes the passed argument and extracts the wanted value".

The first approach emphasizes the ability of the object to do the task on its own, the second approach emphasizes the ability of an separate algoritm to extract the data. Sometimes, the separate code may be that much special that it is not wise to add it as a general method to the class of the object.

Using 'sudo apt-get install build-essentials'

Drop the 's' off of the package name.

You want sudo apt-get install build-essential

You may also need to run sudo apt-get update to make sure that your package index is up to date.

For anyone wondering why this package may be needed as part of another install, it contains the essential tools for building most other packages from source (C/C++ compiler, libc, and make).

Html.Textbox VS Html.TextboxFor

Ultimately they both produce the same HTML but Html.TextBoxFor() is strongly typed where as Html.TextBox isn't.

1:  @Html.TextBox("Name")
2:  Html.TextBoxFor(m => m.Name)

will both produce

<input id="Name" name="Name" type="text" />

So what does that mean in terms of use?

Generally two things:

  1. The typed TextBoxFor will generate your input names for you. This is usually just the property name but for properties of complex types can include an underscore such as 'customer_name'
  2. Using the typed TextBoxFor version will allow you to use compile time checking. So if you change your model then you can check whether there are any errors in your views.

It is generally regarded as better practice to use the strongly typed versions of the HtmlHelpers that were added in MVC2.

How to set custom location for local installation of npm package?

TL;DR

You can do this by using the --prefix flag and the --global* flag.

pje@friendbear:~/foo $ npm install bower -g --prefix ./vendor/node_modules
[email protected] /Users/pje/foo/vendor/node_modules/bower

*Even though this is a "global" installation, installed bins won't be accessible through the command line unless ~/foo/vendor/node_modules exists in PATH.

TL;DR

Every configurable attribute of npm can be set in any of six different places. In order of priority:

  • Command-Line Flags: --prefix ./vendor/node_modules
  • Environment Variables: NPM_CONFIG_PREFIX=./vendor/node_modules
  • User Config File: $HOME/.npmrc or userconfig param
  • Global Config File: $PREFIX/etc/npmrc or userconfig param
  • Built-In Config File: path/to/npm/itself/npmrc
  • Default Config: node_modules/npmconf/config-defs.js

By default, locally-installed packages go into ./node_modules. global ones go into the prefix config variable (/usr/local by default).

You can run npm config list to see your current config and npm config edit to change it.

PS

In general, npm's documentation is really helpful. The folders section is a good structural overview of npm and the config section answers this question.

PostgreSQL create table if not exists

Try this:

CREATE TABLE IF NOT EXISTS app_user (
  username varchar(45) NOT NULL,
  password varchar(450) NOT NULL,
  enabled integer NOT NULL DEFAULT '1',
  PRIMARY KEY (username)
)

Converting string to number in javascript/jQuery

You can use parseInt(string, radix) to convert string value to integer like this code below

var votevalue = parseInt($('button').data('votevalue'));
?

DEMO

How do I get the picture size with PIL?

from PIL import Image

im = Image.open('whatever.png')
width, height = im.size

According to the documentation.

Using .text() to retrieve only text not nested in child tags

I am not a jquery expert, but how about,

$('#listItem').children().first().text()

.Net picking wrong referenced assembly version

In case is saves someone else 3 hours... my case was a bit different. My code used DevExpress v11.1 v11.1.4.0. I had it all referenced correctly in my code. But .net memory profiler installed DevExpress v11.1 v11.1.12.0 in the GAC. In fact it wasn't the components I referenced but the ones they referenced internally that failed. Try as I might, the GAC is always checked first. It compiled and ran fine but I couldn't view the win forms designer and the stack trace was no help at all. Finally uninstalled .net memory profiler and all was restored.

Trying to embed newline in a variable in bash

The trivial solution is to put those newlines where you want them.

var="a
b
c"

Yes, that's an assignment wrapped over multiple lines.

However, you will need to double-quote the value when interpolating it, otherwise the shell will split it on whitespace, effectively turning each newline into a single space (and also expand any wildcards).

echo "$p"

Generally, you should double-quote all variable interpolations unless you specifically desire the behavior described above.

asp.net Button OnClick event not firing

in my case: make sure not exist any form element in your page other than top main form, this cause events not fired

Using jQuery to see if a div has a child with a certain class

If it's a direct child you can do as below if it could be nested deeper remove the >

$("#text-field").keydown(function(event) {
    if($('#popup>p.filled-text').length !== 0) {
        console.log("Found");
     }
});

MVVM: Tutorial from start to finish?

My blog has a complete series of tutorial starting from scratch for WPF MVVM and WPF Prism. Have a look here: http://blog.raffaeu.com/archive/2009/06/03/wpf-and-vmmv-tutorial-01-introduction.aspx

Java Immutable Collections

I believe the point here is that even if a collection is Unmodifiable, that does not ensure that it cannot change. Take for example a collection that evicts elements if they are too old. Unmodifiable just means that the object holding the reference cannot change it, not that it cannot change. A true example of this is Collections.unmodifiableList method. It returns an unmodifiable view of a List. The the List reference that was passed into this method is still modifiable and so the list can be modified by any holder of the reference that was passed. This can result in ConcurrentModificationExceptions and other bad things.

Immutable, mean that in no way can the collection be changed.

Second question: An Immutable collection does not mean that the objects contained in the collection will not change, just that collection will not change in the number and composition of objects that it holds. In other words, the collection's list of references will not change. That does not mean that the internals of the object being referenced cannot change.

Difference between return 1, return 0, return -1 and exit?

return n from main is equivalent to exit(n).

The valid returned is the rest of your program. It's meaning is OS dependent. On unix, 0 means normal termination and non-zero indicates that so form of error forced your program to terminate without fulfilling its intended purpose.

It's unusual that your example returns 0 (normal termination) when it seems to have run out of memory.

php_network_getaddresses: getaddrinfo failed: Name or service not known

$url = "http://user:[email protected]/abc.php?var1=def";
$contents = file_get_contents($url);
echo $contents;

How to check if a variable is an integer or a string?

In my opinion you have two options:

  • Just try to convert it to an int, but catch the exception:

    try:
        value = int(value)
    except ValueError:
        pass  # it was a string, not an int.
    

    This is the Ask Forgiveness approach.

  • Explicitly test if there are only digits in the string:

    value.isdigit()
    

    str.isdigit() returns True only if all characters in the string are digits (0-9).

    The unicode / Python 3 str type equivalent is unicode.isdecimal() / str.isdecimal(); only Unicode decimals can be converted to integers, as not all digits have an actual integer value (U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example).

    This is often called the Ask Permission approach, or Look Before You Leap.

The latter will not detect all valid int() values, as whitespace and + and - are also allowed in int() values. The first form will happily accept ' +10 ' as a number, the latter won't.

If your expect that the user normally will input an integer, use the first form. It is easier (and faster) to ask for forgiveness rather than for permission in that case.

How to increase font size in the Xcode editor?

Apply following some steps:

Go to xcode_preferences->Then select font and colors->select all the text options->click on the font section and change fonts u want

Timestamp with a millisecond precision: How to save them in MySQL

CREATE TABLE fractest( c1 TIME(3), c2 DATETIME(3), c3 TIMESTAMP(3) );

INSERT INTO fractest VALUES
('17:51:04.777', '2018-09-08 17:51:04.777', '2018-09-08 17:51:04.777');

How to get the current location in Google Maps Android API v2?

Only one condition, I tested that it wasn't null was, if you allow enough time to user to touch the "get my location" layer button, then it will not get null value.

did you specify the right host or port? error on Kubernetes

I had same error, this worked for me. Run

minikube status

if the response is

type: Control Plane
host: Stopped
kubelet: Stopped
apiserver: Stopped
kubeconfig: Stopped

run minikube start

type: Control Plane
host: Running
kubelet: Running
apiserver: Running
kubeconfig: Configured

You can proceed

Is it possible to use std::string in a constexpr?

As of C++20, yes.

As of C++17, you can use string_view:

constexpr std::string_view sv = "hello, world";

A string_view is a string-like object that acts as an immutable, non-owning reference to any sequence of char objects.

Converting string from snake_case to CamelCase in Ruby

The ruby core itself has no support to convert a string from snake case to (upper) camel case (also known as pascal case).

So you need either to make your own implementation or use an existing gem.

There is a small ruby gem called lucky_case which allows you to convert a string from any of the 10+ supported cases to another case easily:

require 'lucky_case'

# to get upper camel case (pascal case) as string
LuckyCase.pascal_case('app_user') # => 'AppUser'
# to get the pascal case constant
LuckyCase.constantize('app_user') # => AppUser
# or the opposite way
LuckyCase.snake_case('AppUser')   # => app_user

You can even monkey patch the String class if you want to:

require 'lucky_case/string'

'app_user'.pascal_case # => 'AppUser'
'app_user'.constantize # => AppUser
# ...

Have a look at the offical repository for more examples and documentation:

https://github.com/magynhard/lucky_case

Which command in VBA can count the number of characters in a string variable?

Try this:

word = "habit"
findchar = 'b"
replacechar = ""
charactercount = len(word) - len(replace(word,findchar,replacechar))

Delete rows containing specific strings in R

You could use dplyr::filter() and negate a grepl() match:

library(dplyr)

df %>% 
  filter(!grepl('REVERSE', Name))

Or with dplyr::filter() and negating a stringr::str_detect() match:

library(stringr)

df %>% 
  filter(!str_detect(Name, 'REVERSE'))

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

I have faced same problem since I have updated the latest react version. Solved like below.

My code was

async componentDidMount() {
  const { default: Component } = await importComponent();
  Nprogress.done();
  this.setState({
    component: <Component {...this.props} />
  });
}

Changed to

componentWillUnmount() {
  this.mounted = false;
}
async componentDidMount() {
  this.mounted = true;
  const { default: Component } = await importComponent();
  if (this.mounted) {
    this.setState({
      component: <Component {...this.props} />
    });
  }
}

mysql server port number

if you want to have your port as a variable, you can write php like this:

$username = user;
$password = pw;
$host = 127.0.0.1;
$database = dbname;
$port = 3308; 

$conn = mysql_connect($host.':'.$port, $username, $password);
$db=mysql_select_db($database,$conn);

Get the records of last month in SQL server

Last month consider as till last day of the month. 31/01/2016 here last day of the month would be 31 Jan. which is not similar to last 30 days.

SELECT CONVERT(DATE, DATEADD(DAY,-DAY(GETDATE()),GETDATE()))

HashMap: One Key, multiple Values

Apache Commons collection classes is the solution.

    MultiMap multiMapDemo = new MultiValueMap();

    multiMapDemo .put("fruit", "Mango");
    multiMapDemo .put("fruit", "Orange");
    multiMapDemo.put("fruit", "Blueberry");

    System.out.println(multiMap.get("fruit"));
   // Mango Orange Blueberry

Maven Dependency

    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -- 
     >
     <dependency>
         <groupId>org.apache.commons</groupId>
         <artifactId>commons-collections4</artifactId>
         <version>4.4</version>
    </dependency>

In android how to set navigation drawer header image and name programmatically in class file?

   FirebaseAuth firebaseauth = FirebaseAuth.getInstance(); 

   NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);   //displays text of header of nav drawer.
    View headerview = navigationView.getHeaderView(0);

    TextView tt1 = (TextView) headerview.findViewById(R.id.textview_username);
    tt1.setText(firebaseauth.getCurrentUser().getDisplayName());//username of logged in user.  

   TextView tt = (TextView) headerview.findViewById(R.id.textView_emailid);
    tt.setText(firebaseauth.getCurrentUser().getEmail());    //email id of logged in user.

    final ImageView img1 = (ImageView) headerview.findViewById(R.id.imageView_userimage);
    Glide.with(getApplicationContext())
            .load(firebaseauth.getCurrentUser().getPhotoUrl()).asBitmap().atMost().error(R.drawable.ic_selfie_point_icon)   //asbitmap after load always.
            .into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    img1.setImageBitmap(resource);
                }
            });

I have made this code by myself with some logic...Its 100% working.....pls do upvote my ans.

The textview and imageview are from @layout/nav_header_main.xml

How to split data into training/testing sets using sample function

Use caTools package in R sample code will be as follows:-

data
split = sample.split(data$DependentcoloumnName, SplitRatio = 0.6)
training_set = subset(data, split == TRUE)
test_set = subset(data, split == FALSE)

How to open a page in a new window or tab from code-behind

Use:

Target= "_blank" property of anchor tag

Given a filesystem path, is there a shorter way to extract the filename without its extension?

try

System.IO.Path.GetFileNameWithoutExtension(path); 

demo

string fileName = @"C:\mydir\myfile.ext";
string path = @"C:\mydir\";
string result;

result = Path.GetFileNameWithoutExtension(fileName);
Console.WriteLine("GetFileNameWithoutExtension('{0}') returns '{1}'", 
    fileName, result);

result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
    path, result);

// This code produces output similar to the following:
//
// GetFileNameWithoutExtension('C:\mydir\myfile.ext') returns 'myfile'
// GetFileName('C:\mydir\') returns ''

https://msdn.microsoft.com/en-gb/library/system.io.path.getfilenamewithoutextension%28v=vs.80%29.aspx

How to round the minute of a datetime object

A two line intuitive solution to round to a given time unit, here seconds, for a datetime object t:

format_str = '%Y-%m-%d %H:%M:%S'
t_rounded = datetime.strptime(datetime.strftime(t, format_str), format_str)

If you wish to round to a different unit simply alter format_str.

This approach does not round to arbitrary time amounts as above methods, but is a nicely Pythonic way to round to a given hour, minute or second.

Set variable value to array of strings

You're trying to assign three separate string literals to a single string variable. A valid string variable would be 'John, Sarah, George'. If you want embedded single quotes between the double quotes, you have to escape them.

Also, your actual SELECT won't work, because SQL databases won't parse the string variable out into individual literal values. You need to use dynamic SQL instead, and then execute that dynamic SQL statement. (Search this site for dynamic SQL, with the database engine you're using as the topic (as in [sqlserver] dynamic SQL), and you should get several examples.)

Using success/error/finally/catch with Promises in AngularJS

Promises are an abstraction over statements that allow us to express ourselves synchronously with asynchronous code. They represent a execution of a one time task.

They also provide exception handling, just like normal code, you can return from a promise or you can throw.

What you'd want in synchronous code is:

try{
  try{
      var res = $http.getSync("url");
      res = someProcessingOf(res);
  } catch (e) {
      console.log("Got an error!",e);
      throw e; // rethrow to not marked as handled
  }
  // do more stuff with res
} catch (e){
     // handle errors in processing or in error.
}

The promisified version is very similar:

$http.get("url").
then(someProcessingOf).
catch(function(e){
   console.log("got an error in initial processing",e);
   throw e; // rethrow to not marked as handled, 
            // in $q it's better to `return $q.reject(e)` here
}).then(function(res){
    // do more stuff
}).catch(function(e){
    // handle errors in processing or in error.
});

How to get the part of a file after the first line that matches a regular expression?

The following will print the line matching TERMINATE till the end of the file:

sed -n -e '/TERMINATE/,$p'

Explained: -n disables default behavior of sed of printing each line after executing its script on it, -e indicated a script to sed, /TERMINATE/,$ is an address (line) range selection meaning the first line matching the TERMINATE regular expression (like grep) to the end of the file ($), and p is the print command which prints the current line.

This will print from the line that follows the line matching TERMINATE till the end of the file:
(from AFTER the matching line to EOF, NOT including the matching line)

sed -e '1,/TERMINATE/d'

Explained: 1,/TERMINATE/ is an address (line) range selection meaning the first line for the input to the 1st line matching the TERMINATE regular expression, and d is the delete command which delete the current line and skip to the next line. As sed default behavior is to print the lines, it will print the lines after TERMINATE to the end of input.

Edit:

If you want the lines before TERMINATE:

sed -e '/TERMINATE/,$d'

And if you want both lines before and after TERMINATE in 2 different files in a single pass:

sed -e '1,/TERMINATE/w before
/TERMINATE/,$w after' file

The before and after files will contain the line with terminate, so to process each you need to use:

head -n -1 before
tail -n +2 after

Edit2:

IF you do not want to hard-code the filenames in the sed script, you can:

before=before.txt
after=after.txt
sed -e "1,/TERMINATE/w $before
/TERMINATE/,\$w $after" file

But then you have to escape the $ meaning the last line so the shell will not try to expand the $w variable (note that we now use double quotes around the script instead of single quotes).

I forgot to tell that the new line is important after the filenames in the script so that sed knows that the filenames end.


Edit: 2016-0530

Sébastien Clément asked: "How would you replace the hardcoded TERMINATE by a variable?"

You would make a variable for the matching text and then do it the same way as the previous example:

matchtext=TERMINATE
before=before.txt
after=after.txt
sed -e "1,/$matchtext/w $before
/$matchtext/,\$w $after" file

to use a variable for the matching text with the previous examples:

## Print the line containing the matching text, till the end of the file:
## (from the matching line to EOF, including the matching line)
matchtext=TERMINATE
sed -n -e "/$matchtext/,\$p"
## Print from the line that follows the line containing the 
## matching text, till the end of the file:
## (from AFTER the matching line to EOF, NOT including the matching line)
matchtext=TERMINATE
sed -e "1,/$matchtext/d"
## Print all the lines before the line containing the matching text:
## (from line-1 to BEFORE the matching line, NOT including the matching line)
matchtext=TERMINATE
sed -e "/$matchtext/,\$d"

The important points about replacing text with variables in these cases are:

  1. Variables ($variablename) enclosed in single quotes ['] won't "expand" but variables inside double quotes ["] will. So, you have to change all the single quotes to double quotes if they contain text you want to replace with a variable.
  2. The sed ranges also contain a $ and are immediately followed by a letter like: $p, $d, $w. They will also look like variables to be expanded, so you have to escape those $ characters with a backslash [\] like: \$p, \$d, \$w.

Is there a way to use use text as the background with CSS?

SVG text background image

_x000D_
_x000D_
body {_x000D_
    background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='50px' width='120px'><text x='0' y='15' fill='red' font-size='20'>I love SVG!</text></svg>");_x000D_
}
_x000D_
<p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p>_x000D_
<p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p><p>I hate SVG!</p>
_x000D_
_x000D_
_x000D_

Here is an indented version of the CSS so you can understand better. Note that this does not work, you need to use the single liner SVG from the snippet above instead:

body {
  background-image:url("data:image/svg+xml;utf8,
  <svg xmlns='http://www.w3.org/2000/svg' version='1.1'
       height='50px' width='120px'>
    <text x='0' y='15' fill='red' font-size='20'>I love SVG!</text>
  </svg>");
}

Not sure how portable this is (works on Firefox 31 and Chrome 36), and it is technically an image... but the source is inline and plain text, and it scales infinitely.

@senectus found that it works better on IE if you base64 encode it: https://stackoverflow.com/a/25593531/895245

How to turn a String into a JavaScript function call?

Based on Nicolas Gauthier answer:

var strng = 'someobj.someCallback';
var data = 'someData';

var func = window;
var funcSplit = strng.split('.');
for(i = 0;i < funcSplit.length;i++){
   //We maybe can check typeof and break the bucle if typeof != function
   func = func[funcSplit[i]];
}
func(data);

How to send email by using javascript or jquery

You can do it server-side with nodejs.

Check out the popular Nodemailer package. There are plenty of transports and plugins for integrating with services like AWS SES and SendGrid!

The following example uses SES transport (Amazon SES):

let nodemailer = require("nodemailer");
let aws = require("aws-sdk");
let transporter = nodemailer.createTransport({
  SES: new aws.SES({ apiVersion: "2010-12-01" })
});

How to use putExtra() and getExtra() for string data

Push Data

import android.content.Intent;

    ...

    Intent intent = 
        new Intent( 
            this, 
            MyActivity.class );
    intent.putExtra( "paramName", "paramValue" );
    startActivity( intent );

The above code might be inside the main activity. "MyActivity.class" is the second Activity we want to launch; it must be explicitly included in your AndroidManifest.xml file.

<activity android:name=".MyActivity" />

Pull Data

import android.os.Bundle;

    ...

    Bundle extras = getIntent().getExtras();
    if (extras != null)
    {
        String myParam = extras.getString("paramName");
    }
    else
    {
        //..oops!
    }

In this example, the above code would be inside your MyActivity.java file.

Gotchas

This method can only pass strings. So let's say you need to pass an ArrayList to your ListActivity; a possible workaround is to pass a comma-separated-string and then split it on the other side.

Alternative Solutions

Use SharedPreferences

How do you use math.random to generate random ints?

As an alternative, if there's not a specific reason to use Math.random(), use Random.nextInt():

import java.util.Random;

Random rnd = new Random();
int abc = rnd.nextInt(100); // +1 if you want 1-100, otherwise will be 0-99.

Add item to Listview control

I have done it like this and it seems to work:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string[] row = { textBox1.Text, textBox2.Text, textBox3.Text };
        var listViewItem = new ListViewItem(row); 
        listView1.Items.Add(listViewItem);
    }
}

Using PowerShell to write a file in UTF-8 without the BOM

Could use below to get UTF8 without BOM

$MyFile | Out-File -Encoding ASCII

Keyboard shortcut to clear cell output in Jupyter notebook

I just looked and found cell|all output|clear which worked with:

Server Information: You are using Jupyter notebook.

The version of the notebook server is: 6.1.5 The server is running on this version of Python: Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)]

Current Kernel Information: Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:37:02) [MSC v.1924 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.

Java synchronized method lock on object, or method?

From oracle documentation link

Making methods synchronized has two effects:

First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads

Have a look at this documentation page to understand intrinsic locks and lock behavior.

This will answer your question: On same object x , you can't call x.addA() and x.addB() at same time when one of the synchronized methods execution is in progress.

How to get the number of threads in a Java process

I have written a program to iterate all Threads created and printing getState() of each Thread

import java.util.Set;

public class ThreadStatus {
    public static void main(String args[]) throws Exception{
        for ( int i=0; i< 5; i++){
            Thread t = new Thread(new MyThread());
            t.setName("MyThread:"+i);
            t.start();
        }
        int threadCount = 0;
        Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
        for ( Thread t : threadSet){
            if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup()){
                System.out.println("Thread :"+t+":"+"state:"+t.getState());
                ++threadCount;
            }
        }
        System.out.println("Thread count started by Main thread:"+threadCount);
    }
}

class MyThread implements Runnable{
    public void run(){
        try{
            Thread.sleep(2000);
        }catch(Exception err){
            err.printStackTrace();
        }
    }
}

Output:

java ThreadStatus

Thread :Thread[MyThread:0,5,main]:state:TIMED_WAITING
Thread :Thread[main,5,main]:state:RUNNABLE
Thread :Thread[MyThread:1,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:4,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:2,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:3,5,main]:state:TIMED_WAITING
Thread count started by Main thread:6

If you remove below condition

if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup())

You will get below threads in output too, which have been started by system.

Reference Handler, Signal Dispatcher,Attach Listener and Finalizer.

Android: Share plain text using intent (to all messaging apps)

Images or binary data:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("image/jpg");
Uri uri = Uri.fromFile(new File(getFilesDir(), "foo.jpg"));
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri.toString());
startActivity(Intent.createChooser(sharingIntent, "Share image using"));

or HTML:

Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/html");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("<p>This is the text shared.</p>"));
startActivity(Intent.createChooser(sharingIntent,"Share using"));

Using psql how do I list extensions installed in a database?

In psql that would be

\dx

See the manual for details: http://www.postgresql.org/docs/current/static/app-psql.html

Doing it in plain SQL it would be a select on pg_extension:

SELECT * 
FROM pg_extension

http://www.postgresql.org/docs/current/static/catalog-pg-extension.html

How to use \n new line in VB msgbox() ...?

This work for me: MessageBox.Show("YourString" & vbcrlf & "YourNewLineString")

Releasing memory in Python

eryksun has answered question #1, and I've answered question #3 (the original #4), but now let's answer question #2:

Why does it release 50.5mb in particular - what is the amount that is released based on?

What it's based on is, ultimately, a whole series of coincidences inside Python and malloc that are very hard to predict.

First, depending on how you're measuring memory, you may only be measuring pages actually mapped into memory. In that case, any time a page gets swapped out by the pager, memory will show up as "freed", even though it hasn't been freed.

Or you may be measuring in-use pages, which may or may not count allocated-but-never-touched pages (on systems that optimistically over-allocate, like linux), pages that are allocated but tagged MADV_FREE, etc.

If you really are measuring allocated pages (which is actually not a very useful thing to do, but it seems to be what you're asking about), and pages have really been deallocated, two circumstances in which this can happen: Either you've used brk or equivalent to shrink the data segment (very rare nowadays), or you've used munmap or similar to release a mapped segment. (There's also theoretically a minor variant to the latter, in that there are ways to release part of a mapped segment—e.g., steal it with MAP_FIXED for a MADV_FREE segment that you immediately unmap.)

But most programs don't directly allocate things out of memory pages; they use a malloc-style allocator. When you call free, the allocator can only release pages to the OS if you just happen to be freeing the last live object in a mapping (or in the last N pages of the data segment). There's no way your application can reasonably predict this, or even detect that it happened in advance.

CPython makes this even more complicated—it has a custom 2-level object allocator on top of a custom memory allocator on top of malloc. (See the source comments for a more detailed explanation.) And on top of that, even at the C API level, much less Python, you don't even directly control when the top-level objects are deallocated.

So, when you release an object, how do you know whether it's going to release memory to the OS? Well, first you have to know that you've released the last reference (including any internal references you didn't know about), allowing the GC to deallocate it. (Unlike other implementations, at least CPython will deallocate an object as soon as it's allowed to.) This usually deallocates at least two things at the next level down (e.g., for a string, you're releasing the PyString object, and the string buffer).

If you do deallocate an object, to know whether this causes the next level down to deallocate a block of object storage, you have to know the internal state of the object allocator, as well as how it's implemented. (It obviously can't happen unless you're deallocating the last thing in the block, and even then, it may not happen.)

If you do deallocate a block of object storage, to know whether this causes a free call, you have to know the internal state of the PyMem allocator, as well as how it's implemented. (Again, you have to be deallocating the last in-use block within a malloced region, and even then, it may not happen.)

If you do free a malloced region, to know whether this causes an munmap or equivalent (or brk), you have to know the internal state of the malloc, as well as how it's implemented. And this one, unlike the others, is highly platform-specific. (And again, you generally have to be deallocating the last in-use malloc within an mmap segment, and even then, it may not happen.)

So, if you want to understand why it happened to release exactly 50.5mb, you're going to have to trace it from the bottom up. Why did malloc unmap 50.5mb worth of pages when you did those one or more free calls (for probably a bit more than 50.5mb)? You'd have to read your platform's malloc, and then walk the various tables and lists to see its current state. (On some platforms, it may even make use of system-level information, which is pretty much impossible to capture without making a snapshot of the system to inspect offline, but luckily this isn't usually a problem.) And then you have to do the same thing at the 3 levels above that.

So, the only useful answer to the question is "Because."

Unless you're doing resource-limited (e.g., embedded) development, you have no reason to care about these details.

And if you are doing resource-limited development, knowing these details is useless; you pretty much have to do an end-run around all those levels and specifically mmap the memory you need at the application level (possibly with one simple, well-understood, application-specific zone allocator in between).