Programs & Examples On #Log analysis

Log-analysis is the process of parsing log file, created from any logging service or application.

How do I use Notepad++ (or other) with msysgit?

Here is a solution with Cygwin:

#!/bin/dash -e
if [ "$1" ]
then k=$(cygpath -w "$1")
elif [ "$#" != 0 ]
then k=
fi
Notepad2 ${k+"$k"}
  1. If no path, pass no path

  2. If path is empty, pass empty path

  3. If path is not empty, convert to Windows format.

Then I set these variables:

export EDITOR=notepad2.sh
export GIT_EDITOR='dash /usr/local/bin/notepad2.sh'
  1. EDITOR allows script to work with Git

  2. GIT_EDITOR allows script to work with Hub commands

Source

datetime datatype in java

You can use Calendar.

     Calendar rightNow = Calendar.getInstance();

Calendar

Date4j alternative to Date, Calendar, and related Java classes

Lock down Microsoft Excel macro

Protect/Lock Excel VBA Code:

When we write VBA code it is often desired to have the VBA Macro code not visible to end-users. This is to protect your intellectual property and/or stop users messing about with your code. Just be aware that Excel's protection ability is far from what would be considered secure. There are also many VBA Password Recovery [tools] for sale on the www.

To protect your code, open the Excel Workbook and go to Tools>Macro>Visual Basic Editor (Alt+F11). Now, from within the VBE go to Tools>VBAProject Properties and then click the Protection page tab and then check "Lock project from viewing" and then enter your password and again to confirm it. After doing this you must save, close & reopen the Workbook for the protection to take effect.

(Emphasis mine)

Seems like your best bet. It won't stop people determined to steal your code but it's enough to stop casual pirates.

Remember, even if you were able to distribute a compiled copy of your code there'd be nothing to stop people decompiling it.

Not Equal to This OR That in Lua

For testing only two values, I'd personally do this:

if x ~= 0 and x ~= 1 then
    print( "X must be equal to 1 or 0" )
    return
end

If you need to test against more than two values, I'd stuff your choices in a table acting like a set, like so:

choices = {[0]=true, [1]=true, [3]=true, [5]=true, [7]=true, [11]=true}

if not choices[x] then
    print("x must be in the first six prime numbers")
    return
end

Angular IE Caching issue for $http

An option is to use the simple approach of adding a Timestamp with each request no need to clear cache.

    let c=new Date().getTime();
    $http.get('url?d='+c)

How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting

If you have already installed 2.2.5 and set as current ruby version, but still showing the same error even if the Ruby version 2.3.0 is not even installed, then just install the bundler.

gem install bundler

and then:

bundle install

TypeError: p.easing[this.easing] is not a function

For those who have a custom jQuery UI build (bower for ex.), add the effects core located in ..\jquery-ui\ui\effect.js.

Unable to establish SSL connection, how do I fix my SSL cert?

I meet this same question. The port 443 wasn't open in Centos.

Check the 443 port with the following command:

sudo lsof -i tcp:443

In the first line of /etc/httpd/conf.d/ssl.conf add this two lines:

LoadModule ssl_module modules/mod_ssl.so
Listen 443

Connect to SQL Server through PDO using SQL Server Driver

Well that's the best part about PDOs is that it's pretty easy to access any database. Provided you have installed those drivers, you should be able to just do:

$db = new PDO("sqlsrv:Server=YouAddress;Database=YourDatabase", "Username", "Password");

powershell - list local users and their groups

For Googlers, another way to get a list of users is to use:

Get-WmiObject -Class Win32_UserAccount

From http://buckeyejeeps.com/blog/?p=764

New features in java 7

The following list contains links to the the enhancements pages in the Java SE 7.

Swing
IO and New IO
Networking
Security
Concurrency Utilities
Rich Internet Applications (RIA)/Deployment
    Requesting and Customizing Applet Decoration in Dragg able Applets
    Embedding JNLP File in Applet Tag
    Deploying without Codebase
    Handling Applet Initialization Status with Event Handlers
Java 2D
Java XML – JAXP, JAXB, and JAX-WS
Internationalization
java.lang Package
    Multithreaded Custom Class Loaders in Java SE 7
Java Programming Language
    Binary Literals
    Strings in switch Statements
    The try-with-resources Statement
    Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
    Underscores in Numeric Literals
    Type Inference for Generic Instance Creation
    Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods
Java Virtual Machine (JVM)
    Java Virtual Machine Support for Non-Java Languages
    Garbage-First Collector
    Java HotSpot Virtual Machine Performance Enhancements
JDBC

Reference 1 Reference 2

How to link to part of the same document in Markdown?

This may be out-of-date thread but to create inner document links in markdown in Github use...
(NOTE: lowercase #title)

# Contents
 - [Specification](#specification) 
 - [Dependencies Title](#dependencies-title) 

## Specification
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. 

## Dependencies Title
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. Example text blah. Example text blah. 
Example text blah. Example text blah. 

A good question was made so I have edited my answer;

An inner link can be made to any title size using - #, ##, ###, #### I created a quick example below... https://github.com/aogilvie/markdownLinkTest

Ansible: deploy on multiple hosts in the same time

In my case I needed the configuration stage to be blocking as a whole, but execute each role in parallel. I've tackled this issue using the following code:

echo webserver loadbalancer database | tr ' ' '\n' \
| xargs -I % -P 3 bash -c 'ansible-playbook $1.yml' -- %

the -P 3 argument in xargs makes sure that all the commands are ran in parallel, each command executes the respective playbook and the command as a whole blocks until all parts are finished.

CSS3 Transition - Fade out effect

Here is another way to do the same.

fadeIn effect

.visible {
  visibility: visible;
  opacity: 1;
  transition: opacity 2s linear;
}

fadeOut effect

.hidden {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s 2s, opacity 2s linear;
}

UPDATE 1: I found more up-to-date tutorial CSS3 Transition: fadeIn and fadeOut like effects to hide show elements and Tooltip Example: Show Hide Hint or Help Text using CSS3 Transition here with sample code.

UPDATE 2: (Added details requested by @big-money)

When showing the element (by switching to the visible class), we want the visibility:visible to kick in instantly, so it’s ok to transition only the opacity property. And when hiding the element (by switching to the hidden class), we want to delay the visibility:hidden declaration, so that we can see the fade-out transition first. We’re doing this by declaring a transition on the visibility property, with a 0s duration and a delay. You can see a detailed article here.

I know I am too late to answer but posting this answer to save others time. Hope it helps you!!

Setting max-height for table cell contents

Just put the labels in a div inside the TD and put the height and overflow.. like below.

<table>
<tr>
  <td><div style="height:40px; overflow:hidden">Sample</div></td>
  <td><div style="height:40px; overflow:hidden">Text</div></td>
  <td><div style="height:40px; overflow:hidden">Here</div></td>
</tr>
</table>

Android Studio says "cannot resolve symbol" but project compiles

Invalidate Caches / Restart didn't work for me this time.

Found a solution like this:

  1. Remove the compile *** or implementation *** line in build.gradle.

  2. Clean and rebuild. Errors should be raised here.

  3. Add the line in step 1 back to build.gradle.

  4. Clean and rebuild.

Weird...

Javascript date.getYear() returns 111 in 2011?

From what I've read on Mozilla's JS pages, getYear is deprecated. As pointed out many times, getFullYear() is the way to go. If you're really wanting to use getYear() add 1900 to it.

var now = new Date(),
    year = now.getYear() + 1900;

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

On MAC Remove gradle-2.1-all folder from the following path /Users/amitsapra/.gradle/wrapper/dists/gradle-2.1-all and then try gradle build again. I faced same issues with 5.4.1-all.

It takes a little time but fixes everything

How to update a value, given a key in a hashmap?

Since I can't comment to a few answers due to less reputation, I will post a solution which I applied.

for(String key : someArray)
{
   if(hashMap.containsKey(key)//will check if a particular key exist or not 
   {
      hashMap.put(hashMap.get(key),value+1);// increment the value by 1 to an already existing key
   }
   else
   {
      hashMap.put(key,value);// make a new entry into the hashmap
   }
}

Transform DateTime into simple Date in Ruby on Rails

I recently wrote a gem to simplify this process and to neaten up your views, etc etc.

Check it out at: http://github.com/platform45/easy_dates

How to style a checkbox using CSS

SCSS / SASS Implementation

A more modern approach

For those using SCSS (or easily converted to SASS), the following will be helpful. Effectively, make an element next to the checkbox, which is the one that you will style. When the checkbox is clicked, the CSS restyles the sister element (to your new, checked style). Code is below:

_x000D_
_x000D_
label.checkbox {_x000D_
  input[type="checkbox"] {_x000D_
    visibility: hidden;_x000D_
    display: block;_x000D_
    height: 0;_x000D_
    width: 0;_x000D_
    position: absolute;_x000D_
    overflow: hidden;_x000D_
_x000D_
    &:checked + span {_x000D_
      background: $accent;_x000D_
    }_x000D_
  }_x000D_
_x000D_
  span {_x000D_
    cursor: pointer;_x000D_
    height: 15px;_x000D_
    width: 15px;_x000D_
    border: 1px solid $accent;_x000D_
    border-radius: 2px;_x000D_
    display: inline-block;_x000D_
    transition: all 0.2s $interpol;_x000D_
  }_x000D_
}
_x000D_
<label class="checkbox">_x000D_
    <input type="checkbox" />_x000D_
    <span></span>_x000D_
    Label text_x000D_
</label>
_x000D_
_x000D_
_x000D_

How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"

Your application has an AppCompat theme

<application
    android:theme="@style/AppTheme">

But, you overwrote the Activity (which extends AppCompatActivity) with a theme that isn't descendant of an AppCompat theme

<activity android:name=".MainActivity"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >

You could define your own fullscreen theme like so (notice AppCompat in the parent=)

<style name="AppFullScreenTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

Then set that on the Activity.

<activity android:name=".MainActivity"
    android:theme="@style/AppFullScreenTheme" >

Note: There might be an AppCompat theme that's already full screen, but don't know immediately

ORA-01950: no privileges on tablespace 'USERS'

You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run

ALTER USER <user> quota unlimited on <tablespace name>;

or

ALTER USER <user> quota 100M on <tablespace name>;

as a DBA user (depending on how much space you need / want to grant).

Is there a Python equivalent to Ruby's string interpolation?

For old Python (tested on 2.4) the top solution points the way. You can do this:

import string

def try_interp():
    d = 1
    f = 1.1
    s = "s"
    print string.Template("d: $d f: $f s: $s").substitute(**locals())

try_interp()

And you get

d: 1 f: 1.1 s: s

OpenSSL and error in reading openssl.conf file

set OPENSSL_CONF=c:/{path to openSSL}/bin/openssl.cfg

take care of the right extension (openssl.cfg not cnf)!

I have installed OpenSSL from here: http://slproweb.com/products/Win32OpenSSL.html

Open Source Alternatives to Reflector?

The main reason I used Reflector (and, I think, the main reason most people used it) was for its decompiler: it can translate a method's IL back into source code.

On that count, Monoflector would be the project to watch. It uses Cecil, which does the reflection, and Cecil.Decompiler, which does the decompilation. But Monoflector layers a UI on top of both libraries, which should give you a very good idea of how to use the API.

Monoflector is also a decent alternative to Reflector outright. It lets you browse the types and decompile the methods, which is 99% of what people used Reflector for. It's very rough around the edges, but I'm thinking that will change quickly.

Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

Pretty sure that this exception is thrown when the Excel file is either password protected or the file itself is corrupted. If you just want to read a .xlsx file, try my code below. It's a lot more shorter and easier to read.

import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
//.....

static final String excelLoc = "C:/Documents and Settings/Users/Desktop/testing.xlsx";

public static void ReadExcel() {
InputStream inputStream = null;
   try {
        inputStream = new FileInputStream(new File(excelLoc));
        Workbook wb = WorkbookFactory.create(inputStream);
        int numberOfSheet = wb.getNumberOfSheets();

        for (int i = 0; i < numberOfSheet; i++) {
             Sheet sheet = wb.getSheetAt(i);
             //.... Customize your code here
             // To get sheet name, try -> sheet.getSheetName()
        }
   } catch {}
}

How do I alter the position of a column in a PostgreSQL database table?

I use Django and it requires id column in each table if you don't want to have a headache. Unfortunately, I was careless and my table bp.geo_location_vague didn't contain this field. I initialed little trick. Step 1:

CREATE VIEW bp.geo_location_vague_vw AS
    SELECT 
        a.id, -- I change order of id column here. 
        a.in_date,
        etc
    FROM bp.geo_location_vague a

Step 2: (without create table - table will create automaticaly!)

SELECT * into bp.geo_location_vague_cp2 FROM bp.geo_location_vague_vw

Step 3:

CREATE SEQUENCE bp.tbl_tbl_id_seq;
ALTER TABLE bp.geo_location_vague_cp2 ALTER COLUMN id SET DEFAULT nextval('tbl_tbl_id_seq');
ALTER SEQUENCE bp.tbl_tbl_id_seq OWNED BY bp.geo_location_vague_cp2.id;
SELECT setval('tbl_tbl_id_seq', COALESCE(max(id), 0)) FROM bp.geo_location_vague_cp2;

Because I need have bigserial pseudotype in the table. After SELECT * into pg will create bigint type insetad bigserial.

step 4: Now we can drop the view, drop source table and rename the new table in the old name. The trick was ended successfully.

How to disable Google Chrome auto update?

If you are using Mac OS. Keep the version that you need and then following step help you stop updating chrome permanently.

To Disable auto update:-

Empty these directories:

~/Library/Google/GoogleSoftwareUpdate/

Then change the permissions on these folders named 'GoogleSoftwareUpdate' so that there's no owner and no read/write/execute permissions. In terminal:

cd /Library/Google/
sudo chown nobody:nogroup GoogleSoftwareUpdate
sudo chmod 000 GoogleSoftwareUpdate

cd ~/Library/Google/
sudo chown nobody:nogroup GoogleSoftwareUpdate
sudo chmod 000 GoogleSoftwareUpdate                                                                        

Then do the same for the folder Google one level up.

cd /Library/
sudo chown nobody:nogroup Google
sudo chmod 000 Google
cd ~/Library/                                                                                                                    
sudo chown nobody:nogroup Google
sudo chmod 000 Google

Hope this help!

How to get the selected item of a combo box to a string variable in c#

Try this:

string selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
MessageBox.Show(selected);

Unresolved external symbol in object files

See Linker Tools Error LNK2019 at MSDN, it has a detailed list of common problems that cause LNK2019.

How to find difference between two Joda-Time DateTimes in minutes

Something like...

DateTime today = new DateTime();
DateTime yesterday = today.minusDays(1);

Duration duration = new Duration(yesterday, today);
System.out.println(duration.getStandardDays());
System.out.println(duration.getStandardHours());
System.out.println(duration.getStandardMinutes());

Which outputs

1
24
1440

or

System.out.println(Minutes.minutesBetween(yesterday, today).getMinutes());

Which is probably more what you're after

I want to remove double quotes from a String

If you want to remove all double quotes in string, use

var str = '"some "quoted" string"';
console.log( str.replace(/"/g, '') );
// some quoted string

Otherwise you want to remove only quotes around the string, use:

var str = '"some "quoted" string"';
console.log( clean = str.replace(/^"|"$/g, '') );
// some "quoted" string

How to force Docker for a clean build of an image

To ensure that your build is completely rebuild, including checking the base image for updates, use the following options when building:

--no-cache - This will force rebuilding of layers already available

--pull - This will trigger a pull of the base image referenced using FROM ensuring you got the latest version.

The full command will therefore look like this:

docker build --pull --no-cache --tag myimage:version .

Same options are available for docker-compose:

docker-compose build --no-cache --pull

Note that if your docker-compose file references an image, the --pull option will not actually pull the image if there is one already.

To force docker-compose to re-pull this, you can run:

docker-compose pull

HTML image not showing in Gmail

Late to the party but here goes... I have experienced this problem as well and it was solved with the following:

  • Including the scheme in the src url (using "//" does not work - use full scheme EG: "https://")
  • Including width and height attributes
  • Including style="display:block" attribute
  • Including both alt and title attributes

EG:

<img src="https://static.mydomain.com/images/logo.png" alt="Logo" title="Logo" style="display:block" width="200" height="87" />

Bootstrap-select - how to fire event on change

Easiest implementation.

<script>
    $( ".selectpicker" ).change(function() {
        alert( "Handler for .change() called." );
    });
</script>

Checking whether a variable is an integer or not

Here's a summary of the different methods mentioned here:

  • int(x) == x
  • try x = operator.index(x)
  • isinstance(x, int)
  • isinstance(x, numbers.Integral)

and here's how they apply to a variety of numerical types that have integer value:

Table of methods for checking whether Python numerical types are integers

You can see they aren't 100% consistent. Fraction and Rational are conceptually the same, but one supplies a .index() method and the other doesn't. Complex types don't like to convert to int even if the real part is integral and imaginary part is 0.

(np.int8|16|32|64(5) means that np.int8(5), np.int32(5), etc. all behave identically)

How do you sort an array on multiple columns?

Try this:

t.sort( (a,b)=> a[3].localeCompare(b[3]) || a[1].localeCompare(b[1]) );

_x000D_
_x000D_
let t = [_x000D_
    //[publicationID, publication_name, ownderID, owner_name ]_x000D_
    [1, 'ZBC', 3, 'John Smith'],_x000D_
    [2, 'FBC', 5, 'Mike Tyson'],_x000D_
    [3, 'ABC', 7, 'Donald Duck'],_x000D_
    [4, 'DBC', 1, 'Michael Jackson'],_x000D_
    [5, 'XYZ', 2, 'Michael Jackson'],_x000D_
    [6, 'BBC', 4, 'Michael Jackson'],_x000D_
  ]; _x000D_
  _x000D_
  // owner_name subarrray index = 3_x000D_
  // publication_name subarrray index = 1_x000D_
_x000D_
t.sort( (a,b)=> a[3].localeCompare(b[3]) || a[1].localeCompare(b[1]) );_x000D_
_x000D_
console.log(t.join('\n'));
_x000D_
_x000D_
_x000D_

I assume that your data in array let t = [ [publicationID, publication_name, ownderID, owner_name ], ... ] where index of owner_name = 3 and publication_name =1.

How do I install a plugin for vim?

To expand on Karl's reply, Vim looks in a specific set of directories for its runtime files. You can see that set of directories via :set runtimepath?. In order to tell Vim to also look inside ~/.vim/vim-haml you'll want to add

set runtimepath+=$HOME/.vim/vim-haml

to your ~/.vimrc. You'll likely also want the following in your ~/.vimrc to enable all the functionality provided by vim-haml.

filetype plugin indent on
syntax on

You can refer to the 'runtimepath' and :filetype help topics in Vim for more information.

Match linebreaks - \n or \r\n?

In Python:

# as Peter van der Wal's answer
re.split(r'\r\n|\r|\n', text, flags=re.M) 

or more rigorous:

# https://docs.python.org/3/library/stdtypes.html#str.splitlines
str.splitlines()

Java: Convert String to TimeStamp

The easy way to convert String to java.sql.Timestamp:

Timestamp t = new Timestamp(DateUtil.provideDateFormat().parse("2019-01-14T12:00:00.000Z").getTime());

DateUtil.java:

import java.text.SimpleDateFormat;
import java.util.TimeZone;

public interface DateUtil {

  String ISO_DATE_FORMAT_ZERO_OFFSET = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
  String UTC_TIMEZONE_NAME = "UTC";

  static SimpleDateFormat provideDateFormat() {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(ISO_DATE_FORMAT_ZERO_OFFSET);
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone(UTC_TIMEZONE_NAME));
    return simpleDateFormat;
  }
}

XOR operation with two strings in java

the abs function is when the Strings are not the same length so the legth of the result will be the same as the min lenght of the two String a and b

public String xor(String a, String b){
    StringBuilder sb = new StringBuilder();
    for(int k=0; k < a.length(); k++)
       sb.append((a.charAt(k) ^ b.charAt(k + (Math.abs(a.length() - b.length()))))) ;
       return sb.toString();
}

How to emit an event from parent to child?

As far as I know, there are 2 standard ways you can do that.

1. @Input

Whenever the data in the parent changes, the child gets notified about this in the ngOnChanges method. The child can act on it. This is the standard way of interacting with a child.

Parent-Component
public inputToChild: Object;

Parent-HTML
<child [data]="inputToChild"> </child>       

Child-Component: @Input() data;

ngOnChanges(changes: { [property: string]: SimpleChange }){
   // Extract changes to the input property by its name
   let change: SimpleChange = changes['data']; 
// Whenever the data in the parent changes, this method gets triggered. You 
// can act on the changes here. You will have both the previous value and the 
// current value here.
}
  1. Shared service concept

Creating a service and using an observable in the shared service. The child subscribes to it and whenever there is a change, the child will be notified. This is also a popular method. When you want to send something other than the data you pass as the input, this can be used.

SharedService
subject: Subject<Object>;

Parent-Component
constructor(sharedService: SharedService)
this.sharedService.subject.next(data);

Child-Component
constructor(sharedService: SharedService)
this.sharedService.subject.subscribe((data)=>{

// Whenever the parent emits using the next method, you can receive the data 
in here and act on it.})

Why is the time complexity of both DFS and BFS O( V + E )

I think every edge has been considered twice and every node has been visited once, so the total time complexity should be O(2E+V).

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

Time::Piece::datetime() can eliminate T.

use Time::Piece;
print localtime->datetime(T => q{ });

Ajax passing data to php script

You can also use bellow code for pass data using ajax.

var dataString = "album" + title;
$.ajax({  
    type: 'POST',  
    url: 'test.php', 
    data: dataString,
    success: function(response) {
        content.html(response);
    }
});

How to remove a key from HashMap while iterating over it?

To remove specific key and element from hashmap use

hashmap.remove(key)

full source code is like

import java.util.HashMap;
public class RemoveMapping {
     public static void main(String a[]){
        HashMap hashMap = new HashMap();
        hashMap.put(1, "One");
        hashMap.put(2, "Two");
        hashMap.put(3, "Three");
        System.out.println("Original HashMap : "+hashMap);
        hashMap.remove(3);   
        System.out.println("Changed HashMap : "+hashMap);        
    }
}

Source : http://www.tutorialdata.com/examples/java/collection-framework/hashmap/remove-mapping-of-specified--key-from-hashmap

How to change the href for a hyperlink using jQuery

Even though the OP explicitly asked for a jQuery answer, you don't need to use jQuery for everything these days.

A few methods without jQuery:

  • If you want to change the href value of all <a> elements, select them all and then iterate through the nodelist: (example)

    var anchors = document.querySelectorAll('a');
    Array.prototype.forEach.call(anchors, function (element, index) {
        element.href = "http://stackoverflow.com";
    });
    
  • If you want to change the href value of all <a> elements that actually have an href attribute, select them by adding the [href] attribute selector (a[href]): (example)

    var anchors = document.querySelectorAll('a[href]');
    Array.prototype.forEach.call(anchors, function (element, index) {
        element.href = "http://stackoverflow.com";
    });
    
  • If you want to change the href value of <a> elements that contain a specific value, for instance google.com, use the attribute selector a[href*="google.com"]: (example)

    var anchors = document.querySelectorAll('a[href*="google.com"]');
    Array.prototype.forEach.call(anchors, function (element, index) {
        element.href = "http://stackoverflow.com";
    });
    

    Likewise, you can also use the other attribute selectors. For instance:

    • a[href$=".png"] could be used to select <a> elements whose href value ends with .png.

    • a[href^="https://"] could be used to select <a> elements with href values that are prefixed with https://.

  • If you want to change the href value of <a> elements that satisfy multiple conditions: (example)

    var anchors = document.querySelectorAll('a[href^="https://"], a[href$=".png"]');
    Array.prototype.forEach.call(anchors, function (element, index) {
        element.href = "http://stackoverflow.com";
    });
    

..no need for regex, in most cases.

How do I convert this list of dictionaries to a csv file?

this is when you have one dictionary list:

import csv
with open('names.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

java.lang.ClassNotFoundException is indicate that class is not found in class path. it could be the version of log4j is not compatible. check for different log4j version.

Drop shadow on a div container?

CSS3 has a box-shadow property. Vendor prefixes are required at the moment for maximum browser compatibility.

div.box-shadow {
    -webkit-box-shadow: 2px 2px 4px 1px #fff;
    box-shadow: 2px 2px 4px 1px #fff;
}

There is a generator available at css3please.

Ruby on Rails form_for select field with class

You can also add prompt option like this.

<%= f.select(:object_field, ['Item 1', 'Item 2'], {include_blank: "Select something"}, { :class => 'my_style_class' }) %>

How to get a MemoryStream from a Stream in .NET?

How do I copy the contents of one stream to another?

see that. accept a stream and copy to memory. you should not use .Length for just Stream because it is not necessarily implemented in every concrete Stream.

How to run a script file remotely using SSH

Backticks will run the command on the local shell and put the results on the command line. What you're saying is 'execute ./test/foo.sh and then pass the output as if I'd typed it on the commandline here'.

Try the following command, and make sure that thats the path from your home directory on the remote computer to your script.

ssh kev@server1 './test/foo.sh'

Also, the script has to be on the remote computer. What this does is essentially log you into the remote computer with the listed command as your shell. You can't run a local script on a remote computer like this (unless theres some fun trick I don't know).

How do I set the selenium webdriver get timeout?

Try this:

 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

Find Facebook user (url to profile page) by known email address

Maybe this is a little bit late but I found a web site which gives social media account details by know email addreess. It is https://www.fullcontact.com

You can use Person Api there and get the info.

This is a type of get : https://api.fullcontact.com/v2/person.xml?email=someone@****&apiKey=********

Also there is xml or json choice.

How do I resolve a HTTP 414 "Request URI too long" error?

Based on John's answer, I changed the GET request to a POST request. It works, without having to change the server configuration. So I went looking how to implement this. The following pages were helpful:

jQuery Ajax POST example with PHP (Note the sanitize posted data remark) and

http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

Basically, the difference is that the GET request has the url and parameters in one string and then sends null:

http.open("GET", url+"?"+params, true);
http.send(null);

whereas the POST request sends the url and the parameters in separate commands:

http.open("POST", url, true);
http.send(params);

Here is a working example:

ajaxPOST.html:

<html>
<head>
<script type="text/javascript">
    function ajaxPOSTTest() {
        try {
            // Opera 8.0+, Firefox, Safari
            ajaxPOSTTestRequest = new XMLHttpRequest();
        } catch (e) {
            // Internet Explorer Browsers
            try {
                ajaxPOSTTestRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    ajaxPOSTTestRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    // Something went wrong
                    alert("Your browser broke!");
                    return false;
                }
            }
        }

        ajaxPOSTTestRequest.onreadystatechange = ajaxCalled_POSTTest;
        var url = "ajaxPOST.php";
        var params = "lorem=ipsum&name=binny";
        ajaxPOSTTestRequest.open("POST", url, true);
        ajaxPOSTTestRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajaxPOSTTestRequest.send(params);
    }

    //Create a function that will receive data sent from the server
    function ajaxCalled_POSTTest() {
        if (ajaxPOSTTestRequest.readyState == 4) {
            document.getElementById("output").innerHTML = ajaxPOSTTestRequest.responseText;
        }
    }
</script>

</head>
<body>
    <button onclick="ajaxPOSTTest()">ajax POST Test</button>
    <div id="output"></div>
</body>
</html>

ajaxPOST.php:

<?php

$lorem=$_POST['lorem'];
print $lorem.'<br>';

?>

I just sent over 12,000 characters without any problems.

How do you list all triggers in a MySQL database?

You can use below to find a particular trigger definition.

SHOW TRIGGERS LIKE '%trigger_name%'\G

or the below to show all the triggers in the database. It will work for MySQL 5.0 and above.

SHOW TRIGGERS\G

How to create file object from URL object (image)

You can make use of ImageIO in order to load the image from an URL and then write it to a file. Something like this:

URL url = new URL("http://google.com/pathtoaimage.jpg");
BufferedImage img = ImageIO.read(url);
File file = new File("downloaded.jpg");
ImageIO.write(img, "jpg", file);

This also allows you to convert the image to some other format if needed.

My prerelease app has been "processing" for over a week in iTunes Connect, what gives?

I got this message from App Store Developer Support (2016-01-02):

Be aware that it can take up to 24 hours for a build to fully process through our system and become available for use. If a build does not finish processing in 24 hours, this can typically be resolved by submitting the build again with a higher build number.

Not much of an answer (nothing about why it can take so long time), but it's the answer Apple is giving us.

How to split long commands over multiple lines in PowerShell

You can use the backtick operator:

& "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" `
    -verb:sync `
    -source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web" `
    -dest:contentPath="c:\websites\xxx\wwwroot\,computerName=192.168.1.1,username=administrator,password=xxx"

That's still a little too long for my taste, so I'd use some well-named variables:

$msdeployPath = "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe"
$verbArg = '-verb:sync'
$sourceArg = '-source:contentPath="c:\workspace\xxx\master\Build\_PublishedWebsites\xxx.Web"'
$destArg = '-dest:contentPath="c:\websites\xxx\wwwroot\,computerName=192.168.1.1,username=administrator,password=xxx"'

& $msdeployPath $verbArg $sourceArg $destArg

Are there any style options for the HTML5 Date picker?

You can use the following CSS to style the input element.

_x000D_
_x000D_
input[type="date"] {_x000D_
  background-color: red;_x000D_
  outline: none;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-clear-button {_x000D_
  font-size: 18px;_x000D_
  height: 30px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-inner-spin-button {_x000D_
  height: 28px;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
  font-size: 15px;_x000D_
}
_x000D_
<input type="date" value="From" name="from" placeholder="From" required="" />
_x000D_
_x000D_
_x000D_

How to measure height, width and distance of object using camera?

First of all i will say Nice Thaught to develop such app.

Now i am not sure about it, but if you can able to get the face-detection like thing for any object in android camera so with help of that you can achieve that things.

Well i am not sure about it but still have give some view so you can get idea of it.

All the Best. :))

How can I download HTML source in C#

@cms way is the more recent, suggested in MS website, but I had a hard problem to solve, with both method posted here, now I post the solution for all!

problem: if you use an url like this: www.somesite.it/?p=1500 in some case you get an internal server error (500), although in web browser this www.somesite.it/?p=1500 perfectly work.

solution: you have to move out parameters, working code is:

using System.Net;
//...
using (WebClient client = new WebClient ()) 
{
    client.QueryString.Add("p", "1500"); //add parameters
    string htmlCode = client.DownloadString("www.somesite.it");
    //...
}

here official documentation

Does IE9 support console.log, and is it a real function?

In Internet Explorer 9 (and 8), the console object is only exposed when the developer tools are opened for a particular tab. If you hide the developer tools window for that tab, the console object remains exposed for each page you navigate to. If you open a new tab, you must also open the developer tools for that tab in order for the console object to be exposed.

The console object is not part of any standard and is an extension to the Document Object Model. Like other DOM objects, it is considered a host object and is not required to inherit from Object, nor its methods from Function, like native ECMAScript functions and objects do. This is the reason apply and call are undefined on those methods. In IE 9, most DOM objects were improved to inherit from native ECMAScript types. As the developer tools are considered an extension to IE (albeit, a built-in extension), they clearly didn't receive the same improvements as the rest of the DOM.

For what it's worth, you can still use some Function.prototype methods on console methods with a little bind() magic:

var log = Function.prototype.bind.call(console.log, console);
log.apply(console, ["this", "is", "a", "test"]);
//-> "thisisatest"

Insert default value when parameter is null

The questioner needs to learn the difference between an empty value provided and null.

Others have posted the right basic answer: A provided value, including a null, is something and therefore it's used. Default ONLY provides a value when none is provided. But the real problem here is lack of understanding of the value of null.

.

Access maven properties defined in the pom

Maven already has a solution to do what you want:

Get MavenProject from just the POM.xml - pom parser?

btw: first hit at google search ;)

Model model = null;
FileReader reader = null;
MavenXpp3Reader mavenreader = new MavenXpp3Reader();

try {
     reader = new FileReader(pomfile); // <-- pomfile is your pom.xml
     model = mavenreader.read(reader);
     model.setPomFile(pomfile);
}catch(Exception ex){
     // do something better here
     ex.printStackTrace()
}

MavenProject project = new MavenProject(model);
project.getProperties() // <-- thats what you need

Parse XML using JavaScript

The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.

var parseXml;
if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    throw new Error("No XML parser found");
}

Example usage:

var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);

Which I got from https://stackoverflow.com/a/8412989/1232175.

How to use a WSDL

Use WSDL.EXE utility to generate a Web Service proxy from WSDL.

You'll get a long C# source file that contains a class that looks like this:

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="MyService", Namespace="http://myservice.com/myservice")]
public partial class MyService : System.Web.Services.Protocols.SoapHttpClientProtocol {
    ...
}

In your client-side, Web-service-consuming code:

  1. instantiate MyService.
  2. set its Url property
  3. invoke Web methods

What is a software framework?

A lot of good answers already, but let me see if I can give you another viewpoint.

Simplifying things by quite a bit, you can view a framework as an application that is complete except for the actual functionality. You plug in the functionality and PRESTO! you have an application.

Consider, say, a GUI framework. The framework contains everything you need to make an application. Indeed you can often trivially make a minimal application with very few lines of source that does absolutely nothing -- but it does give you window management, sub-window management, menus, button bars, etc. That's the framework side of things. By adding your application functionality and "plugging it in" to the right places in the framework you turn this empty app that does nothing more than window management, etc. into a real, full-blown application.

There are similar types of frameworks for web apps, for server-side apps, etc. In each case the framework provides the bulk of the tedious, repetitive code (hopefully) while you provide the actual problem domain functionality. (This is the ideal. In reality, of course, the success of the framework is highly variable.)

I stress again that this is the simplified view of what a framework is. I'm not using scary terms like "Inversion of Control" and the like although most frameworks have such scary concepts built-in. Since you're a beginner, I thought I'd spare you the jargon and go with an easy simile.

Change value of input and submit form in JavaScript

You can use the onchange event:

<form name="myform" id="myform" action="action.php">
    <input type="hidden" name="myinput" value="0" onchange="this.form.submit()"/>
    <input type="text" name="message" value="" />
    <input type="submit" name="submit" onclick="DoSubmit()" />
</form>

Javascript dynamic array of strings

What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time.

Ok, so you need some user input first? There's a couple of methods of how to do that.

  1. First is the prompt() function which displays a popup asking the user for some input.
    • Pros: easy. Cons: ugly, can't go back to edit easily.
  2. Second is using html <input type="text"> fields.
    • Pros: can be styled, user can easily review and edit. Cons: a bit more coding needed.

For the prompt method, collecting your strings is a doddle:

var input = []; // initialise an empty array
var temp = '';
do {
    temp = prompt("Enter a number. Press cancel or leave empty to finish.");
    if (temp === "" || temp === null) {
        break;
    } else {
        input.push(temp);  // the array will dynamically grow
    }
} while (1);

(Yeah it's not the prettiest loop, but it's late and I'm tired....)

The other method requires a bit more effort.

  1. Put a single input field on the page.
  2. Add an onfocus handler to it.
    1. Check if there is another input element after this one, and if there is, check if it's empty.
      • If there is, don't do anything.
      • Otherwise, create a new input, put it after this one and apply the same handler to the new input.
  3. When the user clicks OK, loop through all the <input>s on the page and store them into an array.

eg:

// if you put your dynamic text fields in a container it'll be easier to get them
var inputs = document.getElementById('inputArea').getElementsByTagName('input');
var input = [];
for (var i = 0, l = inputs.length; i < l; ++i) {
    if (inputs[i].value.length) {
        input.push(inputs[i].value);
    }
}

After that, regardless of your method of collecting the input, you can print the numbers back on screen in a number of ways. A simple way would be like this:

var div = document.createElement('div');
for (var i = 0, l = input.length; i < l; ++i) {
    div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);

I've put this together so you can see it work at jsbin
Prompt method: http://jsbin.com/amefu
Inputs method: http://jsbin.com/iyoge

How to get a enum value from string in C#?

Using Enum.TryParse you don't need the Exception handling:

baseKey e;

if ( Enum.TryParse(s, out e) )
{
 ...
}

How is a CSS "display: table-column" supposed to work?

The CSS table model is based on the HTML table model http://www.w3.org/TR/CSS21/tables.html

A table is divided into ROWS, and each row contains one or more cells. Cells are children of ROWS, they are NEVER children of columns.

"display: table-column" does NOT provide a mechanism for making columnar layouts (e.g. newspaper pages with multiple columns, where content can flow from one column to the next).

Rather, "table-column" ONLY sets attributes that apply to corresponding cells within the rows of a table. E.g. "The background color of the first cell in each row is green" can be described.

The table itself is always structured the same way it is in HTML.

In HTML (observe that "td"s are inside "tr"s, NOT inside "col"s):

<table ..>
  <col .. />
  <col .. />
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
</table>

Corresponding HTML using CSS table properties (Note that the "column" divs do not contain any contents -- the standard does not allow for contents directly in columns):

_x000D_
_x000D_
.mytable {_x000D_
  display: table;_x000D_
}_x000D_
.myrow {_x000D_
  display: table-row;_x000D_
}_x000D_
.mycell {_x000D_
  display: table-cell;_x000D_
}_x000D_
.column1 {_x000D_
  display: table-column;_x000D_
  background-color: green;_x000D_
}_x000D_
.column2 {_x000D_
  display: table-column;_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 1</div>_x000D_
    <div class="mycell">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 2</div>_x000D_
    <div class="mycell">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_



OPTIONAL: both "rows" and "columns" can be styled by assigning multiple classes to each row and cell as follows. This approach gives maximum flexibility in specifying various sets of cells, or individual cells, to be styled:

_x000D_
_x000D_
//Useful css declarations, depending on what you want to affect, include:_x000D_
_x000D_
/* all cells (that have "class=mycell") */_x000D_
.mycell {_x000D_
}_x000D_
_x000D_
/* class row1, wherever it is used */_x000D_
.row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 (if you've put "class=mycell" on each cell) */_x000D_
.row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 */_x000D_
.row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows */_x000D_
.cell1 {_x000D_
}_x000D_
_x000D_
/* row1 inside class mytable (so can have different tables with different styles) */_x000D_
.mytable .row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 of a mytable */_x000D_
.mytable .row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 of a mytable */_x000D_
.mytable .row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows of a mytable */_x000D_
.mytable .cell1 {_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow row1">_x000D_
    <div class="mycell cell1">contents of first cell in row 1</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow row2">_x000D_
    <div class="mycell cell1">contents of first cell in row 2</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In today's flexible designs, which use <div> for multiple purposes, it is wise to put some class on each div, to help refer to it. Here, what used to be <tr> in HTML became class myrow, and <td> became class mycell. This convention is what makes the above CSS selectors useful.

PERFORMANCE NOTE: putting class names on each cell, and using the above multi-class selectors, is better performance than using selectors ending with *, such as .row1 * or even .row1 > *. The reason is that selectors are matched last first, so when matching elements are being sought, .row1 * first does *, which matches all elements, and then checks all the ancestors of each element, to find if any ancestor has class row1. This might be slow in a complex document on a slow device. .row1 > * is better, because only the immediate parent is examined. But it is much better still to immediately eliminate most elements, via .row1 .cell1. (.row1 > .cell1 is an even tighter spec, but it is the first step of the search that makes the biggest difference, so it usually isn't worth the clutter, and the extra thought process as to whether it will always be a direct child, of adding the child selector >.)

The key point to take away re performance is that the last item in a selector should be as specific as possible, and should never be *.

Git Push Error: insufficient permission for adding an object to repository database

For my case none of the suggestions worked. I'm on Windows and this worked for me:

  • Copy the remote repo into another folder
  • Share the folder and give appropriate permissions.
  • Make sure you can access the folder from your local machine.
  • Add this repo as another remote repo in your local repo. (git remote add foo //SERVERNAME/path/to/copied/git)
  • Push to foo. git push foo master. Did it worked? Great! Now delete not-working repo and rename this into whatever it was before. Make sure permissions and share property remains the same.

What is the best way to extract the first word from a string in Java?

You should be doing this

String input = "hello world, this is a line of text";

int i = input.indexOf(' ');
String word = input.substring(0, i);
String rest = input.substring(i);

The above is the fastest way of doing this task.

How do I write JSON data to a file?

if you are trying to write a pandas dataframe into a file using a json format i'd recommend this

destination='filepath'
saveFile = open(destination, 'w')
saveFile.write(df.to_json())
saveFile.close()

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

Highlight the difference between two strings in PHP

There is also a PECL extension for xdiff:

In particular:

Example from PHP Manual:

<?php
$old_article = file_get_contents('./old_article.txt');
$new_article = $_POST['article'];

$diff = xdiff_string_diff($old_article, $new_article, 1);
if (is_string($diff)) {
    echo "Differences between two articles:\n";
    echo $diff;
}

Simple parse JSON from URL on Android and display in listview

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

public class GetJsonFromUrl {
    String url = null;

    public GetJsonFromUrl(String url) {
        this.url = url;
    }

    public String GetJsonData() {
        try {
            URL Url = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) Url.openConnection();
            InputStream is = connection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            line = sb.toString();
            connection.disconnect();
            is.close();
            sb.delete(0, sb.length());
            return line;
        } catch (Exception e) {
            return null;
        }
    }
} 

and this class use for post data

import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

/**
 * Created by user on 11/2/16.
 */
public class sendDataToServer {
   public String postdata(String requestURL,HashMap<String,String> postDataParams){
        try {
            String response = "";
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            String line;
            BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line=br.readLine()) != null) {
                response+=line;
            }
            Log.d("test", response);
            return response;
        }catch (Exception e){
            return e.toString();
        }
    }

    public String postjson(String url,String json){
        try {

            URL obj = new URL(url);
            HttpURLConnection con= (HttpURLConnection) obj.openConnection();

            //add reuqest header
            con.setRequestMethod("POST");
            con.setRequestProperty("Accept", "application/json");
            String urlParameters = ""+json;

            // Send post request
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setRequestProperty("Content-Type", "application/json");
            OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
            wr.write(urlParameters);
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post parameters : " + urlParameters);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            //print result
            System.out.println(response.toString());
            return response.toString();
        }catch(Exception e){

            return e.toString();
        }
    }

    private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
        }
        return result.toString();
    }

   /* public String postdata(String url) {
    }*/
}

Start index for iterating Python list

islice has the advantage that it doesn't need to copy part of the list

from itertools import islice
for day in islice(days, 1, None):
    ...

How can I check if an element exists in the visible DOM?

Use querySelectorAll with forEach,

document.querySelectorAll('.my-element').forEach((element) => {
  element.classList.add('new-class');
});

as the opposite of:

const myElement = document.querySelector('.my-element');
if (myElement) {
  element.classList.add('new-class');
}

Angular JS POST request not sending JSON data

you can use your method by this way

var app = 'AirFare';
var d1 = new Date();
var d2 = new Date();

$http({
    url: '/api/apiControllerName/methodName',
    method: 'POST',
    params: {application:app, from:d1, to:d2},
    headers: { 'Content-Type': 'application/json;charset=utf-8' },
    //timeout: 1,
    //cache: false,
    //transformRequest: false,
    //transformResponse: false
}).then(function (results) {
    return results;
}).catch(function (e) {

});

cURL equivalent in Node.js?

EDIT:

For new projects please refrain from using request, since now the project is in maitainance mode, and will eventually be deprecated

https://github.com/request/request/issues/3142

Instead i would recommend Axios, the library is in line with Node latest standards, and there are some available plugins to enhance it, enabling mock server responses, automatic retries and other features.

https://github.com/axios/axios

const axios = require('axios');

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

Or using async / await:

try{
    const response = await axios.get('/user?ID=12345');
    console.log(response)
} catch(axiosErr){
    console.log(axiosErr)
}

I usually use REQUEST, its a simplified but powerful HTTP client for Node.js

https://github.com/request/request

Its on NPM npm install request

Here is a usage sample:

var request = require('request');

request('http://www.google.com', function (error, response, body) {
   if (!error && response.statusCode == 200) {
       console.log(body) // Show the HTML for the Google homepage.
   }
})

Import data.sql MySQL Docker Container

you can copy the export file for e.g dump.sql using docker cp into the container and then import the db. if you need full instructions, let me know and I will provide

How do I create a new branch?

Branches in SVN are essentially directories; you don't name the branch so much as choose the name of the directory to branch into.

The common way of 'naming' a branch is to place it under a directory called branches in your repository. In the "To URL:" portion of TortoiseSVN's Branch dialog, you would therefore enter something like:

(svn/http)://path-to-repo/branches/your-branch-name

The main branch of a project is referred to as the trunk, and is usually located in:

(svn/http)://path-to-repo/trunk

Add shadow to custom shape on Android

I would suggest a small improvement to Bruce's solution which is to prevent overdrawing the same shape on top of each other and to simply use stroke instead of solid. It would look like this:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- Drop Shadow Stack -->
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <stroke android:color="#02000000" android:width="1dp"  />
            <corners android:radius="8dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <stroke android:color="#05000000" android:width="1dp" />
            <corners android:radius="7dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <stroke android:color="#10000000" android:width="1dp" />
            <corners android:radius="6dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <stroke android:color="#15000000" android:width="1dp" />
            <corners android:radius="5dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <stroke android:color="#20000000" android:width="1dp" />
            <corners android:radius="4dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <stroke android:color="#25000000" android:width="1dp" />
            <corners android:radius="3dp" />
        </shape>
    </item>
    <item>
        <shape>
            <padding android:top="1dp" android:right="1dp" android:bottom="1dp" android:left="1dp" />
            <stroke android:color="#30000000" android:width="1dp" />
            <corners android:radius="3dp" />
        </shape>
    </item>

    <!-- Background -->
    <item>
        <shape>
            <solid android:color="#FFF" />
            <corners android:radius="3dp" />
        </shape>
    </item>
</layer-list>

screenshot of the rendering of the shadow Lastly I wanted to point out for people who would like a shadow in a specific direction that all you have to do is set the top, bottom, left or right to 0dp (for a solid line) or -1dp (for nothing)

How to copy directories with spaces in the name

When you specify the last Directory on the path remove the last .

for example "\server\directory with space\directory with space".

that should do it.

change directory in batch file using variable

simple way to do this... here are the example

cd program files
cd poweriso
piso mount D:\<Filename.iso> <Virtual Drive>
Pause

this will mount the ISO image to the specific drive...use

How to print like printf in Python3?

Simple printf() function from O'Reilly's Python Cookbook.

import sys
def printf(format, *args):
    sys.stdout.write(format % args)

Example output:

i = 7
pi = 3.14159265359
printf("hi there, i=%d, pi=%.2f\n", i, pi)
# hi there, i=7, pi=3.14

GZIPInputStream reading line by line

The basic setup of decorators is like this:

InputStream fileStream = new FileInputStream(filename);
InputStream gzipStream = new GZIPInputStream(fileStream);
Reader decoder = new InputStreamReader(gzipStream, encoding);
BufferedReader buffered = new BufferedReader(decoder);

The key issue in this snippet is the value of encoding. This is the character encoding of the text in the file. Is it "US-ASCII", "UTF-8", "SHIFT-JIS", "ISO-8859-9", …? there are hundreds of possibilities, and the correct choice usually cannot be determined from the file itself. It must be specified through some out-of-band channel.

For example, maybe it's the platform default. In a networked environment, however, this is extremely fragile. The machine that wrote the file might sit in the neighboring cubicle, but have a different default file encoding.

Most network protocols use a header or other metadata to explicitly note the character encoding.

In this case, it appears from the file extension that the content is XML. XML includes the "encoding" attribute in the XML declaration for this purpose. Furthermore, XML should really be processed with an XML parser, not as text. Reading XML line-by-line seems like a fragile, special case.

Failing to explicitly specify the encoding is against the second commandment. Use the default encoding at your peril!

Save the console.log in Chrome to a file

I have found a great and easy way for this.

  1. In the console - right click on the console logged object

  2. Click on 'Store as global variable'

  3. See the name of the new variable - e.g. it is variableName1

  4. Type in the console: JSON.stringify(variableName1)

  5. Copy the variable string content: e.g. {"a":1,"b":2,"c":3}

enter image description here

  1. Go to some JSON online editor: e.g. https://jsoneditoronline.org/

enter image description here

Protect .NET code from reverse engineering?

If you want people to able to run your code (and if you don't, then why did you write it in the first place?), then their CPU needs to be able to execute your code. In order to be able to execute the code, the CPU needs to be able to understand it.

Since CPUs are dumb, and humans aren't, this means that humans can understand the code as well.

There's only one way to make sure that your users don't get your code: don't give them your code.

This can be achieved two ways: Software as a service (SaaS), that is, you run your software on your server and only let your users access it remotely. This is the model that Stack Overflow uses, for example. I'm pretty sure that Stack Overflow doesn't obfuscate their code, yet you can't decompile it.

The other way is the appliance model: instead of giving your users your code, you give them a computer containing the code. This is the model that gaming consoles, most mobile phones and TiVo use. Note that this only works if you "own" the entire execution path: you need to build your own CPU, your own computer, write your own operating system and your own CLI implementation. Then, and only then can you protect your code. (But note that even the tiniest mistake will render all of your protections useless. Microsoft, Apple, Sony, the music industry and the movie industry can attest to that.)

Or, you could just do nothing, which means that your code will be automatically protected by copyright law.

Python List & for-each access (Find/Replace in built-in list)

Answering this has been good, as the comments have led to an improvement in my own understanding of Python variables.

As noted in the comments, when you loop over a list with something like for member in my_list the member variable is bound to each successive list element. However, re-assigning that variable within the loop doesn't directly affect the list itself. For example, this code won't change the list:

my_list = [1,2,3]
for member in my_list:
    member = 42
print my_list

Output:

[1, 2, 3]

If you want to change a list containing immutable types, you need to do something like:

my_list = [1,2,3]
for ndx, member in enumerate(my_list):
    my_list[ndx] += 42
print my_list

Output:

[43, 44, 45]

If your list contains mutable objects, you can modify the current member object directly:

class C:
    def __init__(self, n):
        self.num = n
    def __repr__(self):
        return str(self.num)

my_list = [C(i) for i in xrange(3)]
for member in my_list:
    member.num += 42
print my_list

[42, 43, 44]

Note that you are still not changing the list, simply modifying the objects in the list.

You might benefit from reading Naming and Binding.

How to check the gradle version in Android Studio?

File->Project Structure->Project pane->"Android plugin version".

Make sure you don't confuse the Gradle version with the Android plugin version. The former is the build system itself, the latter is the plugin to the build system that knows how to build Android projects

Convert bytes to a string

In Python 3, the default encoding is "utf-8", so you can directly use:

b'hello'.decode()

which is equivalent to

b'hello'.decode(encoding="utf-8")

On the other hand, in Python 2, encoding defaults to the default string encoding. Thus, you should use:

b'hello'.decode(encoding)

where encoding is the encoding you want.

Note: support for keyword arguments was added in Python 2.7.

How to position the form in the center screen?

Try using this:

this.setBounds(x,y,w,h);

How do I delete specific characters from a particular String in Java?

Note that the word boundaries also depend on the Locale. I think the best way to do it using standard java.text.BreakIterator. Here is an example from the java.sun.com tutorial.

import java.text.BreakIterator;
import java.util.Locale;

public static void main(String[] args) {
    String text = "\n" +
            "\n" +
            "For example I'm extracting a text String from a text file and I need those words to form an array. However, when I do all that some words end with comma (,) or a full stop (.) or even have brackets attached to them (which is all perfectly normal).\n" +
            "\n" +
            "What I want to do is to get rid of those characters. I've been trying to do that using those predefined String methods in Java but I just can't get around it.\n" +
            "\n" +
            "Every help appreciated. Thanx";
    BreakIterator wordIterator = BreakIterator.getWordInstance(Locale.getDefault());
    extractWords(text, wordIterator);
}

static void extractWords(String target, BreakIterator wordIterator) {
    wordIterator.setText(target);
    int start = wordIterator.first();
    int end = wordIterator.next();

    while (end != BreakIterator.DONE) {
        String word = target.substring(start, end);
        if (Character.isLetterOrDigit(word.charAt(0))) {
            System.out.println(word);
        }
        start = end;
        end = wordIterator.next();
    }
}

Source: http://java.sun.com/docs/books/tutorial/i18n/text/word.html

Cannot connect to Database server (mysql workbench)

Run the ALTER USER command. Be sure to change password to a strong password of your choosing.

  1. sudo mysql # Login to mysql`

  2. Run the below command

    ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
    

Now you can access it by using the new password.

Ref : https://www.digitalocean.com/community/tutorials/how-to-install-mysql-on-ubuntu-18-04

highlight the navigation menu for the current page

I usually use a class to achieve this. It's very simple to implement to anything, navigation links, hyperlinks and etc.

In your CSS document insert:

.current,
nav li a:hover {
   /* styles go here */
   color: #e00122;
   background-color: #fffff;
}

This will make the hover state of the list items have red text and a white background. Attach that class of current to any link on the "current" page and it will display the same styles.

Im your HTML insert:

<nav>
   <ul>
      <li class="current"><a href="#">Nav Item 1</a></li>
      <li><a href="#">Nav Item 2</a></li>
      <li><a href="#">Nav Item 3</a></li>
   </ul>
</nav>

How to install a certificate in Xcode (preparing for app store submission)

In Xcode 5 this has been moved to:

Xcode>Preferences>Accounts>View Details button>

Reordering Chart Data Series

These are the buttons UP/DOWN

enter image description here

What is the python "with" statement designed for?

In python generally “with” statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. “with” statement makes the exception handling simpler by providing cleanup activities.

General form of with:

with open(“file name”, “mode”) as file-var:
    processing statements

note: no need to close the file by calling close() upon file-var.close()

How to pass a list from Python, by Jinja2 to JavaScript

I had a similar problem using Flask, but I did not have to resort to JSON. I just passed a list letters = ['a','b','c'] with render_template('show_entries.html', letters=letters), and set

var letters = {{ letters|safe }}

in my javascript code. Jinja2 replaced {{ letters }} with ['a','b','c'], which javascript interpreted as an array of strings.

DateTime.MinValue and SqlDateTime overflow

Here is what you can do. Though there are lot many ways to achieve it.

DateTime? d = null;    
if (txtBirthDate.Text == string.Empty)
    objinfo.BirthDate = d;
else
    objinfo.BirthDate =  DateTime.Parse(txtBirthDate.Text);

Note: This will work only if your database datetime column is Allow Null. Else you can define a standard minimum value for DateTime d.

svn cleanup: sqlite: database disk image is malformed

If you install the Tortoise SVN, Please go to task manager and stop it. Then try to delete the folder. it will work

Difference between 2 dates in SQLite

Both answers provide solutions a bit more complex, as they need to be. Say the payment was created on January 6, 2013. And we want to know the difference between this date and today.

sqlite> SELECT julianday() - julianday('2013-01-06');
34.7978485878557 

The difference is 34 days. We can use julianday('now') for better clarity. In other words, we do not need to put date() or datetime() functions as parameters to julianday() function.

Is there a method to generate a UUID with go language

u[8] = (u[8] | 0x80) & 0xBF // what's the purpose ?
u[6] = (u[6] | 0x40) & 0x4F // what's the purpose ?

These lines clamp the values of byte 6 and 8 to a specific range. rand.Read returns random bytes in the range 0-255, which are not all valid values for a UUID. As far as I can tell, this should be done for all the values in the slice though.

If you are on linux, you can alternatively call /usr/bin/uuidgen.

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    out, err := exec.Command("uuidgen").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%s", out)
}

Which yields:

$ go run uuid.go 
dc9076e9-2fda-4019-bd2c-900a8284b9c4

How to have a default option in Angular.js select box

If you want to make sure your $scope.somethingHere value doesn't get overwritten when your view initializes, you'll want to coalesce (somethingHere = somethingHere || options[0].value) the value in your ng-init like so:

<select ng-model="somethingHere" 
        ng-init="somethingHere = somethingHere || options[0].value"
        ng-options="option.value as option.name for option in options">
</select>

doGet and doPost in Servlets

Could it be that you are passing the data through get, not post?

<form method="get" ..>
..
</form>

java.lang.IllegalAccessError: tried to access method

From Android perspective: Method not available in api version

I was getting this Issue primarily because i was using some thing that is not available/deprecated in that Android version

Wrong way:

Notification.Builder nBuilder = new Notification.Builder(mContext);
nBuilder.addAction(new Notification.Action(android.R.drawable.ic_menu_view,"PAUSE",pendingIntent));

Right way:

Notification.Builder nBuilder = new Notification.Builder(mContext);
nBuilder.addAction(android.R.drawable.ic_media_pause,"PAUSE",pendingIntent);

here Notification.Action is not available prior to API 20 and my min version was API 16

How do I read / convert an InputStream into a String in Java?

Guava provides much shorter efficient autoclosing solution in case when input stream comes from classpath resource (which seems to be popular task):

byte[] bytes = Resources.toByteArray(classLoader.getResource(path));

or

String text = Resources.toString(classLoader.getResource(path), StandardCharsets.UTF_8);

There is also general concept of ByteSource and CharSource that gently take care of both opening and closing the stream.

So, for example, instead of explicitly opening a small file to read its contents:

String content = Files.asCharSource(new File("robots.txt"), StandardCharsets.UTF_8).read();
byte[] data = Files.asByteSource(new File("favicon.ico")).read();

or just

String content = Files.toString(new File("robots.txt"), StandardCharsets.UTF_8);
byte[] data = Files.toByteArray(new File("favicon.ico"));

How can I get just the first row in a result set AFTER ordering?

You can nest your queries:

select * from (
    select bla
    from bla
    where bla
    order by finaldate desc
)
where rownum < 2

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

I think this represents a good answer.

APK Signature Scheme v2 verification

  1. Locate the APK Signing Block and verify that:
    1. Two size fields of APK Signing Block contain the same value.
    2. ZIP Central Directory is immediately followed by ZIP End of Central Directory record.
    3. ZIP End of Central Directory is not followed by more data.
  2. Locate the first APK Signature Scheme v2 Block inside the APK Signing Block. If the v2 Block if present, proceed to step 3. Otherwise, fall back to verifying the APK using v1 scheme.
  3. For each signer in the APK Signature Scheme v2 Block:
    1. Choose the strongest supported signature algorithm ID from signatures. The strength ordering is up to each implementation/platform version.
    2. Verify the corresponding signature from signatures against signed data using public key. (It is now safe to parse signed data.)
    3. Verify that the ordered list of signature algorithm IDs in digests and signatures is identical. (This is to prevent signature stripping/addition.)
    4. Compute the digest of APK contents using the same digest algorithm as the digest algorithm used by the signature algorithm.
    5. Verify that the computed digest is identical to the corresponding digest from digests.
    6. Verify that SubjectPublicKeyInfo of the first certificate of certificates is identical to public key.
  4. Verification succeeds if at least one signer was found and step 3 succeeded for each found signer.

Note: APK must not be verified using the v1 scheme if a failure occurs in step 3 or 4.

JAR-signed APK verification (v1 scheme)

The JAR-signed APK is a standard signed JAR, which must contain exactly the entries listed in META-INF/MANIFEST.MF and where all entries must be signed by the same set of signers. Its integrity is verified as follows:

  1. Each signer is represented by a META-INF/<signer>.SF and META-INF/<signer>.(RSA|DSA|EC) JAR entry.
  2. <signer>.(RSA|DSA|EC) is a PKCS #7 CMS ContentInfo with SignedData structure whose signature is verified over the <signer>.SF file.
  3. <signer>.SF file contains a whole-file digest of the META-INF/MANIFEST.MF and digests of each section of META-INF/MANIFEST.MF. The whole-file digest of the MANIFEST.MF is verified. If that fails, the digest of each MANIFEST.MF section is verified instead.
  4. META-INF/MANIFEST.MF contains, for each integrity-protected JAR entry, a correspondingly named section containing the digest of the entry’s uncompressed contents. All these digests are verified.
  5. APK verification fails if the APK contains JAR entries which are not listed in the MANIFEST.MF and are not part of JAR signature. The protection chain is thus <signer>.(RSA|DSA|EC) ? <signer>.SF ? MANIFEST.MF ? contents of each integrity-protected JAR entry.

@import vs #import - iOS 7

There is a few benefits of using modules. You can use it only with Apple's framework unless module map is created. @import is a bit similar to pre-compiling headers files when added to .pch file which is a way to tune app the compilation process. Additionally you do not have to add libraries in the old way, using @import is much faster and efficient in fact. If you still look for a nice reference I will highly recommend you reading this article.

Error: Tablespace for table xxx exists. Please DISCARD the tablespace before IMPORT

If you get the .idb recreated again after you delete it, then read this answer.

This how it worked with me. I had the .idb file without it's corresponding .frm and whenever I delete the .idb file, the database recreate it again. and I found the solution in one line in MySQL documentation (Tablespace Does Not Exist part)

1- Create a matching .frm file in some other database directory and copy it to the database directory where the orphan table is located.

2- Issue DROP TABLE for the original table. That should successfully drop the table and InnoDB should print a warning to the error log that the .ibd file was missing.

I copied another table .frm file and name it like my missing table, then make a normal drop table query and voila, it worked and the table is dropped normally!

my system is XAMPP on windows MariaDB v 10.1.8

Go to particular revision

I was in a situation where we have a master branch, and then another branch called 17.0 and inside this 17.0 there was a commit hash no say "XYZ". And customer is given a build till that XYZ revision. Now we came across a bug and that needs to be solved for that customer. So we need to create separate branch for that customer till that "xyz" hash. So here is how I did it.

First I created a folder with that customer name on my local machine. Say customer name is "AAA" once that folder is created issue following command inside this folder:

  1. git init
  2. git clone After this command you will be on master branch. So switch to desired branch
  3. git checkout 17.0 This will bring you to the branch where your commit is present
  4. git checkout This will take your repository till that hash commit. See the name of ur branch it got changed to that commit hash no. Now give a branch name to this hash
  5. git branch ABC This will create a new branch on your local machine.
  6. git checkout ABC
  7. git push origin ABC This will push this branch to remote repository and create a branch on git server. You are done.

How to draw a filled triangle in android canvas?

you can also use vertice :

private static final int verticesColors[] = {
    Color.LTGRAY, Color.LTGRAY, Color.LTGRAY, 0xFF000000, 0xFF000000, 0xFF000000
};
float verts[] = {
    point1.x, point1.y, point2.x, point2.y, point3.x, point3.y
};
canvas.drawVertices(Canvas.VertexMode.TRIANGLES, verts.length, verts, 0, null, 0, verticesColors,   0, null, 0, 0, new Paint());

git rebase fatal: Needed a single revision

I ran into this and realized I didn't fetch the upstream before trying to rebase. All I needed was to git fetch upstream

How to add a line break in an Android TextView?

If you're using XML to declare your TextView use android:singleLine = "false" or in Java, use txtSubTitle.setSingleLine(false);

c# replace \" characters

Replace(@"\""", "")

You have to use double-doublequotes to escape double-quotes within a verbatim string.

How to use a filter in a controller?

First of all inject $filter to your controller, making sure ngSanitize is loaded within your app, later within the controller usage is as follows:

$filter('linky')(text, target, attributes)

Always check out the angularjs docs

How to configure Docker port mapping to use Nginx as an upstream proxy?

I tried using the popular Jason Wilder reverse proxy that code-magically works for everyone, and learned that it doesn't work for everyone (ie: me). And I'm brand new to NGINX, and didn't like that I didn't understand the technologies I was trying to use.

Wanted to add my 2 cents, because the discussion above around linking containers together is now dated since it is a deprecated feature. So here's an explanation on how to do it using networks. This answer is a full example of setting up nginx as a reverse proxy to a statically paged website using Docker Compose and nginx configuration.

TL;DR;

Add the services that need to talk to each other onto a predefined network. For a step-by-step discussion on Docker networks, I learned some things here: https://technologyconversations.com/2016/04/25/docker-networking-and-dns-the-good-the-bad-and-the-ugly/

Define the Network

First of all, we need a network upon which all your backend services can talk on. I called mine web but it can be whatever you want.

docker network create web

Build the App

We'll just do a simple website app. The website is a simple index.html page being served by an nginx container. The content is a mounted volume to the host under a folder content

DockerFile:

FROM nginx
COPY default.conf /etc/nginx/conf.d/default.conf

default.conf

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /var/www/html;
        index  index.html index.htm;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

docker-compose.yml

version: "2"

networks:
  mynetwork:
    external:
      name: web

services:
  nginx:
    container_name: sample-site
    build: .
    expose:
      - "80"
    volumes:
      - "./content/:/var/www/html/"
    networks:
      default: {}
      mynetwork:
        aliases:
          - sample-site

Note that we no longer need port mapping here. We simple expose port 80. This is handy for avoiding port collisions.

Run the App

Fire this website up with

docker-compose up -d

Some fun checks regarding the dns mappings for your container:

docker exec -it sample-site bash
ping sample-site

This ping should work, inside your container.

Build the Proxy

Nginx Reverse Proxy:

Dockerfile

FROM nginx

RUN rm /etc/nginx/conf.d/*

We reset all the virtual host config, since we're going to customize it.

docker-compose.yml

version: "2"

networks:
  mynetwork:
    external:
      name: web


services:
  nginx:
    container_name: nginx-proxy
    build: .
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./conf.d/:/etc/nginx/conf.d/:ro
      - ./sites/:/var/www/
    networks:
      default: {}
      mynetwork:
        aliases:
          - nginx-proxy

Run the Proxy

Fire up the proxy using our trusty

docker-compose up -d

Assuming no issues, then you have two containers running that can talk to each other using their names. Let's test it.

docker exec -it nginx-proxy bash
ping sample-site
ping nginx-proxy

Set up Virtual Host

Last detail is to set up the virtual hosting file so the proxy can direct traffic based on however you want to set up your matching:

sample-site.conf for our virtual hosting config:

  server {
    listen 80;
    listen [::]:80;

    server_name my.domain.com;

    location / {
      proxy_pass http://sample-site;
    }

  }

Based on how the proxy was set up, you'll need this file stored under your local conf.d folder which we mounted via the volumes declaration in the docker-compose file.

Last but not least, tell nginx to reload it's config.

docker exec nginx-proxy service nginx reload

These sequence of steps is the culmination of hours of pounding head-aches as I struggled with the ever painful 502 Bad Gateway error, and learning nginx for the first time, since most of my experience was with Apache.

This answer is to demonstrate how to kill the 502 Bad Gateway error that results from containers not being able to talk to one another.

I hope this answer saves someone out there hours of pain, since getting containers to talk to each other was really hard to figure out for some reason, despite it being what I expected to be an obvious use-case. But then again, me dumb. And please let me know how I can improve this approach.

In WPF, what are the differences between the x:Name and Name attributes?

There really is only one name in XAML, the x:Name. A framework, such as WPF, can optionally map one of its properties to XAML's x:Name by using the RuntimeNamePropertyAttribute on the class that designates one of the classes properties as mapping to the x:Name attribute of XAML.

The reason this was done was to allow for frameworks that already have a concept of "Name" at runtime, such as WPF. In WPF, for example, FrameworkElement introduces a Name property.

In general, a class does not need to store the name for x:Name to be useable. All x:Name means to XAML is generate a field to store the value in the code behind class. What the runtime does with that mapping is framework dependent.

So, why are there two ways to do the same thing? The simple answer is because there are two concepts mapped onto one property. WPF wants the name of an element preserved at runtime (which is usable through Bind, among other things) and XAML needs to know what elements you want to be accessible by fields in the code behind class. WPF ties these two together by marking the Name property as an alias of x:Name.

In the future, XAML will have more uses for x:Name, such as allowing you to set properties by referring to other objects by name, but in 3.5 and prior, it is only used to create fields.

Whether you should use one or the other is really a style question, not a technical one. I will leave that to others for a recommendation.

See also AutomationProperties.Name VS x:Name, AutomationProperties.Name is used by accessibility tools and some testing tools.

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

How can I get the current user's username in Bash?

The current user's username can be gotten in pure Bash with the ${parameter@operator} parameter expansion (introduced in Bash 4.4):

$ : \\u
$ printf '%s\n' "${_@P}"

The : built-in (synonym of true) is used instead of a temporary variable by setting the last argument, which is stored in $_. We then expand it (\u) as if it were a prompt string with the P operator.

This is better than using $USER, as $USER is just a regular environmental variable; it can be modified, unset, etc. Even if it isn't intentionally tampered with, a common case where it's still incorrect is when the user is switched without starting a login shell (su's default).

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

How to generate and auto increment Id with Entity Framework

This is a guess :)

Is it because the ID is a string? What happens if you change it to int?

I mean:

 public int Id { get; set; }

Jquery show/hide table rows

http://sandbox.phpcode.eu/g/corrected-b5fe953c76d4b82f7e63f1cef1bc506e.php

<span id="black_only">Show only black</span><br>
<span id="white_only">Show only white</span><br>
<span id="all">Show all of them</span>
<style>
.black{background-color:black;}
#white{background-color:white;}
</style>
<table class="someclass" border="0" cellpadding="0" cellspacing="0" summary="bla bla bla">
<caption>bla bla bla</caption>
<thead>
  <tr class="black">
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
  </tr>
</thead>
<tbody>
  <tr id="white">
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
</tr>
  <tr class="black" style="background-color:black;">
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
</tr>
</tbody>
<script>
$(function(){
   $("#black_only").click(function(){
    $("#white").hide();
    $(".black").show();

   });
   $("#white_only").click(function(){
    $(".black").hide();
    $("#white").show();

   });
   $("#all").click(function(){
    $("#white").show();
    $(".black").show();

   });

});
</script>

Check if value exists in dataTable?

You can use LINQ-to-DataSet with Enumerable.Any:

String author = "John Grisham";
bool contains = tbl.AsEnumerable().Any(row => author == row.Field<String>("Author"));

Another approach is to use DataTable.Select:

DataRow[] foundAuthors = tbl.Select("Author = '" + searchAuthor + "'");
if(foundAuthors.Length != 0)
{
    // do something...
}

Q: what if we do not know the columns Headers and we want to find if any cell value PEPSI exist in any rows'c columns? I can loop it all to find out but is there a better way? –

Yes, you can use this query:

DataColumn[] columns = tbl.Columns.Cast<DataColumn>().ToArray();
bool anyFieldContainsPepsi = tbl.AsEnumerable()
    .Any(row => columns.Any(col => row[col].ToString() == "PEPSI"));

What's the difference between Cache-Control: max-age=0 and no-cache?

I had this same question, and found some info in my searches (your question came up as one of the results). Here's what I determined...

There are two sides to the Cache-Control header. One side is where it can be sent by the web server (aka. "origin server"). The other side is where it can be sent by the browser (aka. "user agent").


When sent by the origin server

I believe max-age=0 simply tells caches (and user agents) the response is stale from the get-go and so they SHOULD revalidate the response (eg. with the If-Not-Modified header) before using a cached copy, whereas, no-cache tells them they MUST revalidate before using a cached copy. From 14.9.1 What is Cacheable:

no-cache

...a cache MUST NOT use the response to satisfy a subsequent request without successful revalidation with the origin server. This allows an origin server to prevent caching even by caches that have been configured to return stale responses to client requests.

In other words, caches may sometimes choose to use a stale response (although I believe they have to then add a Warning header), but no-cache says they're not allowed to use a stale response no matter what. Maybe you'd want the SHOULD-revalidate behavior when baseball stats are generated in a page, but you'd want the MUST-revalidate behavior when you've generated the response to an e-commerce purchase.

Although you're correct in your comment when you say no-cache is not supposed to prevent storage, it might actually be another difference when using no-cache. I came across a page, Cache Control Directives Demystified, that says (I can't vouch for its correctness):

In practice, IE and Firefox have started treating the no-cache directive as if it instructs the browser not to even cache the page. We started observing this behavior about a year ago. We suspect that this change was prompted by the widespread (and incorrect) use of this directive to prevent caching.

...

Notice that of late, "cache-control: no-cache" has also started behaving like the "no-store" directive.

As an aside, it appears to me that Cache-Control: max-age=0, must-revalidate should basically mean the same thing as Cache-Control: no-cache. So maybe that's a way to get the MUST-revalidate behavior of no-cache, while avoiding the apparent migration of no-cache to doing the same thing as no-store (ie. no caching whatsoever)?


When sent by the user agent

I believe shahkalpesh's answer applies to the user agent side. You can also look at 13.2.6 Disambiguating Multiple Responses.

If a user agent sends a request with Cache-Control: max-age=0 (aka. "end-to-end revalidation"), then each cache along the way will revalidate its cache entry (eg. with the If-Not-Modified header) all the way to the origin server. If the reply is then 304 (Not Modified), the cached entity can be used.

On the other hand, sending a request with Cache-Control: no-cache (aka. "end-to-end reload") doesn't revalidate and the server MUST NOT use a cached copy when responding.

Check if a key exists inside a json object

Try this,

if(thisSession.hasOwnProperty('merchant_id')){

}

the JS Object thisSession should be like

{
amt: "10.00",
email: "[email protected]",
merchant_id: "sam",
mobileNo: "9874563210",
orderID: "123456",
passkey: "1234"
}

you can find the details here

How do I get the path and name of the file that is currently executing?

It's not entirely clear what you mean by "the filepath of the file that is currently running within the process". sys.argv[0] usually contains the location of the script that was invoked by the Python interpreter. Check the sys documentation for more details.

As @Tim and @Pat Notz have pointed out, the __file__ attribute provides access to

the file from which the module was loaded, if it was loaded from a file

Format number to always show 2 decimal places

(num + "").replace(/^([0-9]*)(\.[0-9]{1,2})?.*$/,"$1$2")

Why use #define instead of a variable

#define can accomplish some jobs that normal C++ cannot, like guarding headers and other tasks. However, it definitely should not be used as a magic number- a static const should be used instead.

Redirect echo output in shell script to logfile

I tried to manage using the below command. This will write the output in log file as well as print on console.

#!/bin/bash

# Log Location on Server.
LOG_LOCATION=/home/user/scripts/logs
exec > >(tee -i $LOG_LOCATION/MylogFile.log)
exec 2>&1

echo "Log Location should be: [ $LOG_LOCATION ]"

Please note: This is bash code so if you run it using sh it will through syntax error

mat-form-field must contain a MatFormFieldControl

Unfortunately content projection into mat-form-field is not supported yet. Please track the following github issue to get the latest news about it.

By now the only solution for you is either place your content directly into mat-form-field component or implement a MatFormFieldControl class thus creating a custom form field component.

How to Create simple drag and Drop in angularjs

Modified from the angular-drag-and-drop-lists examples page

Markup

<div class="row">
    <div ng-repeat="(listName, list) in models.lists" class="col-md-6">
        <ul dnd-list="list">
            <li ng-repeat="item in list" 
                dnd-draggable="item" 
                dnd-moved="list.splice($index, 1)" 
                dnd-effect-allowed="move" 
                dnd-selected="models.selected = item" 
                ng-class="{'selected': models.selected === item}" 
                draggable="true">{{item.label}}</li>
        </ul>
    </div>
</div>

Angular

var app = angular.module('angular-starter', [
    'ui.router',
    'dndLists'
]);

app.controller('MainCtrl', function($scope){

    $scope.models = {
        selected: null,
        lists: {"A": [], "B": []}
    };

    // Generate initial model
    for (var i = 1; i <= 3; ++i) {
        $scope.models.lists.A.push({label: "Item A" + i});
        $scope.models.lists.B.push({label: "Item B" + i});
    }

    // Model to JSON for demo purpose
    $scope.$watch('models', function(model) {
        $scope.modelAsJson = angular.toJson(model, true);
    }, true);
});

Library can be installed via bower or npm: angular-drag-and-drop-lists

How to write and read a file with a HashMap?

HashMap implements Serializable so you can use normal serialization to write hashmap to file

Here is the link for Java - Serialization example

draw diagonal lines in div background with CSS

_x000D_
_x000D_
.borders {_x000D_
    width: 200px;_x000D_
    height: 100px;_x000D_
    background-color: black;_x000D_
    border-width: 40px;_x000D_
    border-style: solid;_x000D_
    border-color: red blue green yellow;_x000D_
}
_x000D_
<div class='borders'></div>
_x000D_
_x000D_
_x000D_

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

"java.lang.SecurityException: class" org.hamcrest.Matchers "'s signer information does not match signer information of other classes in the same package"

Do it: Right-click on your package click on Build Path -> Configure Build Path Click on the Libraries tab Remove JUnit Apply and close Ready.

Git merge with force overwrite

Not really related to this answer, but I'd ditch git pull, which just runs git fetch followed by git merge. You are doing three merges, which is going to make your Git run three fetch operations, when one fetch is all you will need. Hence:

git fetch origin   # update all our origin/* remote-tracking branches

git checkout demo         # if needed -- your example assumes you're on it
git merge origin/demo     # if needed -- see below

git checkout master
git merge origin/master

git merge -X theirs demo   # but see below

git push origin master     # again, see below

Controlling the trickiest merge

The most interesting part here is git merge -X theirs. As root545 noted, the -X options are passed on to the merge strategy, and both the default recursive strategy and the alternative resolve strategy take -X ours or -X theirs (one or the other, but not both). To understand what they do, though, you need to know how Git finds, and treats, merge conflicts.

A merge conflict can occur within some file1 when the base version differs from both the current (also called local, HEAD, or --ours) version and the other (also called remote or --theirs) version of that same file. That is, the merge has identified three revisions (three commits): base, ours, and theirs. The "base" version is from the merge base between our commit and their commit, as found in the commit graph (for much more on this, see other StackOverflow postings). Git has then found two sets of changes: "what we did" and "what they did". These changes are (in general) found on a line-by-line, purely textual basis. Git has no real understanding of file contents; it is merely comparing each line of text.

These changes are what you see in git diff output, and as always, they have context as well. It's possible that things we changed are on different lines from things they changed, so that the changes seem like they would not collide, but the context has also changed (e.g., due to our change being close to the top or bottom of the file, so that the file runs out in our version, but in theirs, they have also added more text at the top or bottom).

If the changes happen on different lines—for instance, we change color to colour on line 17 and they change fred to barney on line 71—then there is no conflict: Git simply takes both changes. If the changes happen on the same lines, but are identical changes, Git takes one copy of the change. Only if the changes are on the same lines, but are different changes, or that special case of interfering context, do you get a modify/modify conflict.

The -X ours and -X theirs options tell Git how to resolve this conflict, by picking just one of the two changes: ours, or theirs. Since you said you are merging demo (theirs) into master (ours) and want the changes from demo, you would want -X theirs.

Blindly applying -X, however, is dangerous. Just because our changes did not conflict on a line-by-line basis does not mean our changes do not actually conflict! One classic example occurs in languages with variable declarations. The base version might declare an unused variable:

int i;

In our version, we delete the unused variable to make a compiler warning go away—and in their version, they add a loop some lines later, using i as the loop counter. If we combine the two changes, the resulting code no longer compiles. The -X option is no help here since the changes are on different lines.

If you have an automated test suite, the most important thing to do is to run the tests after merging. You can do this after committing, and fix things up later if needed; or you can do it before committing, by adding --no-commit to the git merge command. We'll leave the details for all of this to other postings.


1You can also get conflicts with respect to "file-wide" operations, e.g., perhaps we fix the spelling of a word in a file (so that we have a change), and they delete the entire file (so that they have a delete). Git will not resolve these conflicts on its own, regardless of -X arguments.


Doing fewer merges and/or smarter merges and/or using rebase

There are three merges in both of our command sequences. The first is to bring origin/demo into the local demo (yours uses git pull which, if your Git is very old, will fail to update origin/demo but will produce the same end result). The second is to bring origin/master into master.

It's not clear to me who is updating demo and/or master. If you write your own code on your own demo branch, and others are writing code and pushing it to the demo branch on origin, then this first-step merge can have conflicts, or produce a real merge. More often than not, it's better to use rebase, rather than merge, to combine work (admittedly, this is a matter of taste and opinion). If so, you might want to use git rebase instead. On the other hand, if you never do any of your own commits on demo, you don't even need a demo branch. Alternatively, if you want to automate a lot of this, but be able to check carefully when there are commits that both you and others, made, you might want to use git merge --ff-only origin/demo: this will fast-forward your demo to match the updated origin/demo if possible, and simply outright fail if not (at which point you can inspect the two sets of changes, and choose a real merge or a rebase as appropriate).

This same logic applies to master, although you are doing the merge on master, so you definitely do need a master. It is, however, even likelier that you would want the merge to fail if it cannot be done as a fast-forward non-merge, so this probably also should be git merge --ff-only origin/master.

Let's say that you never do your own commits on demo. In this case we can ditch the name demo entirely:

git fetch origin   # update origin/*

git checkout master
git merge --ff-only origin/master || die "cannot fast-forward our master"

git merge -X theirs origin/demo || die "complex merge conflict"

git push origin master

If you are doing your own demo branch commits, this is not helpful; you might as well keep the existing merge (but maybe add --ff-only depending on what behavior you want), or switch it to doing a rebase. Note that all three methods may fail: merge may fail with a conflict, merge with --ff-only may not be able to fast-forward, and rebase may fail with a conflict (rebase works by, in essence, cherry-picking commits, which uses the merge machinery and hence can get a merge conflict).

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

import re
pattern = re.compile("<(\d{4,5})>")

for i, line in enumerate(open('test.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.group())

A couple of notes about the regex:

  • You don't need the ? at the end and the outer (...) if you don't want to match the number with the angle brackets, but only want the number itself
  • It matches either 4 or 5 digits between the angle brackets

Update: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.

More about regex in python can be found here : Regular Expression HOWTO

Angular directives - when and how to use compile, controller, pre-link and post-link

Post-link function

When the post-link function is called, all previous steps have taken place - binding, transclusion, etc.

This is typically a place to further manipulate the rendered DOM.

Do:

  • Manipulate DOM (rendered, and thus instantiated) elements.
  • Attach event handlers.
  • Inspect child elements.
  • Set up observations on attributes.
  • Set up watches on the scope.

How to define Singleton in TypeScript

Here is yet another way to do it with a more conventional javascript approach using an IFFE:

module App.Counter {
    export var Instance = (() => {
        var i = 0;
        return {
            increment: (): void => {
                i++;
            },
            getCount: (): number => {
                return i;
            }
        }
    })();
}

module App {
    export function countStuff() {
        App.Counter.Instance.increment();
        App.Counter.Instance.increment();
        alert(App.Counter.Instance.getCount());
    }
}

App.countStuff();

View a demo

putting a php variable in a HTML form value

You can do it like this,

<input type="text" name="name" value="<?php echo $name;?>" />

But seen as you've taken it straight from user input, you want to sanitize it first so that nothing nasty is put into the output of your page.

<input type="text" name="name" value="<?php echo htmlspecialchars($name);?>" />

Paritition array into N chunks with Numpy

Try numpy.array_split.

From the documentation:

>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
    [array([ 0.,  1.,  2.]), array([ 3.,  4.,  5.]), array([ 6.,  7.])]

Identical to numpy.split, but won't raise an exception if the groups aren't equal length.

If number of chunks > len(array) you get blank arrays nested inside, to address that - if your split array is saved in a, then you can remove empty arrays by:

[x for x in a if x.size > 0]

Just save that back in a if you wish.

Add multiple items to already initialized arraylist in java

If you are looking to avoid multiple code lines to save space, maybe this syntax could be useful:

        java.util.ArrayList lisFieldNames = new ArrayList() {
            {
                add("value1"); 
                add("value2");
            }
        };

Removing new lines, you can show it compressed as:

        java.util.ArrayList lisFieldNames = new ArrayList() {
            {
                add("value1"); add("value2"); (...);
            }
        };

How to center align the ActionBar title in Android?

Just a quick addition to Ahmad's answer. You can't use getSupportActionBar().setTitle anymore when using a custom view with a TextView. So to set the title when you have multiple Activities with this custom ActionBar (using this one xml), in your onCreate() method after you assign a custom view:

TextView textViewTitle = (TextView) findViewById(R.id.mytext);
textViewTitle.setText(R.string.title_for_this_activity);

Converting map to struct

  • the simplest way to do that is using encoding/json package

just for example:

package main
import (
    "fmt"
    "encoding/json"
)

type MyAddress struct {
    House string
    School string
}
type Student struct {
    Id int64
    Name string
    Scores float32
    Address MyAddress
    Labels []string
}

func Test() {

    dict := make(map[string]interface{})
    dict["id"] = 201902181425       // int
    dict["name"] = "jackytse"       // string
    dict["scores"] = 123.456        // float
    dict["address"] = map[string]string{"house":"my house", "school":"my school"}   // map
    dict["labels"] = []string{"aries", "warmhearted", "frank"}      // slice

    jsonbody, err := json.Marshal(dict)
    if err != nil {
        // do error check
        fmt.Println(err)
        return
    }

    student := Student{}
    if err := json.Unmarshal(jsonbody, &student); err != nil {
        // do error check
        fmt.Println(err)
        return
    }

    fmt.Printf("%#v\n", student)
}

func main() {
    Test()
}

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

What is the difference between require_relative and require in Ruby?

require_relative is a convenient subset of require

require_relative('path')

equals:

require(File.expand_path('path', File.dirname(__FILE__)))

if __FILE__ is defined, or it raises LoadError otherwise.

This implies that:

  • require_relative 'a' and require_relative './a' require relative to the current file (__FILE__).

    This is what you want to use when requiring inside your library, since you don't want the result to depend on the current directory of the caller.

  • eval('require_relative("a.rb")') raises LoadError because __FILE__ is not defined inside eval.

    This is why you can't use require_relative in RSpec tests, which get evaled.

The following operations are only possible with require:

  • require './a.rb' requires relative to the current directory

  • require 'a.rb' uses the search path ($LOAD_PATH) to require. It does not find files relative to current directory or path.

    This is not possible with require_relative because the docs say that path search only happens when "the filename does not resolve to an absolute path" (i.e. starts with / or ./ or ../), which is always the case for File.expand_path.

The following operation is possible with both, but you will want to use require as it is shorter and more efficient:

  • require '/a.rb' and require_relative '/a.rb' both require the absolute path.

Reading the source

When the docs are not clear, I recommend that you take a look at the sources (toggle source in the docs). In some cases, it helps to understand what is going on.

require:

VALUE rb_f_require(VALUE obj, VALUE fname) {
  return rb_require_safe(fname, rb_safe_level());
}

require_relative:

VALUE rb_f_require_relative(VALUE obj, VALUE fname) {
    VALUE base = rb_current_realfilepath();
    if (NIL_P(base)) {
        rb_loaderror("cannot infer basepath");
    }
    base = rb_file_dirname(base);
    return rb_require_safe(rb_file_absolute_path(fname, base), rb_safe_level());
}

This allows us to conclude that

require_relative('path')

is the same as:

require(File.expand_path('path', File.dirname(__FILE__)))

because:

rb_file_absolute_path   =~ File.expand_path
rb_file_dirname1        =~ File.dirname
rb_current_realfilepath =~ __FILE__

how to toggle attr() in jquery

$("form > .form-group > i").click(function(){
    $('#icon').toggleClass('fa-eye fa-eye-slash');

    if($('#icon').hasClass('fa-eye')){
        $('#Password1').attr('type','text');
    } else {
        $('#Password1').attr('type','password');
    }
});

Disable form auto submit on button click

if you want to add directly to input as attribute, use this

 onclick="return false;" 

<input id = "btnPlay" type="button" onclick="return false;" value="play" /> 

this will prevent form submit behaviour

IndentationError expected an indented block

You should install a editor (or IDE) supporting Python syntax. It can highlight source code and make basic format checking. For example: Eric4, Spyder, Ninjia, or Emacs, Vi.

JQuery Redirect to URL after specified time

You could use the setTimeout() function:

// Your delay in milliseconds
var delay = 1000; 
setTimeout(function(){ window.location = URL; }, delay);

GROUP BY to combine/concat a column

SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

Get a list of dates between two dates using a function

SELECT  dateadd(dd,DAYS,'2013-09-07 00:00:00') DATES
INTO        #TEMP1
FROM
(SELECT TOP 365 colorder - 1 AS DAYS from master..syscolumns 
    WHERE id = -519536829 order by colorder) a

WHERE datediff(dd,dateadd(dd,DAYS,'2013-09-07 00:00:00'),'2013-09-13 00:00:00' ) >= 0 
    AND  dateadd(dd,DAYS,'2013-09-07 00:00:00') <=  '2013-09-13 00:00:00'  
    SELECT * FROM #TEMP1

IF... OR IF... in a windows batch file

The goal can be achieved by using IFs indirectly.

Below is an example of a complex expression that can be written quite concisely and logically in a CMD batch, without incoherent labels and GOTOs.

Code blocks between () brackets are handled by CMD as a (pathetic) kind of subshell. Whatever exit code comes out of a block will be used to determine the true/false value the block plays in a larger boolean expression. Arbitrarily large boolean expressions can be built with these code blocks.

Simple example

Each block is resolved to true (i.e. ERRORLEVEL = 0 after the last statement in the block has executed) / false, until the value of the whole expression has been determined or control jumps out (e.g. via GOTO):

 ((DIR c:\xsgdde /w) || (DIR c:\ /w)) && (ECHO -=BINGO=-)

Complex example

This solves the problem raised initially. Multiple statements are possible in each block but in the || || || expression it's preferable to be concise so that it's as readable as possible. ^ is an escape char in CMD batches and when placed at the end of a line it will escape the EOL and instruct CMD to continue reading the current batch of statements on the next line.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

(
    (CALL :ProcedureType1 a b) ^
        || (CALL :ProcedureType2 sgd) ^
            || (CALL :ProcedureType1 c c)
) ^
    && (
        ECHO -=BINGO=-
        GOTO :EOF
    )
ECHO -=no bingo for you=-
GOTO :EOF

:ProcedureType1
    IF "%~1" == "%~2" (EXIT /B 0) ELSE (EXIT /B 1)
GOTO :EOF (this line is decorative as it's never reached)

:ProcedureType2
    ECHO :ax:xa:xx:aa:|FINDSTR /I /L /C:":%~1:">nul
GOTO :EOF

SQL permissions for roles

Unless the role was made dbo, db_owner or db_datawriter, it won't have permission to edit any data. If you want to grant full edit permissions to a single table, do this:

GRANT ALL ON table1 TO doctor 

Users in that role will have no permissions whatsoever to other tables (not even read).

A connection was successfully established with the server, but then an error occurred during the login process. (Error Number: 233)

My problem resolved by this what changes i have done in .net core Do this changes in Appsetting.json

Server=***;Database=***;Persist Security Info=False;User ID=***; Password=***;MultipleActiveResultSets=False;Encrypt=False;TrustServerCertificate=False;Connection Timeout=30

and Do following changes in Package console manager

Scaffold-DbContext "Server=***;Database=***;Persist Security Info=False;User ID=***; Password=***;MultipleActiveResultSets=False;Encrypt=False;TrustServerCertificate=False;Connection Timeout=30;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context DatabaseContext -f

Happy coding

Moving average or running mean

All the aforementioned solutions are poor because they lack

  • speed due to a native python instead of a numpy vectorized implementation,
  • numerical stability due to poor use of numpy.cumsum, or
  • speed due to O(len(x) * w) implementations as convolutions.

Given

import numpy
m = 10000
x = numpy.random.rand(m)
w = 1000

Note that x_[:w].sum() equals x[:w-1].sum(). So for the first average the numpy.cumsum(...) adds x[w] / w (via x_[w+1] / w), and subtracts 0 (from x_[0] / w). This results in x[0:w].mean()

Via cumsum, you'll update the second average by additionally add x[w+1] / w and subtracting x[0] / w, resulting in x[1:w+1].mean().

This goes on until x[-w:].mean() is reached.

x_ = numpy.insert(x, 0, 0)
sliding_average = x_[:w].sum() / w + numpy.cumsum(x_[w:] - x_[:-w]) / w

This solution is vectorized, O(m), readable and numerically stable.

Why is php not running?

One big gotcha is that PHP is disabled in user home directories by default, so if you are testing from ~/public_html it doesn't work. Check /etc/apache2/mods-enabled/php5.conf

# Running PHP scripts in user directories is disabled by default
# 
# To re-enable PHP in user directories comment the following lines
# (from <IfModule ...> to </IfModule>.) Do NOT set it to On as it
# prevents .htaccess files from disabling it.
#<IfModule mod_userdir.c>
#    <Directory /home/*/public_html>
#        php_admin_flag engine Off
#    </Directory>
#</IfModule>

Other than that installing in Ubuntu is real easy, as all the stuff you used to have to put in httpd.conf is done automatically.

How to concatenate multiple lines of output to one line?

Use tr '\n' ' ' to translate all newline characters to spaces:

$ grep pattern file | tr '\n' ' '

Note: grep reads files, cat concatenates files. Don't cat file | grep!

Edit:

tr can only handle single character translations. You could use awk to change the output record separator like:

$ grep pattern file | awk '{print}' ORS='" '

This would transform:

one
two 
three

to:

one" two" three" 

Composer: The requested PHP extension ext-intl * is missing from your system

I have solved this problem by adding --ignore-platform-reqs command with composer install in ubuntu.

composer install --ignore-platform-reqs

How to filter empty or NULL names in a QuerySet?

this is another simple way to do it .

Name.objects.exclude(alias=None)

'const string' vs. 'static readonly string' in C#

OQ asked about static string vs const. Both have different use cases (although both are treated as static).

Use const only for truly constant values (e.g. speed of light - but even this varies depending on medium). The reason for this strict guideline is that the const value is substituted into the uses of the const in assemblies that reference it, meaning you can have versioning issues should the const change in its place of definition (i.e. it shouldn't have been a constant after all). Note this even affects private const fields because you might have base and subclass in different assemblies and private fields are inherited.

Static fields are tied to the type they are declared within. They are used for representing values that need to be the same for all instances of a given type. These fields can be written to as many times as you like (unless specified readonly).

If you meant static readonly vs const, then I'd recommend static readonly for almost all cases because it is more future proof.

Best way to "negate" an instanceof

Usually you don't want just an if but an else clause as well.

if(!(str instanceof String)) { /* do Something */ } 
else { /* do something else */ }

can be written as

if(str instanceof String) { /* do Something else */ } 
else { /* do something */ }

Or you can write the code so you don't need to know if its a String or not. e.g.

if(!(str instanceof String)) { str = str.toString(); } 

can be written as

str = str.toString();

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

I also had this error. It worked normally after I clean up the cookies.

Set icon for Android application

Put your images in mipmap folder and set in manifest file... like as

 <application android:icon="@mipmap/icon" android:label="@string/app_name" >
 .... 
 </application>  

App Folder Directory :

enter image description here

Icon Size & Format : enter image description here

Java: Calculating the angle between two points in degrees

The javadoc for Math.atan(double) is pretty clear that the returning value can range from -pi/2 to pi/2. So you need to compensate for that return value.

HTML character codes for this ? or this ?

The Big and small black triangles facing the 4 directions can be represented thus:

&#x25B2;

&#x25B4;

&#x25B6;

&#x25B8;

&#x25BA;

&#x25BC;

&#x25BE;

&#x25C0;

&#x25C2;

&#x25C4;

Access-Control-Allow-Origin error sending a jQuery Post to Google API's

If you have this error trying to consume a service that you can't add the header Access-Control-Allow-Origin * in that application, but you can put in front of the server a reverse proxy, the error can avoided with a header rewrite.

Assuming the application is running on the port 8080 (public domain at www.mydomain.com), and you put the reverse proxy in the same host at port 80, this is the configuration for Nginx reverse proxy:

server {
    listen      80;
    server_name www.mydomain.com;
    access_log  /var/log/nginx/www.mydomain.com.access.log;
    error_log   /var/log/nginx/www.mydomain.com.error.log;

    location / {
        proxy_pass   http://127.0.0.1:8080;
        add_header   Access-Control-Allow-Origin *;
    }   
}

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

I was also facing the same issue, if suppose that particular fragment is inflated across various screens, there is a chance that the visibility modes set inside the if statements to not function according to our needs as the condition might have been reset when it is inflated a number of times in our app.

In my case, I have to change the visibility mode in one fragment(child fragment) based on a button clicked in another fragment(parent fragment). So I stored the buttonClicked boolean value in a variable of parent fragment and passed it as a parameter to a function in the child fragment. So the visibility modes in the child fragments is changed based on that boolean value that is received via parameter. But as this child fragment is inflated across various screens, the visibility modes kept on resetting even if I make it hidden using View.GONE.

In order to avoid this conflict, I declared a static boolean variable in the child fragment and whenever that boolean value is received from the parent fragment I stored it in the static variable and then changed the visibility modes based on that static variable in the child fragment.

That solved the issue for me.

"Eliminate render-blocking CSS in above-the-fold content"

A related question has been asked before: What is “above-the-fold content” in Google Pagespeed?

Firstly you have to notice that this is all about 'mobile pages'.
So when I interpreted your question and screenshot correctly, then this is not for your site!

On the contrary - doing some of the things advised by Google in their guidelines will things make worse than better for 'normal' websites.
And not everything that comes from Google is the "holy grail" just because it comes from Google. And they themselves are not a good role model if you have a look at their HTML markup.

The best advice I could give you is:

  • Set width and height on replaced elements in your CSS, so that the browser can layout the elements and doesn't have to wait for the replaced content!

Additionally why do you use different CSS files, rather than just one?
The additional request is worse than the small amount of data volume. And after the first request the CSS file is cached anyway.

The things one should always take care of are:

  • reduce the number of requests as much as possible
  • keep your overall page weight as low as possible

And don't puzzle your brain about how to get 100% of Google's PageSpeed Insights tool ...! ;-)

Addition 1: Here is the page on which Google shows us, what they recommend for Optimize CSS Delivery.

As said before, I don't think that this is neither realistic nor that it makes sense for a "normal" website! Because mainly when you have a responsive web design it is most certain that you use media queries and other layout styles. So if you are not gonna load your CSS first and in a blocking manner you'll get a FOUT (Flash Of Unstyled Text). I really do not believe that this is "better" than at least some more milliseconds to render the page!

Imho Google is starting a new "hype" (when I have a look at all the question about it here on Stackoverflow) ...!

Best way to specify whitespace in a String.Split operation

Yes, There is need for one more answer here!

All the solutions thus far address the rather limited domain of canonical input, to wit: a single whitespace character between elements (though tip of the hat to @cherno for at least mentioning the problem). But I submit that in all but the most obscure scenarios, splitting all of these should yield identical results:

string myStrA = "The quick brown fox jumps over the lazy dog";
string myStrB = "The  quick  brown  fox  jumps  over  the  lazy  dog";
string myStrC = "The quick brown fox      jumps over the lazy dog";
string myStrD = "   The quick brown fox jumps over the lazy dog";

String.Split (in any of the flavors shown throughout the other answers here) simply does not work well unless you attach the RemoveEmptyEntries option with either of these:

myStr.Split(new char[0], StringSplitOptions.RemoveEmptyEntries)
myStr.Split(new char[] {' ','\t'}, StringSplitOptions.RemoveEmptyEntries)

As the illustration reveals, omitting the option yields four different results (labeled A, B, C, and D) vs. the single result from all four inputs when you use RemoveEmptyEntries:

String.Split vs Regex.Split

Of course, if you don't like using options, just use the regex alternative :-)

Regex.Split(myStr, @"\s+").Where(s => s != string.Empty)

How to execute an .SQL script file using c#

This Works on Framework 4.0 or Higher. Supports "GO". Also show the error message, line, and sql command.

using System.Data.SqlClient;

        private bool runSqlScriptFile(string pathStoreProceduresFile, string connectionString)
    {
        try
        {
            string script = File.ReadAllText(pathStoreProceduresFile);

            // split script on GO command
            System.Collections.Generic.IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$",
                                     RegexOptions.Multiline | RegexOptions.IgnoreCase);
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                foreach (string commandString in commandStrings)
                {
                    if (commandString.Trim() != "")
                    {
                        using (var command = new SqlCommand(commandString, connection))
                        {
                        try
                        {
                            command.ExecuteNonQuery();
                        }
                        catch (SqlException ex)
                        {
                            string spError = commandString.Length > 100 ? commandString.Substring(0, 100) + " ...\n..." : commandString;
                            MessageBox.Show(string.Format("Please check the SqlServer script.\nFile: {0} \nLine: {1} \nError: {2} \nSQL Command: \n{3}", pathStoreProceduresFile, ex.LineNumber, ex.Message, spError), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return false;
                        }
                    }
                    }
                }
                connection.Close();
            }
        return true;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return false;
        }
    }

jQuery find and replace string

Why you just don't add a class to the string container and then replace the inner text ? Just like in this example.

HTML:

<div>
    <div>
        <p>
           <h1>
             <a class="swapText">lollipops</a>
           </h1>
        </p>
        <span class="swapText">lollipops</span>
    </div>
</div>
<p>
   <span class="lollipops">Hello, World!</span>
   <img src="/lollipops.jpg" alt="Cool image" />
</p>

jQuery:

$(document).ready(function() {
    $('.swapText').text("marshmallows");
});

How to properly use the "choices" field option in Django

You can't have bare words in the code, that's the reason why they created variables (your code will fail with NameError).

The code you provided would create a database table named month (plus whatever prefix django adds to that), because that's the name of the CharField.

But there are better ways to create the particular choices you want. See a previous Stack Overflow question.

import calendar
tuple((m, m) for m in calendar.month_name[1:])

How do I read a string entered by the user in C?

On BSD systems and Android you can also use fgetln:

#include <stdio.h>

char *
fgetln(FILE *stream, size_t *len);

Like so:

size_t line_len;
const char *line = fgetln(stdin, &line_len);

The line is not null terminated and contains \n (or whatever your platform is using) in the end. It becomes invalid after the next I/O operation on stream. You are allowed to modify the returned line buffer.

iPhone SDK:How do you play video inside a view? Rather than fullscreen

Swift version:

import AVFoundation

func playVideo(url: URL) {

    let player = AVPlayer(url: url)

    let layer: AVPlayerLayer = AVPlayerLayer(player: player)
    layer.backgroundColor = UIColor.white.cgColor
    layer.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
    layer.videoGravity = .resizeAspectFill
    self.view.layer.addSublayer(layer)

    player.play()
}

RE error: illegal byte sequence on Mac OS X

You simply have to pipe an iconv command before the sed command. Ex with file.txt input :

iconv -f ISO-8859-1 -t UTF8-MAC file.txt | sed 's/something/àéèêçùû/g' | .....

-f option is the 'from' codeset and -t option is the 'to' codeset conversion.

Take care of case, web pages usually show lowercase like that < charset=iso-8859-1"/> and iconv uses uppercase. You have list of iconv supported codesets in you system with command iconv -l

UTF8-MAC is modern OS Mac codeset for conversion.

How do you reverse a string in place in JavaScript?

During an interview, I was asked to reverse a string without using any variables or native methods. This is my favorite implementation:

function reverseString(str) {
    return str === '' ? '' : reverseString(str.slice(1)) + str[0];
}

VBA Check if variable is empty

For a number, it is tricky because if a numeric cell is empty VBA will assign a default value of 0 to it, so it is hard for your VBA code to tell the difference between an entered zero and a blank numeric cell.

The following check worked for me to see if there was an actual 0 entered into the cell:

If CStr(rng.value) = "0" then
    'your code here'
End If

Testing if value is a function

If it's a string, you could assume / hope it's always of the form

return SomeFunction(arguments);

parse for the function name, and then see if that function is defined using

if (window[functionName]) { 
    // do stuff
}

Sort a Custom Class List<T>

You are right - you need to implement IComparable. To do this, simply declare your class:

public MyClass : IComparable
{
  int IComparable.CompareTo(object obj)
  {
  }
}

In CompareTo, you just implement your custom comparison algorithm (you can use DateTime objects to do this, but just be certain to check the type of "obj" first). For further information, see here and here.

How do you create a static class in C++?

If you're looking for a way of applying the "static" keyword to a class, like you can in C# for example, then you won't be able to without using Managed C++.

But the looks of your sample, you just need to create a public static method on your BitParser object. Like so:

BitParser.h

class BitParser
{
 public:
  static bool getBitAt(int buffer, int bitIndex);

  // ...lots of great stuff

 private:
  // Disallow creating an instance of this object
  BitParser() {}
};

BitParser.cpp

bool BitParser::getBitAt(int buffer, int bitIndex)
{
  bool isBitSet = false;
  // .. determine if bit is set
  return isBitSet;
}

You can use this code to call the method in the same way as your example code.

Hope that helps! Cheers.

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

Here's a free tool that will do it on Windows. I prefer it to a script as it's easy to set up. It runs as a fast native app, works on XP and up, has configuration settings that allow to remap copy/paste/selection keys for command windows:

enter image description here

Plus I know the developers.

LaTeX: remove blank page after a \part or \chapter

A solution that works:

Wrap the part of the document that needs this modified behavior with the code provided below. In my case the portion to wrap is a \part{} and some text following it.

\makeatletter\@openrightfalse
\part{Whatever}

Some text

\chapter{Foo}
\@openrighttrue\makeatother 

The wrapped portion should also include the chapter at the beginning of which this behavior needs to stop. Otherwise LaTeX may generate an empty page before this chapter.

Source: folks at the #latex IRC channel on irc.freenode.net

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

I had the same error for quite a while, and here what fixed it for me.

I simply declared in service that i use what follows:

Description= Your node service description
After=network.target

[Service]
Type=forking
PIDFile=/tmp/node_pid_name.pid
Restart=on-failure
KillSignal=SIGQUIT
WorkingDirectory=/path/to/node/app/root/directory
ExecStart=/path/to/node /path/to/server.js

[Install]
WantedBy=multi-user.target

What should catch your attention here is "After=network.target". I spent days and days looking for fixes on nginx side, while the problem was just that. To be sure, stop running the node service you have, launch the ExecStart command directly and try to reproduce the bug. If it doesn't pop, it just means that your service has a problem. At least this is how i found my answer.

For everybody else, good luck!

How to copy files from 'assets' folder to sdcard?

Using some of the concepts in the answers to this question, I wrote up a class called AssetCopier to make copying /assets/ simple. It's available on github and can be accessed with jitpack.io:

new AssetCopier(MainActivity.this)
        .withFileScanning()
        .copy("tocopy", destDir);

See https://github.com/flipagram/android-assetcopier for more details.

find difference between two text files with one item per line

A tried a slight variation on Luca's answer and it worked for me.

diff file1 file2 | grep ">" | sed 's/^> //g' > diff_file

Note that the searched pattern in sed is a > followed by a space.

Can I map a hostname *and* a port with /etc/hosts?

If you really need to do this, use reverse proxy.

For example, with nginx as reverse proxy

server {
  listen       api.mydomain.com:80;
  server_name  api.mydomain.com;
  location / {
    proxy_pass http://127.0.0.1:8000;
  }
}

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is unsigned 16-bit integer.

unsigned short int is unsigned short integer, but the size is implementation dependent. The standard only says it's at least 16-bit (i.e, minimum value of UINT_MAX is 65535). In practice, it usually is 16-bit, but you can't take that as guaranteed.

Note:

  1. If you want a portable unsigned 16-bit integer, use uint16_t.
  2. inttypes.h and stdint.h are both introduced in C99. If you are using C89, define your own type.
  3. uint16_t may not be provided in certain implementation(See reference below), but unsigned short int is always available.

Reference: C11(ISO/IEC 9899:201x) §7.20 Integer types

For each type described herein that the implementation provides) shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, shall not declare that typedef name nor shall it define the associated macros. An implementation shall provide those types described as ‘‘required’’, but need not provide any of the others (described as ‘optional’’).

Sorting HashMap by values

In Java 8:

Map<Integer, String> sortedMap = 
     unsortedMap.entrySet().stream()
    .sorted(Entry.comparingByValue())
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue,
                              (e1, e2) -> e1, LinkedHashMap::new));

Random integer in VB.NET

Dim rnd As Random = New Random
rnd.Next(n)