Programs & Examples On #Uplevel

Python-Requests close http connection

On Requests 1.X, the connection is available on the response object:

r = requests.post("https://stream.twitter.com/1/statuses/filter.json",
                  data={'track': toTrack}, auth=('username', 'passwd'))

r.connection.close()

getMinutes() 0-9 - How to display two digit numbers?

I dont see any ES6 answers on here so I will add one using StandardJS formatting

// ES6 String formatting example
const time = new Date()
const tempMinutes = new Date.getMinutes()
const minutes = (tempMinutes < 10) ? `0${tempMinutes}` : tempMinutes

ssl.SSLError: tlsv1 alert protocol version

I got this problem too. In macos, here is the solution:

  • Step 1: brew restall python. now you got python3.7 instead of the old python

  • Step 2: build the new env base on python3.7. my path is /usr/local/Cellar/python/3.7.2/bin/python3.7

now, you'll not being disturbed by this problem.

can we use xpath with BeautifulSoup?

As others have said, BeautifulSoup doesn't have xpath support. There are probably a number of ways to get something from an xpath, including using Selenium. However, here's a solution that works in either Python 2 or 3:

from lxml import html
import requests

page = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
tree = html.fromstring(page.content)
#This will create a list of buyers:
buyers = tree.xpath('//div[@title="buyer-name"]/text()')
#This will create a list of prices
prices = tree.xpath('//span[@class="item-price"]/text()')

print('Buyers: ', buyers)
print('Prices: ', prices)

I used this as a reference.

Height of status bar in Android

On Android 4.1 and higher, you can set your application's content to appear behind the status bar, so that the content doesn't resize as the status bar hides and shows. To do this, use SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN. You may also need to use SYSTEM_UI_FLAG_LAYOUT_STABLE to help your app maintain a stable layout.

When you use this approach, it becomes your responsibility to ensure that critical parts of your app's UI (for example, the built-in controls in a Maps application) don't end up getting covered by system bars. This could make your app unusable. In most cases you can handle this by adding the android:fitsSystemWindows attribute to your XML layout file, set to true. This adjusts the padding of the parent ViewGroup to leave space for the system windows. This is sufficient for most applications.

In some cases, however, you may need to modify the default padding to get the desired layout for your app. To directly manipulate how your content lays out relative to the system bars (which occupy a space known as the window's "content insets"), override fitSystemWindows(Rect insets). The fitSystemWindows() method is called by the view hierarchy when the content insets for a window have changed, to allow the window to adjust its content accordingly. By overriding this method you can handle the insets (and hence your app's layout) however you want.

form: https://developer.android.com/training/system-ui/status.html#behind

How to print number with commas as thousands separators?

This is what I do for floats. Although, honestly, I'm not sure which versions it works for - I'm using 2.7:

my_number = 4385893.382939491

my_string = '{:0,.2f}'.format(my_number)

Returns: 4,385,893.38

Update: I recently had an issue with this format (couldn't tell you the exact reason), but was able to fix it by dropping the 0:

my_string = '{:,.2f}'.format(my_number)

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

Insert the image directly in the Jupyter notebook.

Note: You should have a local copy of the image on your computer

You can insert the image in the Jupyter notebook itself. This way you don't need to keep the image separately in the folder.

Steps:

  1. Convert the cell to markdown by:

    • pressing M on the selected cell
      OR
    • From menu bar, Cell > Cell Type > Markdown.
      (Note: It's important to convert the cell to Markdown, otherwise the "Insert Image" option in Step 2 will not be active)
  2. Now go to menu bar and select Edit -> Insert Image.

  3. Select image from your disk and upload.

  4. Press Ctrl+Enter or Shift+Enter.

This will make the image as part of the notebook and you don't need to upload in the directory or Github. I feel this looks more clean and not prone to broken URL issue.

Set Page Title using PHP

What about using something like:

<?php 
    $page_title = "Your page tile";
    include("navigation.php");             // if required
    echo("<title>$page_title</title>");
?>

How do I run all Python unit tests in a directory?

I use PyDev/LiClipse and haven't really figured out how to run all tests at once from the GUI. (edit: you right click the root test folder and choose Run as -> Python unit-test

This is my current workaround:

import unittest

def load_tests(loader, tests, pattern):
    return loader.discover('.')

if __name__ == '__main__':
    unittest.main()

I put this code in a module called all in my test directory. If I run this module as a unittest from LiClipse then all tests are run. If I ask to only repeat specific or failed tests then only those tests are run. It doesn't interfere with my commandline test runner either (nosetests) -- it's ignored.

You may need to change the arguments to discover based on your project setup.

Netbeans how to set command line arguments in Java

import java.io.*;
class Main
{
public static void main(String args[]) throws IOException
{
    int n1,n2,n3,l;
    n1=Integer.parseInt(args[0]);
    n2=Integer.parseInt(args[1]);
    n3=Integer.parseInt(args[2]);
    
    if(n1>n2)
    {
        l=n1;
    }
    else
    {
        l=n2;
    }
    
    if(l<n3)
    {
        System.out.println("largest no is "+n3);
    }
    else
    {
        System.out.println("largest no is "+l);
    }
    
}}

Consider above program, in this program I want to pass 3 no's from Command Line, to do so.

Step 1 : Right Click on Cup and Saucer icon, u'll see this window

1

Step 2: Click on Properties

Step 3: Click Run _> Arguments _> type three no's eg. 32 98 16 then click OK. Plz add space between two arguments. See here

2

Step 4: Run the Program by using F6.

JAX-WS and BASIC authentication, when user names and passwords are in a database

If you put the username and password at clientside into the request this way:

URL url = new URL("http://localhost:8080/myapplication?wsdl");
MyWebService webservice = new MyWebServiceImplService(url).getMyWebServiceImplPort();
Map<String, Object> requestContext = ((BindingProvider) webservice).getRequestContext();
requestContext.put(BindingProvider.USERNAME_PROPERTY, "myusername");
requestContext.put(BindingProvider.PASSWORD_PROPERTY, "mypassword");

and call your webservice

String response = webservice.someMethodAtMyWebservice("test");

Then you can read the Basic Authentication string like this at the server side (you have to add some checks and do some exceptionhandling):

@Resource
WebServiceContext webserviceContext;

public void someMethodAtMyWebservice(String parameter) {
    MessageContext messageContext = webserviceContext.getMessageContext();
    Map<String, ?> httpRequestHeaders = (Map<String, ?>) messageContext.get(MessageContext.HTTP_REQUEST_HEADERS);
    List<?> authorizationList = (List<?>) httpRequestHeaders.get("Authorization");
    if (authorizationList != null && !authorizationList.isEmpty()) {
        String basicString = (String) authorizationList.get(0);
        String encodedBasicString = basicString.substring("Basic ".length());
        String decoded = new String(Base64.getDecoder().decode(encodedBasicString), StandardCharsets.UTF_8);
        String[] splitter = decoded.split(":");
        String usernameFromBasicAuth = splitter[0];
        String passwordFromBasicAuth = splitter[1];
    }

Access mysql remote database from command line

You should put your password with 'p'

mysql -u root -u 1.1.1.1 -p'MyPass'

Java : Cannot format given Object as a Date

I have resolved it , this way

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class DateParser {

    public static void main(String args[]) throws Exception {

        DateParser dateParser = new DateParser();

        String str = dateParser.getparsedDate("2012-11-17T00:00:00.000-05:00");
        System.out.println(str);
    }


    private String getparsedDate(String date) throws Exception {
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
        String s1 = date;
        String s2 = null;
        Date d;
        try {
            d = sdf.parse(s1);
            s2 = (new SimpleDateFormat("MM/yyyy")).format(d);

        } catch (ParseException e) {

            e.printStackTrace();
        }

        return s2;

    }

}

Open a folder using Process.Start

Just for completeness, if all you want to do is to open a folder, use this:

System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo() {
    FileName = "C:\\teste\\",
    UseShellExecute = true,
    Verb = "open"
});

Ensure FileName ends with Path.DirectorySeparatorChar to make it unambiguously point to a folder. (Thanks to @binki.)

This solution won't work for opening a folder and selecting an item, since there doesn't seem a verb for that.

Printing all global variables/local variables?

Type info variables to list "All global and static variable names".

Type info locals to list "Local variables of current stack frame" (names and values), including static variables in that function.

Type info args to list "Arguments of the current stack frame" (names and values).

How do I horizontally center a span element inside a div

another option would be to give the span display:table; and center it via margin:0 auto;

span {
display:table;
margin:0 auto;
}

Unbound classpath container in Eclipse

This is pretty old question and I recently came across this. Also answers says make sure that you have the correct JDK registered in Installed JRE section of Eclipse properties, and that is it. I had the correct JDK registered and that was marked as default, but still I got this error. There is one more missing piece.

Make sure the in the Installed JREs section the name of your target runtime environment is exactly as it is mentioned in your imported project. For example if the error you get is - Unbound classpath container: 'JRE System Library [JavaSE-1.8]'. Then in Installed JREs you need to have JDK 1.8 registered and its name should be the exact value mentioned in square brackets, which in this case is JavaSE-1.8.

Show all tables inside a MySQL database using PHP?

<?php
$dbname = 'mysql_dbname';
if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
mysql_free_result($result);
?>
//Try This code is running perfectly !!!!!!!!!!


How to add facebook share button on my website?

For your own specific server or different pages & image button you could use something like this (PHP only)

<a href="http://www.facebook.com/sharer/sharer.php?u=http://'.$_SERVER['SERVER_NAME'].'" target="_blank"><img src="http://i.stack.imgur.com/rffGp.png" /></a>

I cannot share the snippet with this but you will get the idea...

Javascript, Time and Date: Getting the current minute, hour, day, week, month, year of a given millisecond time

Regarding number of days in month just use static switch command and check if (year % 4 == 0) in which case February will have 29 days.

Minute, hour, day etc:

var someMillisecondValue = 511111222127;
var date = new Date(someMillisecondValue);
var minute = date.getMinutes();
var hour = date.getHours();
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
alert([minute, hour, day, month, year].join("\n"));

nginx - client_max_body_size has no effect

I meet the same problem, but I found it nothing to do with nginx. I am using nodejs as backend server, use nginx as a reverse proxy, 413 code is triggered by node server. node use koa parse the body. koa limit the urlencoded length.

formLimit: limit of the urlencoded body. If the body ends up being larger than this limit, a 413 error code is returned. Default is 56kb.

set formLimit to bigger can solve this problem.

How to print an exception in Python 3?

Try

try:
    print undefined_var
except Exception as e:
    print(e)

this will print the representation given by e.__str__():

"name 'undefined_var' is not defined"

you can also use:

print(repr(e))

which will include the Exception class name:

"NameError("name 'undefined_var' is not defined",)"

AttributeError: 'DataFrame' object has no attribute

To get all the counts for all the columns in a dataframe, it's just df.count()

Compute row average in pandas

If you are looking to average column wise. Try this,

df.drop('Region', axis=1).apply(lambda x: x.mean())

# it drops the Region column
df.drop('Region', axis=1,inplace=True)

CSS3 transitions inside jQuery .css()

Step 1) Remove the semi-colon, it's an object you're creating...

a(this).next().css({
    left       : c,
    transition : 'opacity 1s ease-in-out';
});

to

a(this).next().css({
    left       : c,
    transition : 'opacity 1s ease-in-out'
});

Step 2) Vendor-prefixes... no browsers use transition since it's the standard and this is an experimental feature even in the latest browsers:

a(this).next().css({
    left             : c,
    WebkitTransition : 'opacity 1s ease-in-out',
    MozTransition    : 'opacity 1s ease-in-out',
    MsTransition     : 'opacity 1s ease-in-out',
    OTransition      : 'opacity 1s ease-in-out',
    transition       : 'opacity 1s ease-in-out'
});

Here is a demo: http://jsfiddle.net/83FsJ/

Step 3) Better vendor-prefixes... Instead of adding tons of unnecessary CSS to elements (that will just be ignored by the browser) you can use jQuery to decide what vendor-prefix to use:

$('a').on('click', function () {
    var myTransition = ($.browser.webkit)  ? '-webkit-transition' :
                       ($.browser.mozilla) ? '-moz-transition' : 
                       ($.browser.msie)    ? '-ms-transition' :
                       ($.browser.opera)   ? '-o-transition' : 'transition',
        myCSSObj     = { opacity : 1 };

    myCSSObj[myTransition] = 'opacity 1s ease-in-out';
    $(this).next().css(myCSSObj);
});?

Here is a demo: http://jsfiddle.net/83FsJ/1/

Also note that if you specify in your transition declaration that the property to animate is opacity, setting a left property won't be animated.

Automatically add all files in a folder to a target using CMake?

So Why not use powershell to create the list of source files for you. Take a look at this script

param (
    [Parameter(Mandatory=$True)]
    [string]$root 
)

if (-not (Test-Path  -Path $root)) {    
throw "Error directory does not exist"
}

#get the full path of the root
$rootDir = get-item -Path $root
$fp=$rootDir.FullName;


$files = Get-ChildItem -Path $root -Recurse -File | 
         Where-Object { ".cpp",".cxx",".cc",".h" -contains $_.Extension} | 
         Foreach {$_.FullName.replace("${fp}\","").replace("\","/")}

$CMakeExpr = "set(SOURCES "

foreach($file in $files){

    $CMakeExpr+= """$file"" " ;
}
$CMakeExpr+=")"
return $CMakeExpr;

Suppose you have a folder with this structure

C:\Workspace\A
--a.cpp
C:\Workspace\B 
--b.cpp

Now save this file as "generateSourceList.ps1" for example, and run the script as

~>./generateSourceList.ps1 -root "C:\Workspace" > out.txt

out.txt file will contain

set(SOURCE "A/a.cpp" "B/b.cpp")

Splitting a list into N parts of approximately equal length

def evenly(l, n):
    len_ = len(l)
    split_size = len_ // n
    split_size = n if not split_size else split_size
    offsets = [i for i in range(0, len_, split_size)]
    return [l[offset:offset + split_size] for offset in offsets]

Example:

l = [a for a in range(97)] should be consist of 10 parts, each have 9 elements except the last one.

Output:

[[0, 1, 2, 3, 4, 5, 6, 7, 8],
 [9, 10, 11, 12, 13, 14, 15, 16, 17],
 [18, 19, 20, 21, 22, 23, 24, 25, 26],
 [27, 28, 29, 30, 31, 32, 33, 34, 35],
 [36, 37, 38, 39, 40, 41, 42, 43, 44],
 [45, 46, 47, 48, 49, 50, 51, 52, 53],
 [54, 55, 56, 57, 58, 59, 60, 61, 62],
 [63, 64, 65, 66, 67, 68, 69, 70, 71],
 [72, 73, 74, 75, 76, 77, 78, 79, 80],
 [81, 82, 83, 84, 85, 86, 87, 88, 89],
 [90, 91, 92, 93, 94, 95, 96]]

Sending HTTP Post request with SOAP action using org.apache.http

Here is the example i have tried and it is working for me:

Create the XML file SoapRequestFile.xml

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/">
       <soapenv:Header/>
       <soapenv:Body>
          <tem:GetConversionRate>
             <!--Optional:-->
             <tem:CurrencyFrom>USD</tem:CurrencyFrom>
             <!--Optional:-->
             <tem:CurrencyTo>INR</tem:CurrencyTo>
             <tem:RateDate>2018-12-07</tem:RateDate>
          </tem:GetConversionRate>
       </soapenv:Body>
    </soapenv:Envelope>

And here the code in java:

import java.io.File;
import java.io.FileInputStream;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Assert;
import org.testng.annotations.Test;

import io.restassured.path.json.JsonPath;
import io.restassured.path.xml.XmlPath;
@Test
            public void getMethod() throws Exception  {
                //wsdl file :http://currencyconverter.kowabunga.net/converter.asmx?wsdl
                File soapRequestFile = new File(".\\SOAPRequest\\SoapRequestFile.xml");

                CloseableHttpClient client = HttpClients.createDefault(); //create client
                HttpPost request = new HttpPost("http://currencyconverter.kowabunga.net/converter.asmx"); //Create the request
                request.addHeader("Content-Type", "text/xml"); //adding header
                request.setEntity(new InputStreamEntity(new FileInputStream(soapRequestFile)));
                CloseableHttpResponse response =  client.execute(request);//Execute the command

                int statusCode=response.getStatusLine().getStatusCode();//Get the status code and assert
                System.out.println("Status code: " +statusCode );
                Assert.assertEquals(200, statusCode);

                String responseString = EntityUtils.toString(response.getEntity(),"UTF-8");//Getting the Response body
                System.out.println(responseString);


                XmlPath jsXpath= new XmlPath(responseString);//Converting string into xml path to assert
                String rate=jsXpath.getString("GetConversionRateResult");
                System.out.println("rate returned is: " +  rate);



        }

How to resolve the C:\fakepath?

Use

document.getElementById("file-id").files[0].name; 

instead of

document.getElementById('file-id').value

Create a date from day month and year with T-SQL

Try this query:

    SELECT SUBSTRING(CONVERT(VARCHAR,JOINGDATE,103),7,4)AS
    YEAR,SUBSTRING(CONVERT(VARCHAR,JOINGDATE,100),1,2)AS
MONTH,SUBSTRING(CONVERT(VARCHAR,JOINGDATE,100),4,3)AS DATE FROM EMPLOYEE1

Result:

2014    Ja    1
2015    Ja    1
2014    Ja    1
2015    Ja    1
2012    Ja    1
2010    Ja    1
2015    Ja    1

CSS height 100% percent not working

I believe you need to make sure that all the container div tags above the 100% height div also has 100% height set on them including the body tag and html.

Changing a specific column name in pandas DataFrame

Following short code can help:

df3 = df3.rename(columns={c: c.replace(' ', '') for c in df3.columns})

Remove spaces from columns.

Pandas Merging 101

This post will go through the following topics:

  • Merging with index under different conditions
    • options for index-based joins: merge, join, concat
    • merging on indexes
    • merging on index of one, column of other
  • effectively using named indexes to simplify merging syntax

BACK TO TOP



Index-based joins

TL;DR

There are a few options, some simpler than others depending on the use case.

  1. DataFrame.merge with left_index and right_index (or left_on and right_on using names indexes)
    • supports inner/left/right/full
    • can only join two at a time
    • supports column-column, index-column, index-index joins
  2. DataFrame.join (join on index)
    • supports inner/left (default)/right/full
    • can join multiple DataFrames at a time
    • supports index-index joins
  3. pd.concat (joins on index)
    • supports inner/full (default)
    • can join multiple DataFrames at a time
    • supports index-index joins

Index to index joins

Setup & Basics

import pandas as pd
import numpy as np

np.random.seed([3, 14])
left = pd.DataFrame(data={'value': np.random.randn(4)}, 
                    index=['A', 'B', 'C', 'D'])    
right = pd.DataFrame(data={'value': np.random.randn(4)},  
                     index=['B', 'D', 'E', 'F'])
left.index.name = right.index.name = 'idxkey'

left
           value
idxkey          
A      -0.602923
B      -0.402655
C       0.302329
D      -0.524349

right
 
           value
idxkey          
B       0.543843
D       0.013135
E      -0.326498
F       1.385076

Typically, an inner join on index would look like this:

left.merge(right, left_index=True, right_index=True)

         value_x   value_y
idxkey                    
B      -0.402655  0.543843
D      -0.524349  0.013135

Other joins follow similar syntax.

Notable Alternatives

  1. DataFrame.join defaults to joins on the index. DataFrame.join does a LEFT OUTER JOIN by default, so how='inner' is necessary here.

     left.join(right, how='inner', lsuffix='_x', rsuffix='_y')
    
              value_x   value_y
     idxkey                    
     B      -0.402655  0.543843
     D      -0.524349  0.013135
    

    Note that I needed to specify the lsuffix and rsuffix arguments since join would otherwise error out:

     left.join(right)
     ValueError: columns overlap but no suffix specified: Index(['value'], dtype='object')
    

    Since the column names are the same. This would not be a problem if they were differently named.

     left.rename(columns={'value':'leftvalue'}).join(right, how='inner')
    
             leftvalue     value
     idxkey                     
     B       -0.402655  0.543843
     D       -0.524349  0.013135
    
  2. pd.concat joins on the index and can join two or more DataFrames at once. It does a full outer join by default, so how='inner' is required here..

     pd.concat([left, right], axis=1, sort=False, join='inner')
    
                value     value
     idxkey                    
     B      -0.402655  0.543843
     D      -0.524349  0.013135
    

    For more information on concat, see this post.


Index to Column joins

To perform an inner join using index of left, column of right, you will use DataFrame.merge a combination of left_index=True and right_on=....

right2 = right.reset_index().rename({'idxkey' : 'colkey'}, axis=1)
right2
 
  colkey     value
0      B  0.543843
1      D  0.013135
2      E -0.326498
3      F  1.385076

left.merge(right2, left_index=True, right_on='colkey')

    value_x colkey   value_y
0 -0.402655      B  0.543843
1 -0.524349      D  0.013135

Other joins follow a similar structure. Note that only merge can perform index to column joins. You can join on multiple columns, provided the number of index levels on the left equals the number of columns on the right.

join and concat are not capable of mixed merges. You will need to set the index as a pre-step using DataFrame.set_index.


Effectively using Named Index [pandas >= 0.23]

If your index is named, then from pandas >= 0.23, DataFrame.merge allows you to specify the index name to on (or left_on and right_on as necessary).

left.merge(right, on='idxkey')

         value_x   value_y
idxkey                    
B      -0.402655  0.543843
D      -0.524349  0.013135

For the previous example of merging with the index of left, column of right, you can use left_on with the index name of left:

left.merge(right2, left_on='idxkey', right_on='colkey')

    value_x colkey   value_y
0 -0.402655      B  0.543843
1 -0.524349      D  0.013135


Continue Reading

Jump to other topics in Pandas Merging 101 to continue learning:

* you are here

How to add number of days to today's date?

You can use JavaScript, no jQuery required:

var someDate = new Date();
var numberOfDaysToAdd = 6;
someDate.setDate(someDate.getDate() + numberOfDaysToAdd); 

Formatting to dd/mm/yyyy :

var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var y = someDate.getFullYear();

var someFormattedDate = dd + '/'+ mm + '/'+ y;

How to convert date in to yyyy-MM-dd Format?

You can't format the Date itself. You can only get the formatted result in String. Use SimpleDateFormat as mentioned by others.

Moreover, most of the getter methods in Date are deprecated.

Converting unix timestamp string to readable date

quick and dirty one liner:

'-'.join(str(x) for x in list(tuple(datetime.datetime.now().timetuple())[:6]))

'2013-5-5-1-9-43'

How to export a table dataframe in PySpark to csv?

You need to repartition the Dataframe in a single partition and then define the format, path and other parameter to the file in Unix file system format and here you go,

df.repartition(1).write.format('com.databricks.spark.csv').save("/path/to/file/myfile.csv",header = 'true')

Read more about the repartition function Read more about the save function

However, repartition is a costly function and toPandas() is worst. Try using .coalesce(1) instead of .repartition(1) in previous syntax for better performance.

Read more on repartition vs coalesce functions.

Java multiline string

When a long series of + are used, only one StringBuilder is created, unless the String is determined at compile time in which case no StringBuilder is used!

The only time StringBuilder is more efficient is when multiple statements are used to construct the String.

String a = "a\n";
String b = "b\n";
String c = "c\n";
String d = "d\n";

String abcd = a + b + c + d;
System.out.println(abcd);

String abcd2 = "a\n" +
        "b\n" +
        "c\n" +
        "d\n";
System.out.println(abcd2);

Note: Only one StringBuilder is created.

  Code:
   0:   ldc     #2; //String a\n
   2:   astore_1
   3:   ldc     #3; //String b\n
   5:   astore_2
   6:   ldc     #4; //String c\n
   8:   astore_3
   9:   ldc     #5; //String d\n
   11:  astore  4
   13:  new     #6; //class java/lang/StringBuilder
   16:  dup
   17:  invokespecial   #7; //Method java/lang/StringBuilder."<init>":()V
   20:  aload_1
   21:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   24:  aload_2
   25:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   28:  aload_3
   29:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   32:  aload   4
   34:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   37:  invokevirtual   #9; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
   40:  astore  5
   42:  getstatic       #10; //Field java/lang/System.out:Ljava/io/PrintStream;
   45:  aload   5
   47:  invokevirtual   #11; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   50:  ldc     #12; //String a\nb\nc\nd\n
   52:  astore  6
   54:  getstatic       #10; //Field java/lang/System.out:Ljava/io/PrintStream;
   57:  aload   6
   59:  invokevirtual   #11; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   62:  return

To clarify my question further, I'm not concerned about performance at all. I'm concerned about maintainability and design issues.

Make it as clear and simple as you can.

Using ping in c#

using System.Net.NetworkInformation;    

public static bool PingHost(string nameOrAddress)
{
    bool pingable = false;
    Ping pinger = null;

    try
    {
        pinger = new Ping();
        PingReply reply = pinger.Send(nameOrAddress);
        pingable = reply.Status == IPStatus.Success;
    }
    catch (PingException)
    {
        // Discard PingExceptions and return false;
    }
    finally
    {
        if (pinger != null)
        {
            pinger.Dispose();
        }
    }

    return pingable;
}

function to return a string in java

Your code is fine. There's no problem with returning Strings in this manner.

In Java, a String is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String around without worrying that it would disapper on you, or that someone somewhere would modify it.

If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:

public String time_to_string(long t) // time in milliseconds
{
    if (t < 0)
    {
        return "-";
    }
    else
    {
        int secs = (int)(t/1000);
        int mins = secs/60;
        secs = secs - (mins * 60);
        return String.format("%d:%02d", mins, secs);
    }
}

As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans and have replaced the mix of string concatenation and String.format() with a single call to String.format().

Replace transparency in PNG images with white background

The only one that worked for me was a mix of all the answers:

convert in.png -background white -alpha remove -flatten -alpha off out.png

You must add a reference to assembly 'netstandard, Version=2.0.0.0

We started getting this error on the production server after deploying the application migrated from 4.6.1 to 4.7.2.

We noticed that the .NET framework 4.7.2 was not installed there. In order to solve this issue we did the following steps:

  1. Installed the .NET Framework 4.7.2 from:

    https://support.microsoft.com/en-us/help/4054530/microsoft-net-framework-4-7-2-offline-installer-for-windows

  2. Restarted the machine

  3. Confirmed the .NET Framework version with the help of How do I find the .NET version?

Running the application again with the .Net Framework 4.7.2 version installed on the machine fixed the issue.

Java: Find .txt files in specified folder

import org.apache.commons.io.filefilter.WildcardFileFilter;

.........
.........

File dir = new File(fileDir);
FileFilter fileFilter = new WildcardFileFilter("*.txt");
File[] files = dir.listFiles(fileFilter);

The code above works great for me

Where is Java Installed on Mac OS X?

just write /Library/Java/JavaVirtualMachines/
in Go to Folder --> Go in Finder

What is the easiest way to ignore a JPA field during persistence?

Sometimes you want to:

  1. Serialize a column
  2. Ignore column from being persisted:

Use @Column(name = "columnName", insertable = false, updatable = false)

A good scenario is when a certain column is automatically calculated by using other column values

How to use `replace` of directive definition?

Also i got this error if i had the comment in tn top level of template among with the actual root element.

<!-- Just a commented out stuff -->
<div>test of {{value}}</div>

Changing Fonts Size in Matlab Plots

If anyone was wondering how to change the font sizes without messing around with the Matlab default fonts, and change every font in a figure, I found this thread where suggests this:

set(findall(fig, '-property', 'FontSize'), 'FontSize', 10, 'fontWeight', 'bold')

findall is a pretty handy command and in the case above it really finds all the children who have a 'FontSize' property: axes lables, axes titles, pushbuttons, etc.

Hope it helps.

How to play .mp4 video in videoview in android?

I'm not sure that is the problem but what worked for me is calling mVideoView.start(); inside the mVideoView.setOnPreparedListener event callback.

For example:

Uri uriVideo = Uri.parse(<your link here>);

MediaController mediaController = new MediaController(mContext);
mediaController.setAnchorView(mVideoView);
mVideoView.setMediaController(mediaController);
mVideoView.setVideoURI(uriVideo);
mVideoView.requestFocus();

mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
     @Override
     public void onPrepared(MediaPlayer mp)
     {
          mVideoViewPeekItem.start();
     }
});

Size of Matrix OpenCV

If you are using the Python wrappers, then (assuming your matrix name is mat):

  • mat.shape gives you an array of the type- [height, width, channels]

  • mat.size gives you the size of the array

Sample Code:

import cv2
mat = cv2.imread('sample.png')
height, width, channel = mat.shape[:3]
size = mat.size

How to create a box when mouse over text in pure CSS?

This is a small tweak on the other answers. If you have nested divs you can include more exciting content such as H1s in your popup.

CSS

div.appear {
    width: 250px; 
    border: #000 2px solid;
    background:#F8F8F8;
    position: relative;
    top: 5px;
    left:15px;
    display:none;
    padding: 0 20px 20px 20px;
    z-index: 1000000;
}
div.hover  {
    cursor:pointer;
    width: 5px;
}
div.hover:hover div.appear {
    display:block;
}

HTML

<div class="hover">
<img src="questionmark.png"/>
    <div class="appear">
       <h1>My popup</h1>Hitherto and whenceforth.
    </div>
</div>

The problem with these solutions is that everything after this in the page gets shifted when the popup is displayed, ie, the rest of the page jumps downwards to 'make space'. The only way I could fix this was by making position:absolute and removing the top and left CSS tags.

What is the difference between id and class in CSS, and when should I use them?

As pretty much everyone else has said use ID for one-off elements and class for multiple use elements.

Here is a quick, over simplified example, take HTML and HEAD tags as read

<body>
    <div id="leftCol">
        You will only have one left column
    </div>
    <div id="mainContent">
        Only one main content container, but.....
        <p class="prettyPara">You might want more than one pretty paragraph</p>
        <p>This one is boring and unstyled</p>
        <p class="prettyPara">See I told you, you might need another!</p>
    </div>
    <div id="footer">
        Not very HTML5 but you'll likely only have one of these too.
    </div>
</body>

Also, as mentioned in other answers ID are well exposed to javascript, classes less so. However modern javascript frameworks like jQuery leverage class for javascript too

Creating a mock HttpServletRequest out of a url string?

You would generally test these sorts of things in an integration test, which actually connects to a service. To do a unit test, you should test the objects used by your servlet's doGet/doPost methods.

In general you don't want to have much code in your servlet methods, you would want to create a bean class to handle operations and pass your own objects to it and not servlet API objects.

CSS / HTML Navigation and Logo on same line

Try this CSS:

body {
  margin: 0;
  padding: 0;
}

.logo {
  float: left;
}
/* ~~ Top Navigation Bar ~~ */

#navigation-container {
  width: 1200px;
  margin: 0 auto;
  height: 70px;
}

.navigation-bar {
  background-color: #352d2f;
  height: 70px;
  width: 100%;
}

#navigation-container img {
  float: left;
}

#navigation-container ul {
  padding: 0px;
  margin: 0px;
  text-align: center;
  display:inline-block;
}

#navigation-container li {
  list-style-type: none;
  padding: 0px;
  height: 24px;
  margin-top: 4px;
  margin-bottom: 4px;
  display: inline;
}

#navigation-container li a {
  color: white;
  font-size: 16px;
  font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
  text-decoration: none;
  line-height: 70px;
  padding: 5px 15px;
  opacity: 0.7;
}

#menu {
  float: right;
}

Change grid interval and specify tick labels in Matplotlib

A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.

import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)

fig, ax = plt.subplots(figsize=(10, 8))

# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)

# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))

# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))

# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')

Matplotlib Custom Grid

Getting the actual usedrange

What sort of button, neither a Forms Control nor an ActiveX control should affect the used range.

It is a known problem that excel does not keep track of the used range very well. Any reference to the used range via VBA will reset the value to the current used range. So try running this sub procedure:

Sub ResetUsedRng()
    Application.ActiveSheet.UsedRange 
End Sub 

Failing that you may well have some formatting hanging round. Try clearing/deleting all the cells after your last row.

Regarding the above also see:

Excel Developer Tip

Another method to find the last used cell:

    Dim rLastCell As Range

    Set rLastCell = ActiveSheet.Cells.Find(What:="*", After:=.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
    xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)

Change the search direction to find the first used cell.

Run ssh and immediately execute command

This isn't quite what you're looking for, but I've found it useful in similar circumstances.

I recently added the following to my $HOME/.bashrc (something similar should be possible with shells other than bash):

if [ -f $HOME/.add-screen-to-history ] ; then
    history -s 'screen -dr'
fi

I keep a screen session running on one particular machine, and I've had problems with ssh connections to that machine being dropped, requiring me to re-run screen -dr every time I reconnect.

With that addition, and after creating that (empty) file in my home directory, I automatically have the screen -dr command in my history when my shell starts. After reconnecting, I can just type Control-P Enter and I'm back in my screen session -- or I can ignore it. It's flexible, but not quite automatic, and in your case it's easier than typing tmux list-sessions.

You might want to make the history -s command unconditional.

This does require updating your $HOME/.bashrc on each of the target systems, which might or might not make it unsuitable for your purposes.

Rotate camera in Three.js with mouse

take a look at the following examples

http://threejs.org/examples/#misc_controls_orbit

http://threejs.org/examples/#misc_controls_trackball

there are other examples for different mouse controls, but both of these allow the camera to rotate around a point and zoom in and out with the mouse wheel, the main difference is OrbitControls enforces the camera up direction, and TrackballControls allows the camera to rotate upside-down.

All you have to do is include the controls in your html document

<script src="js/OrbitControls.js"></script>

and include this line in your source

controls = new THREE.OrbitControls( camera, renderer.domElement );

Different ways of loading a file as an InputStream

It Works , try out this :

InputStream in_s1 =   TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml");

SQL Server Management Studio alternatives to browse/edit tables and run queries

I've started using LinqPad. In addition to being more lightweight than SSMS, you can also practice writing LINQ queries- way more fun than boring old TSQL!

How to set iframe size dynamically

I've found this to work the best across all browsers and devices (PC, tables & mobile).

<script type="text/javascript">
                      function iframeLoaded() {
                          var iFrameID = document.getElementById('idIframe');
                          if(iFrameID) {
                                // here you can make the height, I delete it first, then I make it again
                                iFrameID.height = "";
                                iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
                          }   
                      }
                    </script> 


<iframe id="idIframe" onload="iframeLoaded()" frameborder="0" src="yourpage.php" height="100%" width="100%" scrolling="no"></iframe>

How can I URL encode a string in Excel VBA?

None of the solutions here worked for me out of the box, but it was most likely due my lack of experience with VBA. It might also be because I simply copied and pasted some of the functions above, not knowing details that maybe are necessary to make them work on a VBA for applications environment.

My needs were simply to send xmlhttp requests using urls that contained some special characters of the Norwegian language. Some of the solutions above encode even colons, which made the urls unsuitable for what I needed.

I then decided to write my own URLEncode function. It does not use more clever programming such as the one from @ndd and @Tom. I am not a very experienced programmer, but I had to make this done sooner.

I realized that the problem was that my server didn't accept UTF-16 encodings, so I had to write a function that would convert UTF-16 to UTF-8. A good source of information was found here and here.

I haven't tested it extensively to check if it works with url with characters that have higher unicode values and which would produce more than 2 bytes of utf-8 characters. I am not saying it will decode everything that needs to be decoded (but it is easy to modify to include/exclude characters on the select case statement) nor that it will work with higher characters, as I haven't fully tested. But I am sharing the code because it might help someone who is trying to understand the issue.

Any comments are welcome.

Public Function URL_Encode(ByVal st As String) As String

    Dim eachbyte() As Byte
    Dim i, j As Integer 
    Dim encodeurl As String
    encodeurl = "" 

    eachbyte() = StrConv(st, vbFromUnicode)

    For i = 0 To UBound(eachbyte)

        Select Case eachbyte(i)
        Case 0
        Case 32
            encodeurl = encodeurl & "%20"

        ' I am not encoding the lower parts, not necessary for me
        Case 1 To 127
            encodeurl = encodeurl & Chr(eachbyte(i))
        Case Else

            Dim myarr() As Byte
            myarr = utf16toutf8(eachbyte(i))
            For j = LBound(myarr) To UBound(myarr) - 1
                encodeurl = encodeurl & "%" & Hex(myarr(j))
            Next j
        End Select
    Next i
    URL_Encode = encodeurl 
End Function

Public Function utf16toutf8(ByVal thechars As Variant) As Variant
    Dim numbytes As Integer
    Dim byte1 As Byte
    Dim byte2 As Byte
    Dim byte3 As Byte
    Dim byte4 As Byte
    Dim byte5 As Byte 
    Dim i As Integer  
    Dim temp As Variant
    Dim stri As String

    byte1 = 0
    byte2 = byte3 = byte4 = byte5 = 128

    ' Test to see how many bytes the utf-8 char will need
    Select Case thechars
        Case 0 To 127
            numbytes = 1
        Case 128 To 2047
            numbytes = 2
        Case 2048 To 65535
            numbytes = 3
        Case 65536 To 2097152
            numbytes = 4
        Case Else
            numbytes = 5
    End Select

    Dim returnbytes() As Byte
    ReDim returnbytes(numbytes)


    If numbytes = 1 Then
        returnbytes(0) = thechars
        GoTo finish
    End If


    ' prepare the first byte
    byte1 = 192

    If numbytes > 2 Then
        For i = 3 To numbytes
            byte1 = byte1 / 2
            byte1 = byte1 + 128
        Next i
    End If
    temp = 0
    stri = ""
    If numbytes = 5 Then
        temp = thechars And 63

        byte5 = temp + 128
        returnbytes(4) = byte5
        thechars = thechars / 12
        stri = byte5
    End If

    If numbytes >= 4 Then

        temp = 0
        temp = thechars And 63
        byte4 = temp + 128
        returnbytes(3) = byte4
        thechars = thechars / 12
        stri = byte4 & stri
    End If

    If numbytes >= 3 Then

        temp = 0
        temp = thechars And 63
        byte3 = temp + 128
        returnbytes(2) = byte3
        thechars = thechars / 12
        stri = byte3 & stri
    End If

    If numbytes >= 2 Then

        temp = 0
        temp = thechars And 63
        byte2 = temp Or 128
        returnbytes(1) = byte2
        thechars = Int(thechars / (2 ^ 6))
        stri = byte2 & stri
    End If

    byte1 = thechars Or byte1
    returnbytes(0) = byte1

    stri = byte1 & stri

    finish:
       utf16toutf8 = returnbytes()
End Function

Clearing the terminal screen?

ESC is the character _2_7, not _1_7. You can also try decimal 12 (aka. FF, form feed).

Note that all these special characters are not handled by the Arduino but by the program on the receiving side. So a standard Unix terminal (xterm, gnome-terminal, kterm, ...) handles a different set of control sequences then say a Windows terminal program like HTerm.

Therefore you should specify what program you are using exactly for display. After that it is possible to tell you what control characters and control sequences are usable.

Should I use the datetime or timestamp data type in MySQL?

Depends on application, really.

Consider setting a timestamp by a user to a server in New York, for an appointment in Sanghai. Now when the user connects in Sanghai, he accesses the same appointment timestamp from a mirrored server in Tokyo. He will see the appointment in Tokyo time, offset from the original New York time.

So for values that represent user time like an appointment or a schedule, datetime is better. It allows the user to control the exact date and time desired, regardless of the server settings. The set time is the set time, not affected by the server's time zone, the user's time zone, or by changes in the way daylight savings time is calculated (yes it does change).

On the other hand, for values that represent system time like payment transactions, table modifications or logging, always use timestamps. The system will not be affected by moving the server to another time zone, or when comparing between servers in different timezones.

Timestamps are also lighter on the database and indexed faster.

Understanding Apache's access log

You seem to be using the combined log format.

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" combined

  • %h is the remote host (ie the client IP)
  • %l is the identity of the user determined by identd (not usually used since not reliable)
  • %u is the user name determined by HTTP authentication
  • %t is the time the request was received.
  • %r is the request line from the client. ("GET / HTTP/1.0")
  • %>s is the status code sent from the server to the client (200, 404 etc.)
  • %b is the size of the response to the client (in bytes)
  • Referer is the Referer header of the HTTP request (containing the URL of the page from which this request was initiated) if any is present, and "-" otherwise.
  • User-agent is the browser identification string.

The complete(?) list of formatters can be found here. The same section of the documentation also lists other common log formats; readers whose logs don't look quite like this one may find the pattern their Apache configuration is using listed there.

Java URLConnection Timeout

You can set timeouts for all connections made from the jvm by changing the following System-properties:

System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
System.setProperty("sun.net.client.defaultReadTimeout", "10000");

Every connection will time out after 10 seconds.

Setting 'defaultReadTimeout' is not needed, but shown as an example if you need to control reading.

Show/Hide Multiple Divs with Jquery

_x000D_
_x000D_
jQuery(function() {_x000D_
  jQuery('#showall').click(function() {_x000D_
    jQuery('.targetDiv').show();_x000D_
  });_x000D_
  jQuery('.showSingle').click(function() {_x000D_
    jQuery('.targetDiv').hide();_x000D_
    jQuery('#div' + $(this).attr('target')).show();_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="buttons">_x000D_
  <a id="showall">All</a>_x000D_
  <a class="showSingle" target="1">Div 1</a>_x000D_
  <a class="showSingle" target="2">Div 2</a>_x000D_
  <a class="showSingle" target="3">Div 3</a>_x000D_
  <a class="showSingle" target="4">Div 4</a>_x000D_
</div>_x000D_
_x000D_
<div id="div1" class="targetDiv">Lorum Ipsum1</div>_x000D_
<div id="div2" class="targetDiv">Lorum Ipsum2</div>_x000D_
<div id="div3" class="targetDiv">Lorum Ipsum3</div>_x000D_
<div id="div4" class="targetDiv">Lorum Ipsum4</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/XwN2L/

Regular expression to find two strings anywhere in input

(.* word1.* word2.* )|(.* word2.* word1.*)

Conversion failed when converting from a character string to uniqueidentifier - Two GUIDs

DECLARE @t TABLE (ID UNIQUEIDENTIFIER DEFAULT NEWID(),myid UNIQUEIDENTIFIER
                , friendid UNIQUEIDENTIFIER, time1 Datetime, time2 Datetime)
insert into @t (myid,friendid,time1,time2) 
values
 ( CONVERT(uniqueidentifier,'0C6A36BA-10E4-438F-BA86-0D5B68A2BB15'),
   CONVERT(uniqueidentifier,'DF215E10-8BD4-4401-B2DC-99BB03135F2E'),
   '2014-01-05 02:04:41.953','2014-01-05 12:04:41.953')

SELECT * FROM @t

Result Set With out any errors

+------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
¦                  ID                  ¦                 myid                 ¦               friendid               ¦          time1          ¦          time2          ¦
¦--------------------------------------+--------------------------------------+--------------------------------------+-------------------------+-------------------------¦
¦ CF628202-33F3-49CF-8828-CB2D93C69675 ¦ 0C6A36BA-10E4-438F-BA86-0D5B68A2BB15 ¦ DF215E10-8BD4-4401-B2DC-99BB03135F2E ¦ 2014-01-05 02:04:41.953 ¦ 2014-01-05 12:04:41.953 ¦
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

SQL Server equivalent of MySQL's NOW()?

getdate() or getutcdate().

Redirect non-www to www in .htaccess

Here's the correct solution which supports https and http:

# Redirect to www
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

UPD.: for domains like .co.uk, replace

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$

with

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+\.[^.]+$

Changing Background Image with CSS3 Animations

I needed to do the same thing as you and landed on your question. I ended up taking finding about the steps function which I read about from here.

JSFiddle of my solution in action (Note it currently works in Firefox, I'll let you add the crossbrowser lines, trying to keep the solution clean of clutter)

First I created a sprite sheet that had two frames. Then I created the div and put that as the background, but my div is only the size of my sprite (100px).

<div id="cyclist"></div>

#cyclist {
    animation: cyclist 1s infinite steps(2);
    display: block;
    width: 100px;
    height: 100px;
    background-image: url('../images/cyclist-test.png');
    background-repeat: no-repeat;
    background-position: top left;
  }

The animation is set to have 2 steps and have the whole process take 1 second.

@keyframes cyclist {
  0% {
    background-position: 0 0; 
   }
  100% { 
    background-position: 0 -202px; //this should be cleaned up, my sprite sheet is 202px by accident, it should be 200px
   }
}

Thiago above mentioned the steps function but I thought I'd elaborate more on it. Pretty simple and awesome stuff.

How to programmatically set style attribute in a view

I made a helper interface for this using the holder pattern.

public interface StyleHolder<V extends View> {
    void applyStyle(V view);
}

Now for every style you want to use pragmatically just implement the interface, for example:

public class ButtonStyleHolder implements StyleHolder<Button> {

    private final Drawable background;
    private final ColorStateList textColor;
    private final int textSize;

    public ButtonStyleHolder(Context context) {
        TypedArray ta = context.obtainStyledAttributes(R.style.button, R.styleable.ButtonStyleHolder);

        Resources resources = context.getResources();

        background = ta.getDrawable(ta.getIndex(R.styleable.ButtonStyleHolder_android_background));

        textColor = ta.getColorStateList(ta.getIndex(R.styleable.ButtonStyleHolder_android_textColor));

        textSize = ta.getDimensionPixelSize(
                ta.getIndex(R.styleable.ButtonStyleHolder_android_textSize),
                resources.getDimensionPixelSize(R.dimen.standard_text_size)
        );

        // Don't forget to recycle!
        ta.recycle();
    }

    @Override
    public void applyStyle(Button btn) {
        btn.setBackground(background);
        btn.setTextColor(textColor);
        btn.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
    }
}

Declare a stylable in your attrs.xml, the styleable for this example is:

<declare-styleable name="ButtonStyleHolder">
    <attr name="android:background" />
    <attr name="android:textSize" />
    <attr name="android:textColor" />
</declare-styleable>

Here is the style declared in styles.xml:

<style name="button">
    <item name="android:background">@drawable/button</item>
    <item name="android:textColor">@color/light_text_color</item>
    <item name="android:textSize">@dimen/standard_text_size</item>
</style>

And finally the implementation of the style holder:

Button btn = new Button(context);    
StyleHolder<Button> styleHolder = new ButtonStyleHolder(context);
styleHolder.applyStyle(btn);

I found this very helpful as it can be easily reused and keeps the code clean and verbose, i would recommend using this only as a local variable so we can allow the garbage collector to do its job once we're done with setting all the styles.

Get latitude and longitude automatically using php, API

I think allow_url_fopen on your apache server is disabled. you need to trun it on.

kindly change allow_url_fopen = 0 to allow_url_fopen = 1

Don't forget to restart your Apache server after changing it.

How to count TRUE values in a logical vector

I've just had a particular problem where I had to count the number of true statements from a logical vector and this worked best for me...

length(grep(TRUE, (gene.rep.matrix[i,1:6] > 1))) > 5

So This takes a subset of the gene.rep.matrix object, and applies a logical test, returning a logical vector. This vector is put as an argument to grep, which returns the locations of any TRUE entries. Length then calculates how many entries grep finds, thus giving the number of TRUE entries.

How to allow user to pick the image with Swift?

In Swift 5 you have to do this

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet var imageView: UIImageView!
    var imagePicker = UIImagePickerController()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func setPicture(_ sender: Any) {
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            imagePicker.delegate = self
            imagePicker.sourceType = .photoLibrary
            imagePicker.allowsEditing = false

            present(imagePicker, animated: true, completion: nil)
        }
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            imageView.image = image
        }

    }




}

Change font-weight of FontAwesome icons?

Webkit browsers support the ability to add "stroke" to fonts. This bit of style makes fonts look thinner (assuming a white background):

-webkit-text-stroke: 2px white;

Example on codepen here: http://codepen.io/mackdoyle/pen/yrgEH Some people are using SVG for a cross-platform "stroke" solution: http://codepen.io/CrocoDillon/pen/dGIsK

Sorting list based on values from another list

You can create a pandas Series, using the primary list as data and the other list as index, and then just sort by the index:

import pandas as pd
pd.Series(data=X,index=Y).sort_index().tolist()

output:

['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

How to get directory size in PHP

There are several things you could do to optimise the script - but maximum success would make it IO-bound rather than CPU-bound:

  1. Calculate rtrim($path, '/') outside the loop.
  2. make if ($t<>"." && $t<>"..") the outer test - it doesn't need to stat the path
  3. Calculate rtrim($path, '/') . '/' . $t once per loop - inside 2) and taking 1) into account.
  4. Calculate explode(' ','B KB MB GB TB PB'); once rather than each call?

Get all parameters from JSP page

This should print out all Parameters that start with "Question".

<html><body>
<%@ page import = "java.util.*" %>
<b>Parameters:</b><br>
<%
  Enumeration parameterList = request.getParameterNames();
  while( parameterList.hasMoreElements() )
  {
    String sName = parameterList.nextElement().toString();
    if(sName.toLowerCase.startsWith("question")){
      String[] sMultiple = request.getParameterValues( sName );
      if( 1 >= sMultiple.length )
        // parameter has a single value. print it.
        out.println( sName + " = " + request.getParameter( sName ) + "<br>" );
      else
        for( int i=0; i<sMultiple.length; i++ )
          // if a paramater contains multiple values, print all of them
          out.println( sName + "[" + i + "] = " + sMultiple[i] + "<br>" );
    }
  }
%>
</body></html>

Div side by side without float

The usual method when not using floats is to use display: inline-block: http://www.jsfiddle.net/zygnz/1/

.container div {
  display: inline-block;
}

Do note its limitations though: There is a additional space after the first bloc - this is because the two blocks are now essentially inline elements, like a and em, so whitespace between the two counts. This could break your layout and/or not look nice, and I'd prefer not to strip out all whitespaces between characters for the sake of this working.

Floats are also more flexible, in most cases.

How to get the browser viewport dimensions?

A solution that would conform to W3C standards would be to create a transparent div (for example dynamically with JavaScript), set its width and height to 100vw/100vh (Viewport units) and then get its offsetWidth and offsetHeight. After that, the element can be removed again. This will not work in older browsers because the viewport units are relatively new, but if you don't care about them but about (soon-to-be) standards instead, you could definitely go this way:

var objNode = document.createElement("div");
objNode.style.width  = "100vw";
objNode.style.height = "100vh";
document.body.appendChild(objNode);
var intViewportWidth  = objNode.offsetWidth;
var intViewportHeight = objNode.offsetHeight;
document.body.removeChild(objNode);

Of course, you could also set objNode.style.position = "fixed" and then use 100% as width/height - this should have the same effect and improve compatibility to some extent. Also, setting position to fixed might be a good idea in general, because otherwise the div will be invisible but consume some space, which will lead to scrollbars appearing etc.

Why my regexp for hyphenated words doesn't work?

A couple of things:

  1. Your regexes need to be anchored by separators* or you'll match partial words, as is the case now
  2. You're not using the proper syntax for a non-capturing group. It's (?: not (:?

If you address the first problem, you won't need groups at all.

*That is, a blank or beginning/end of string.

How do I parse JSON from a Java HTTPResponse?

Two things which can be done more efficiently:

  1. Use StringBuilder instead of StringBuffer since it's the faster and younger brother.
  2. Use BufferedReader#readLine() to read it line by line instead of reading it char by char.

HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
    builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);

If the JSON is actually a single line, then you can also remove the loop and builder.

HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONArray finalResult = new JSONArray(tokener);

Triangle Draw Method

You can use Processing library: https://processing.org/reference/PGraphics.html

There is a method called triangle():

g.triangle(x1,y1,x2,y2,x3,y3)

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

It appears to me that the simplest way to do this is

import datetime

epoch = datetime.datetime.utcfromtimestamp(0)

def unix_time_millis(dt):
    return (dt - epoch).total_seconds() * 1000.0

C# "as" cast vs classic cast

I suppose it is useful if the result of the cast will be passed to a method that you know will handle null references without throwing and ArgumentNullException or suchlike.

I tend to find very little use for as, since:

obj as T

Is slower than:

if (obj is T)
    ...(T)obj...

The use of as is very much an edge-case scenario for me, so I can't think of any general rules for when I would use it over just casting and handling the (more informative) casting exception further up the stack.

How to retrieve all keys (or values) from a std::map and put them into a vector?

C++0x has given us a further, excellent solution:

std::vector<int> keys;

std::transform(
    m_Inputs.begin(),
    m_Inputs.end(),
    std::back_inserter(keys),
    [](const std::map<int,int>::value_type &pair){return pair.first;});

How can I show a message box with two buttons?

You probably want to do something like this:

result = MsgBox ("Yes or No?", vbYesNo, "Yes No Example")

Select Case result
Case vbYes
    MsgBox("You chose Yes")
Case vbNo
    MsgBox("You chose No")
End Select

To add an icon:

result = MsgBox ("Yes or No?", vbYesNo + vbQuestion, "Yes No Example")

Other icon options:

vbCritical or vbExclamation

How to use the unsigned Integer in Java 8 and Java 9?

Per the documentation you posted, and this blog post - there's no difference when declaring the primitive between an unsigned int/long and a signed one. The "new support" is the addition of the static methods in the Integer and Long classes, e.g. Integer.divideUnsigned. If you're not using those methods, your "unsigned" long above 2^63-1 is just a plain old long with a negative value.

From a quick skim, it doesn't look like there's a way to declare integer constants in the range outside of +/- 2^31-1, or +/- 2^63-1 for longs. You would have to manually compute the negative value corresponding to your out-of-range positive value.

Validating Phone Numbers Using Javascript

<!DOCTYPE html>
<html>
    <head>
        <style>
           .container__1{
               max-width: 450px;
               font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
           }
           .container__1 label{
               display: block;
               margin-bottom: 10px;
           }
           .container__1 label > span{
               float: left;
               width: 100px;
               color: #F072A9;
               font-weight: bold;
               font-size: 13px;
               text-shadow: 1px 1px 1px #fff;
           }
           .container__1 fieldset{
               border-radius: 10px;
               -webkit-border-radious:10px;
               -moz-border-radoius: 10px;
               margin: 0px 0px 0px 0px;
               border: 1px solid #FFD2D2;
               padding: 20px;
               background:#FFF4F4 ;
               box-shadow: inset 0px 0px 15px #FFE5E5;


           }
           .container__1 fieldset legend{
               color: #FFA0C9;
               border-top: 1px solid #FFD2D2 ;
               border-left: 1px solid #FFD2D2 ;
               border-right: 1px solid #FFD2D2 ;
               border-radius: 5px 5px 0px 0px;
               background: #FFF4F4;
               padding: 0px 8px 3px 8px;
               box-shadow: -0px -1px 2px #F1F1F1;
               font-weight: normal;
               font-size: 12px;
           }
           .container__1 textarea{
               width: 250px;
               height: 100px;
           }.container__1 input[type=text],
           .container__1 input[type=email],
           .container__1 select{
               border-radius: 3px;
               border: 1px solid #FFC2DC;
               outline: none;
               color: #F072A9;
               padding: 5px 8px 5px 8px;
               box-shadow: inset 1px 1px 4px #FFD5E7;
               background: #FFEFF6;
               

           }
           .container__1 input[type=submit],
           .container__1 input[type=button]{
               background: #EB3B88;
               border: 1px solid #C94A81;
               padding: 5px 15px 5px 15px;
               color: #FFCBE2;
               box-shadow: inset -1px -1px 3px #FF62A7;
               border-radius: 3px;
               font-weight: bold;
           }
           .required{
               color: red;
           }
        </style>
    </head>
    <body>
        <div class="container__1">
            <form name="RegisterForm" onsubmit="return(SubmitClick())">
                <fieldset>
                    <legend>Personal</legend>
                    <label for="field1"><span >Name<span class="required">*</span><input id="name" type="text" class="input-field" name="Name" value=""</label>
                    <label for="field2"><span >Email<span class="required">*</span><input placeholder="Ex: [email protected]" id="email" type="email" class="input-field" name="Email" value=""</label>
                    <label for="field3"><span >Phone<span class="required">*</span><input placeholder="+919853004369" id="mobile" type="text" class="input-field" name="Mobile" value=""</label>
                    <label for="field4">
                        <span>Subject</span>
                        <select name="subject" id="subject" class="select-field">
                            <option value="none">Choose Your Sub..</option>
                            <option value="Appointment">Appiontment</option>
                            <option value="Interview">Interview</option>
                            <option value="Regarding a post">Regarding a post</option>
                        </select>
                    </label>
                    <label><span></span><input type="submit"  ></label>
                </fieldset>
            </form>
        </div>
    </body>
    <script>
        function SubmitClick(){
        _name = document.querySelector('#name').value;
        _email = document.querySelector('#email').value;
        _mobile = document.querySelector('#mobile').value;
        _subject = document.querySelector('#subject').value;
          if(_name == '' || _name == null ){
              alert('Enter Your Name');
              document.RegisterForm.Name.focus();
              return false; 
          } 
          var atPos = _email.indexOf('@');
         var dotPos = _email.lastIndexOf('.');

          if(_email == '' || atPos<1 || (dotPos - atPos)<2){
              alert('Provide Your Correct Email address');
              document.RegisterForm.Email.focus();
              return false;
          }
          var regExp = /^\+91[0-9]{10}$/;
          if(_mobile == '' || !regExp.test(_mobile)){
              alert('Please Provide your Mobile number as Ex:- +919853004369');
              document.RegisterForm.Mobile.focus();
              return false;
          }
          if(_subject == 'none'){
              alert('Please choose a subject');
              document.RegisterForm.subject.focus();
              return false;
          }else{
            alert (`success!!!:--'\n'Name:${_name},'\n' Mobile: ${_mobile},'\n' Email:${_email},'\n' Subject:${_subject},`)
          }
        
          
        }
    </script>
</html>

How to upload multiple files using PHP, jQuery and AJAX

My solution

  • Assuming that form id = "my_form_id"
  • It detects the form method and form action from HTML

jQuery code

$('#my_form_id').on('submit', function(e) {
    e.preventDefault();
    var formData = new FormData($(this)[0]);
    var msg_error = 'An error has occured. Please try again later.';
    var msg_timeout = 'The server is not responding';
    var message = '';
    var form = $('#my_form_id');
    $.ajax({
        data: formData,
        async: false,
        cache: false,
        processData: false,
        contentType: false,
        url: form.attr('action'),
        type: form.attr('method'),
        error: function(xhr, status, error) {
            if (status==="timeout") {
                alert(msg_timeout);
            } else {
                alert(msg_error);
            }
        },
        success: function(response) {
            alert(response);
        },
        timeout: 7000
    });
});

View a file in a different Git branch without changing branches

If you're using Emacs, you can type C-x v ~ to see a different revision of the file you're currently editing (tags, branches and hashes all work).

Where can I find MySQL logs in phpMyAdmin?

In phpMyAdmin 4.0, you go to Status > Monitor. In there you can enable the slow query log and general log, see a live monitor, select a portion of the graph, see the related queries and analyse them.

Apache Spark: map vs mapPartitions?

Imp. TIP :

Whenever you have heavyweight initialization that should be done once for many RDD elements rather than once per RDD element, and if this initialization, such as creation of objects from a third-party library, cannot be serialized (so that Spark can transmit it across the cluster to the worker nodes), use mapPartitions() instead of map(). mapPartitions() provides for the initialization to be done once per worker task/thread/partition instead of once per RDD data element for example : see below.

val newRd = myRdd.mapPartitions(partition => {
  val connection = new DbConnection /*creates a db connection per partition*/

  val newPartition = partition.map(record => {
    readMatchingFromDB(record, connection)
  }).toList // consumes the iterator, thus calls readMatchingFromDB 

  connection.close() // close dbconnection here
  newPartition.iterator // create a new iterator
})

Q2. does flatMap behave like map or like mapPartitions?

Yes. please see example 2 of flatmap.. its self explanatory.

Q1. What's the difference between an RDD's map and mapPartitions

map works the function being utilized at a per element level while mapPartitions exercises the function at the partition level.

Example Scenario : if we have 100K elements in a particular RDD partition then we will fire off the function being used by the mapping transformation 100K times when we use map.

Conversely, if we use mapPartitions then we will only call the particular function one time, but we will pass in all 100K records and get back all responses in one function call.

There will be performance gain since map works on a particular function so many times, especially if the function is doing something expensive each time that it wouldn't need to do if we passed in all the elements at once(in case of mappartitions).

map

Applies a transformation function on each item of the RDD and returns the result as a new RDD.

Listing Variants

def map[U: ClassTag](f: T => U): RDD[U]

Example :

val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)
 val b = a.map(_.length)
 val c = a.zip(b)
 c.collect
 res0: Array[(String, Int)] = Array((dog,3), (salmon,6), (salmon,6), (rat,3), (elephant,8)) 

mapPartitions

This is a specialized map that is called only once for each partition. The entire content of the respective partitions is available as a sequential stream of values via the input argument (Iterarator[T]). The custom function must return yet another Iterator[U]. The combined result iterators are automatically converted into a new RDD. Please note, that the tuples (3,4) and (6,7) are missing from the following result due to the partitioning we chose.

preservesPartitioning indicates whether the input function preserves the partitioner, which should be false unless this is a pair RDD and the input function doesn't modify the keys.

Listing Variants

def mapPartitions[U: ClassTag](f: Iterator[T] => Iterator[U], preservesPartitioning: Boolean = false): RDD[U]

Example 1

val a = sc.parallelize(1 to 9, 3)
 def myfunc[T](iter: Iterator[T]) : Iterator[(T, T)] = {
   var res = List[(T, T)]()
   var pre = iter.next
   while (iter.hasNext)
   {
     val cur = iter.next;
     res .::= (pre, cur)
     pre = cur;
   }
   res.iterator
 }
 a.mapPartitions(myfunc).collect
 res0: Array[(Int, Int)] = Array((2,3), (1,2), (5,6), (4,5), (8,9), (7,8)) 

Example 2

val x = sc.parallelize(List(1, 2, 3, 4, 5, 6, 7, 8, 9,10), 3)
 def myfunc(iter: Iterator[Int]) : Iterator[Int] = {
   var res = List[Int]()
   while (iter.hasNext) {
     val cur = iter.next;
     res = res ::: List.fill(scala.util.Random.nextInt(10))(cur)
   }
   res.iterator
 }
 x.mapPartitions(myfunc).collect
 // some of the number are not outputted at all. This is because the random number generated for it is zero.
 res8: Array[Int] = Array(1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 7, 7, 7, 9, 9, 10) 

The above program can also be written using flatMap as follows.

Example 2 using flatmap

val x  = sc.parallelize(1 to 10, 3)
 x.flatMap(List.fill(scala.util.Random.nextInt(10))(_)).collect

 res1: Array[Int] = Array(1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10) 

Conclusion :

mapPartitions transformation is faster than map since it calls your function once/partition, not once/element..

Further reading : foreach Vs foreachPartitions When to use What?

How to make an autocomplete TextBox in ASP.NET?

aspx Page Coding

<form id="form1" runat="server">
       <input type="search" name="Search" placeholder="Search for a Product..." list="datalist1"
                    required="">
       <datalist id="datalist1" runat="server">

       </datalist>
 </form>

.cs Page Coding

protected void Page_Load(object sender, EventArgs e)
{
     autocomplete();
}
protected void autocomplete()
{
    Database p = new Database();
    DataSet ds = new DataSet();
    ds = p.sqlcall("select [name] from [stu_reg]");
    int row = ds.Tables[0].Rows.Count;
    string abc="";
    for (int i = 0; i < row;i++ )
        abc = abc + "<option>"+ds.Tables[0].Rows[i][0].ToString()+"</option>";
    datalist1.InnerHtml = abc;
}

Here Database is a File (Database.cs) In Which i have created on method named sqlcall for retriving data from database.

Windows service with timer

You need to put your main code on the OnStart method.

This other SO answer of mine might help.

You will need to put some code to enable debugging within visual-studio while maintaining your application valid as a windows-service. This other SO thread cover the issue of debugging a windows-service.

EDIT:

Please see also the documentation available here for the OnStart method at the MSDN where one can read this:

Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.

Omitting the first line from any Linux command output

Pipe it to awk:

awk '{if(NR>1)print}'

or sed

sed -n '1!p'

align images side by side in html

Try this.

CSS

.imageContainer {
    float: left;
}

p {
    text-align: center;
}

HTML

<div class="image123">
    <div class="imageContainer">
        <img src="/images/tv.gif" height="200" width="200" />
        <p>This is image 1</p>
    </div>
    <div class="imageContainer">
        <img class="middle-img" src="/images/tv.gif"/ height="200" width="200" />
        <p>This is image 2</p>
    </div>
    <div class="imageContainer">    
        <img src="/images/tv.gif"/ height="200" width="200"/>
        <p>This is image 3</p>
    </div>
</div>

Hide axis values but keep axis tick labels in matplotlib

plt.gca().axes.yaxis.set_ticklabels([])

enter image description here

HttpWebRequest-The remote server returned an error: (400) Bad Request

What type of authentication do you use? Send the credentials using the properties Ben said before and setup a cookie handler. You already allow redirection, check your webserver if any redirection occurs (NTLM auth does for sure). If there is a redirection you need to store the session which is mostly stored in a session cookie.

How to var_dump variables in twig templates?

Dump all custom variables:

<h1>Variables passed to the view:</h1>
{% for key, value in _context %}
    {% if key starts with '_' %}
    {% else %}
        <pre style="background: #eee">{{ key }}</pre>
        {{ dump(value) }}
    {% endif %}
{% endfor %}

You can use my plugin which will do that for you (an will nicely format the output):

Twig Dump Bar

How to read .pem file to get private and public key

I think in your private key definition, You should replace:

X509EncodedKeySpec spec = new X509EncodedKeySpec(decoded);

with:

PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);

Look your openssl command:

$openssl **pkcs8** -topk8 -inform PEM -outform PEM -in mykey.pem \ -out private_key.pem -nocrypt

And the java Exception:

Only PCKS8 codification 

tsc is not recognized as internal or external command

Me too faced the same problem. Use nodeJS command prompt instead of windows command prompt.

Step 1: Execute the npm install -g typescript

Step 2: tsc filename.ts

New file will be create same name and different extension as ".js"

Step 3: node filename.js

You can see output in screen. It works for me.

How to pass command line argument to gnuplot?

Yet another way is this:

You have a gnuplot script named scriptname.gp:

#!/usr/bin/gnuplot -p
# This code is in the file 'scriptname.gp'
EPATH = $0
FILENAME = $1 

plot FILENAME

Now you can call the gnuplot script scriptname.gp by this convoluted peace of syntax:

echo "call \"scriptname.gp\" \"'.'\" \"'data.dat'\"" | gnuplot 

ADB Install Fails With INSTALL_FAILED_TEST_ONLY

I don't know if it's gonna be useful for anyone or not, but I got this error message, when I accidentally tried to build and install my project with test gradle plugin ('gradle:2.4.0-alpha5') version in stable Android Studio version (2.3, not in 2.4 preview 5 version I'd downloaded and installed before).

When I realized my mistake, I launched preview Android Studio version and it built and installed my project without any problem.

Find Item in ObservableCollection without using a loop

Well if you have N objects and you need to get the Title of all of them you have to use a loop. If you only need the title and you really want to improve this, maybe you can make a separated array containing only the title, this would improve the performance. You need to define the amount of memory available and the amount of objects that you can handle before saying this can damage the performance, and in any case the solution would be changing the design of the program not the algorithm.

Installing Python 2.7 on Windows 8

Easiest way is to open CMD or powershell as administrator and type

set PATH=%PATH%;C:\Python27

Jquery UI tooltip does not support html content

You may modify the source code 'jquery-ui.js' , find this default function for retrieving target element's title attribute content.

var tooltip = $.widget( "ui.tooltip", {
version: "1.11.4",
options: {
    content: function() {
        // support: IE<9, Opera in jQuery <1.7
        // .text() can't accept undefined, so coerce to a string
        var title = $( this ).attr( "title" ) || "";
        // Escape title, since we're going from an attribute to raw HTML
        return $( "<a>" ).text( title ).html();
    },

change it to

var tooltip = $.widget( "ui.tooltip", {
version: "1.11.4",
options: {
    content: function() {
        // support: IE<9, Opera in jQuery <1.7
        // .text() can't accept undefined, so coerce to a string
        if($(this).attr('ignoreHtml')==='false'){
            return $(this).prop("title");
        }
        var title = $( this ).attr( "title" ) || "";
        // Escape title, since we're going from an attribute to raw HTML
        return $( "<a>" ).text( title ).html();
    },

thus whenever you want to display html tips , just add an attribute ignoreHtml='false' on your target html element; like this <td title="<b>display content</b><br/>other" ignoreHtml='false'>display content</td>

Array initialization syntax when not in a declaration

Why is this blocked by Java?

You'd have to ask the Java designers. There might be some subtle grammatical reason for the restriction. Note that some of the array creation / initialization constructs were not in Java 1.0, and (IIRC) were added in Java 1.1.

But "why" is immaterial ... the restriction is there, and you have to live with it.

I know how to work around it, but from time to time it would be simpler.

You can write this:

AClass[] array;
...
array = new AClass[]{object1, object2};

Python class input argument

The problem in your initial definition of the class is that you've written:

class name(object, name):

This means that the class inherits the base class called "object", and the base class called "name". However, there is no base class called "name", so it fails. Instead, all you need to do is have the variable in the special init method, which will mean that the class takes it as a variable.

class name(object):
  def __init__(self, name):
    print name

If you wanted to use the variable in other methods that you define within the class, you can assign name to self.name, and use that in any other method in the class without needing to pass it to the method.

For example:

class name(object):
  def __init__(self, name):
    self.name = name
  def PrintName(self):
    print self.name

a = name('bob')
a.PrintName()
bob

move_uploaded_file gives "failed to open stream: Permission denied" error

This problem happens when the apache user (www-data) does not have permission to write in the folder. To solver this problem you need to put the user inside the group www-data.

I just made this:

Execute this php code <?php echo exec('whoami'); ?> to discover the user used by apache. After, execute the commands in the terminal:

user@machine:/# cd /var/www/html

user@machine:/var/www/html# ls -l

It will return something like this:

total of files

drwxr-xr-x 7 user group size date folder

I kept the user but changed the group to www-data

chown -R user:www-data yourprojectfoldername

chmod 775 yourprojectfoldername

getOutputStream() has already been called for this response

Ok, you should be using a servlet not a JSP but if you really need to... add this directive at the top of your page:

<%@ page trimDirectiveWhitespaces="true" %>

Or in the jsp-config section your web.xml

<jsp-config>
  <jsp-property-group>
    <url-pattern>*.jsp</url-pattern>
    <trim-directive-whitespaces>true</trim-directive-whitespaces>
  </jsp-property-group>
</jsp-config>

Also flush/close the OutputStream and return when done.

dataOutput.flush();
dataOutput.close();
return;

How do I show my global Git configuration?

You can also use cat ~/.gitconfig.

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

Or just use this in your View(Razor page)

@item.ResgistrationhaseDate.ToString(string.Format("dd/MM/yyyy"))

I recommend that don't add date format in your model class

Fixed Table Cell Width

You could try using the <col> tag manage table styling for all rows but you will need to set the table-layout:fixed style on the <table> or the tables css class and set the overflow style for the cells

http://www.w3schools.com/TAGS/tag_col.asp

<table class="fixed">
    <col width="20px" />
    <col width="30px" />
    <col width="40px" />
    <tr>
        <td>text</td>
        <td>text</td>
        <td>text</td>
    </tr>
</table>

and this be your CSS

table.fixed { table-layout:fixed; }
table.fixed td { overflow: hidden; }

How to install all required PHP extensions for Laravel?

Laravel Server Requirements mention that BCMath, Ctype, JSON, Mbstring, OpenSSL, PDO, Tokenizer, and XML extensions are required. Most of the extensions are installed and enabled by default.

You can run the following command in Ubuntu to make sure the extensions are installed.

sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip

PHP version specific installation (if PHP 7.4 installed)

sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring

You may need other PHP extensions for your composer packages. Find from links below.

PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)

PHP extensions for Ubuntu 18.04 LTS (Bionic)

PHP extensions for Ubuntu 16.04 LTS (Xenial)

Iterating each character in a string using Python

Well you can also do something interesting like this and do your job by using for loop

#suppose you have variable name
name = "Mr.Suryaa"
for index in range ( len ( name ) ):
    print ( name[index] ) #just like c and c++ 

Answer is

M r . S u r y a a

However since range() create a list of the values which is sequence thus you can directly use the name

for e in name:
    print(e)

This also produces the same result and also looks better and works with any sequence like list, tuple, and dictionary.

We have used tow Built in Functions ( BIFs in Python Community )

1) range() - range() BIF is used to create indexes Example

for i in range ( 5 ) :
can produce 0 , 1 , 2 , 3 , 4

2) len() - len() BIF is used to find out the length of given string

PHP & localStorage;

localStorage is something that is kept on the client side. There is no data transmitted to the server side.

You can only get the data with JavaScript and you can send it to the server side with Ajax.

What can be the reasons of connection refused errors?

1.Check your server status.

2.Check the port status.

For example 3306 netstat -nupl|grep 3306.

3.Check your firewalls. For example add 3306

vim /etc/sysconfig/iptables
# add
-A INPUT -p tcp -m state --state NEW -m tcp --dport 3306 -j ACCEPT

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:

HTML

<div class="abc"></div>
<div class="abc"></div>

JS

var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div');
div.id = 'hello1';

var body = document.querySelector('body');
body.appendChild(div);

Update

You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0];
    s.id = btoa({{str(produit["avt"]["fto"])}});
</script>

Your requirements still aren't 100% clear though.

Decreasing for loops in Python impossible?

for n in range(6,0,-1):
    print n

Objective-C - Remove last character from string

If it's an NSMutableString (which I would recommend since you're changing it dynamically), you can use:

[myString deleteCharactersInRange:NSMakeRange([myRequestString length]-1, 1)];

How to change onClick handler dynamically?

The YUI example above should really be:

<script>
  YAHOO.util.Event.onDOMReady(function() {   
     Dom.get("foo").onclick =  function (){alert('foo');};
  });
</script>

Check if an apt-get package is installed and then install it if it's not on Linux

This explicitly prints 0 if installed else 1 using only awk:

dpkg-query -W -f '${Status}\n' 'PKG' 2>&1|awk '/ok installed/{print 0;exit}{print 1}'

or if you prefer the other way around where 1 means installed and 0 otherwise:

dpkg-query -W -f '${Status}\n' 'PKG' 2>&1|awk '/ok installed/{print 1;exit}{print 0}'

** replace PKG with your package name

Convenience function:

installed() {
    return $(dpkg-query -W -f '${Status}\n' "${1}" 2>&1|awk '/ok installed/{print 0;exit}{print 1}')
}


# usage:
installed gcc && echo Yes || echo No

#or

if installed gcc; then
    echo yes
else
    echo no
fi

JavaFX - create custom button with image

You just need to create your own class inherited from parent. Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.

public class ImageButton extends Parent {

    private static final Image NORMAL_IMAGE = ...;
    private static final Image PRESSED_IMAGE = ...;

    private final ImageView iv;

    public ImageButton() {
        this.iv = new ImageView(NORMAL_IMAGE);
        this.getChildren().add(this.iv);

        this.iv.setOnMousePressed(new EventHandler<MouseEvent>() {

            public void handle(MouseEvent evt) {
                iv.setImage(PRESSED_IMAGE);
            }

        });

        // TODO other event handlers like mouse up

    } 

}

How to make child divs always fit inside parent div?

you could use inherit

#one {width:500px;height:300px;}
#two {width:inherit;height:inherit;}
#three {width:inherit;height:inherit;}

AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

I had similar issue, trying to load data from Excel spreadsheet; and was running on WinX64. So I went VS BI`s project properties: Configuration Properties \ Dbugging and Switch Run64BitRuntime from True to False. It worked.

Ajax - 500 Internal Server Error

I think your return string data is very long. so the JSON format has been corrupted. You should change the max size for JSON data in this way :

Open the Web.Config file and paste these lines into the configuration section

<system.web.extensions>
  <scripting>
    <webServices>
      <jsonSerialization maxJsonLength="50000000"/>
    </webServices>
  </scripting>
</system.web.extensions>

Number to String in a formula field

I believe this is what you're looking for:

Convert Decimal Numbers to Text showing only the non-zero decimals

Especially this line might be helpful:

StringVar text     :=  Totext ( {Your.NumberField} , 6 , ""  )  ;

The first parameter is the decimal to be converted, the second parameter is the number of decimal places and the third parameter is the separator for thousands/millions etc.

How to configure custom PYTHONPATH with VM and PyCharm?

In pycharm 5 follow this, https://www.jetbrains.com/pycharm/help/configuring-python-interpreter-for-a-project.html

1)Open the Settings dialog box, and click Project Interpreter page.
2)In the Projects pane, choose the desired project.
3)For the selected project, choose SDK from the list of available Python interpreters and virtual environments.

Where does Java's String constant pool live, the heap or the stack?

As other answers explain Memory in Java is divided into two portions

1. Stack: One stack is created per thread and it stores stack frames which again stores local variables and if a variable is a reference type then that variable refers to a memory location in heap for the actual object.

2. Heap: All kinds of objects will be created in heap only.

Heap memory is again divided into 3 portions

1. Young Generation: Stores objects which have a short life, Young Generation itself can be divided into two categories Eden Space and Survivor Space.

2. Old Generation: Store objects which have survived many garbage collection cycles and still being referenced.

3. Permanent Generation: Stores metadata about the program e.g. runtime constant pool.

String constant pool belongs to the permanent generation area of Heap memory.

We can see the runtime constant pool for our code in the bytecode by using javap -verbose class_name which will show us method references (#Methodref), Class objects ( #Class ), string literals ( #String )

runtime-constant-pool

You can read more about it on my article How Does JVM Handle Method Overloading and Overriding Internally.

Return an empty Observable

With the new syntax of RxJS 5.5+, this becomes as the following:

// RxJS 6
import { EMPTY, empty, of } from "rxjs";

// rxjs 5.5+ (<6)
import { empty } from "rxjs/observable/empty";
import { of } from "rxjs/observable/of";

empty(); // deprecated use EMPTY
EMPTY;
of({});

Just one thing to keep in mind, EMPTY completes the observable, so it won't trigger next in your stream, but only completes. So if you have, for instance, tap, they might not get trigger as you wish (see an example below).

Whereas of({}) creates an Observable and emits next with a value of {} and then it completes the Observable.

E.g.:

EMPTY.pipe(
    tap(() => console.warn("i will not reach here, as i am complete"))
).subscribe();

of({}).pipe(
    tap(() => console.warn("i will reach here and complete"))
).subscribe();

Two-dimensional array in Swift

Before using multidimensional arrays in Swift, consider their impact on performance. In my tests, the flattened array performed almost 2x better than the 2D version:

var table = [Int](repeating: 0, count: size * size)
let array = [Int](1...size)
for row in 0..<size {
    for column in 0..<size {
        let val = array[row] * array[column]
        // assign
        table[row * size + column] = val
    }
}

Average execution time for filling up a 50x50 Array: 82.9ms

vs.

var table = [[Int]](repeating: [Int](repeating: 0, count: size), count: size)
let array = [Int](1...size)
for row in 0..<size {
    for column in 0..<size {
        // assign
        table[row][column] = val
    }
}

Average execution time for filling up a 50x50 2D Array: 135ms

Both algorithms are O(n^2), so the difference in execution times is caused by the way we initialize the table.

Finally, the worst you can do is using append() to add new elements. That proved to be the slowest in my tests:

var table = [Int]()    
let array = [Int](1...size)
for row in 0..<size {
    for column in 0..<size {
        table.append(val)
    }
}

Average execution time for filling up a 50x50 Array using append(): 2.59s

Conclusion

Avoid multidimensional arrays and use access by index if execution speed matters. 1D arrays are more performant, but your code might be a bit harder to understand.

You can run the performance tests yourself after downloading the demo project from my GitHub repo: https://github.com/nyisztor/swift-algorithms/tree/master/big-o-src/Big-O.playground

Installing SciPy with pip

For the Arch Linux users:

pip install --user scipy prerequisites the following Arch packages to be installed:

  • gcc-fortran
  • blas
  • lapack

What is the best way to seed a database in Rails?

Rails has a built in way to seed data as explained here.

Another way would be to use a gem for more advanced or easy seeding such as: seedbank.

The main advantage of this gem and the reason I use it is that it has advanced capabilities such as data loading dependencies and per environment seed data.

Adding an up to date answer as this answer was first on google.

How can I make Flexbox children 100% height of their parent?

I have answered a similar question here.

I know you have already said position: absolute; is inconvenient, but it works. See below for further information on fixing the resize issue.

Also see this jsFiddle for a demo, although I have only added WebKit prefixes so open in Chrome.

You basically have two issues which I will deal with separately.

  1. Getting the child of a flex-item to fill height 100%
  • Set position: relative; on the parent of the child.
  • Set position: absolute; on the child.
  • You can then set width/height as required (100% in my sample).
  1. Fixing the resize scrolling "quirk" in Chrome
  • Put overflow-y: auto; on the scrollable div.
  • The scrollable div must have an explicit height specified. My sample already has height 100%, but if none is already applied you can specify height: 0;

See this answer for more information on the scrolling issue.

how to set mongod --dbpath

very simple:

sudo chown mongodb:mongodb /var/lib/mongodb/mongod.lock 

How to generate a random int in C?

Well, STL is C++, not C, so I don't know what you want. If you want C, however, there is the rand() and srand() functions:

int rand(void);

void srand(unsigned seed);

These are both part of ANSI C. There is also the random() function:

long random(void);

But as far as I can tell, random() is not standard ANSI C. A third-party library may not be a bad idea, but it all depends on how random of a number you really need to generate.

How to create empty text file from a batch file?

fsutil file createnew file.cmd 0

How to make a machine trust a self-signed Java application

I had the same problem, but i solved it from Java Control Panel-->Security-->SecurityLevel:MEDIUM. Just so, no Manage certificates, imports ,exports etc..

Mockito: Trying to spy on method is calling the original method

Let me quote the official documentation:

Important gotcha on spying real objects!

Sometimes it's impossible to use when(Object) for stubbing spies. Example:

List list = new LinkedList();
List spy = spy(list);

// Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");

// You have to use doReturn() for stubbing
doReturn("foo").when(spy).get(0);

In your case it goes something like:

doReturn(resultsIWant).when(myClassSpy).method1();

How to get distinct results in hibernate with joins and row-based limiting (paging)?

session = (Session) getEntityManager().getDelegate();
Criteria criteria = session.createCriteria(ComputedProdDaily.class);
ProjectionList projList = Projections.projectionList();
projList.add(Projections.property("user.id"), "userid");
projList.add(Projections.property("loanState"), "state");
criteria.setProjection(Projections.distinct(projList));
criteria.add(Restrictions.isNotNull("this.loanState"));
criteria.setResultTransformer(Transformers.aliasToBean(UserStateTransformer.class));

This helped me :D

Getting files by creation date in .NET

@jing: "The DirectoryInfo solution is much faster then this (especially for network path)"

I cant confirm this. It seems as if Directory.GetFiles triggers a filesystem or network cache. The first request takes a while, but the following requests are much faster, even if new files were added. In my test I did a Directory.getfiles and a info.GetFiles with the same patterns and both run equally

GetFiles  done 437834 in00:00:20.4812480
process files  done 437834 in00:00:00.9300573
GetFiles by Dirinfo(2)  done 437834 in00:00:20.7412646

Show red border for all invalid fields after submitting form angularjs

I have created a working CodePen example to demonstrate how you might accomplish your goals.

I added ng-click to the <form> and removed the logic from your button:

<form name="addRelation" data-ng-click="save(model)">
...
<input class="btn" type="submit" value="SAVE" />

Here's the updated template:

<section ng-app="app" ng-controller="MainCtrl">
  <form class="well" name="addRelation" data-ng-click="save(model)">
    <label>First Name</label>
    <input type="text" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.FirstName.$invalid">First Name is required</span><br/>
    <label>Last Name</label>
    <input type="text" placeholder="Last Name" data-ng-model="model.lastName" id="LastName" name="LastName" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.LastName.$invalid">Last Name is required</span><br/>
    <label>Email</label>
    <input type="email" placeholder="Email" data-ng-model="model.email" id="Email" name="Email" required/><br/>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.required">Email address is required</span>
    <span class="text-error" data-ng-show="addRelation.submitted && addRelation.Email.$error.email">Email address is not valid</span><br/>
    <input class="btn" type="submit" value="SAVE" />  
  </form>
</section>

and controller code:

app.controller('MainCtrl', function($scope) {  
  $scope.save = function(model) {
    $scope.addRelation.submitted = true;

    if($scope.addRelation.$valid) {
      // submit to db
      console.log(model); 
    } else {
      console.log('Errors in form data');
    }
  };
});

I hope this helps.

Shortcut for creating single item list in C#

Michael's idea of using extension methods leads to something even simpler:

public static List<T> InList<T>(this T item)
{
    return new List<T> { item };
}

So you could do this:

List<string> foo = "Hello".InList();

I'm not sure whether I like it or not, mind you...

Convert string to float?

Try this:

String numberStr = "3.5";
Float number = null;
try {
   number = Float.parseFloat(numberStr);
} catch (NumberFormatException e) {
    System.out.println("numberStr is not a number");
}

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

If nothing helps and you are still getting this exception, review your equals() methods - and don't include child collection in it. Especially if you have deep structure of embedded collections (e.g. A contains Bs, B contains Cs, etc.).

In example of Account -> Transactions:

  public class Account {

    private Long id;
    private String accountName;
    private Set<Transaction> transactions;

    @Override
    public boolean equals(Object obj) {
      if (this == obj)
        return true;
      if (obj == null)
        return false;
      if (!(obj instanceof Account))
        return false;
      Account other = (Account) obj;
      return Objects.equals(this.id, other.id)
          && Objects.equals(this.accountName, other.accountName)
          && Objects.equals(this.transactions, other.transactions); // <--- REMOVE THIS!
    }
  }

In above example remove transactions from equals() checks. This is because hibernate will imply that you are not trying to update old object, but you pass a new object to persist, whenever you change element on the child collection.
Of course this solutions will not fit all applications and you should carefully design what you want to include in the equals and hashCode methods.

Android "elevation" not showing a shadow

Adding background color helped me.

<CalendarView
    android:layout_width="match_parent"
    android:id="@+id/calendarView"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:layout_height="wrap_content"
    android:elevation="5dp"

    android:background="@color/windowBackground"

    />

How to add a single item to a Pandas Series

How to add single item. This is not very effective but follows what you are asking for:

x = p.Series()
N = 4
for i in xrange(N):
   x = x.set_value(i, i**2)

produces x:

0    0
1    1
2    4
3    9

Obviously there are better ways to generate this series in only one shot.

For your second question check answer and references of SO question add one row in a pandas.DataFrame.

How to support placeholder attribute in IE8 and 9

For others landing here. This is what worked for me:

//jquery polyfill for showing place holders in IE9
$('[placeholder]').focus(function() {
    var input = $(this);
    if (input.val() == input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
    }
}).blur(function() {
    var input = $(this);
    if (input.val() == '' || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
    }
}).blur();

$('[placeholder]').parents('form').submit(function() {
    $(this).find('[placeholder]').each(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
            input.val('');
        }
    })
});

Just add this in you script.js file. Courtesy of http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

Oracle date difference to get number of years

Need to find difference in year, if leap year the a year is of 366 days.

I dont work in oracle much, please make this better. Here is how I did:

SELECT CASE
          WHEN    ( (fromisleapyear = 'Y') AND (frommonth < 3))
               OR ( (toisleapyear = 'Y') AND (tomonth > 2)) THEN
             datedif / 366
          ELSE
             datedif / 365
       END
          yeardifference
  FROM (SELECT datedif,
               frommonth,
               tomonth,
               CASE
                  WHEN (       (MOD (fromyear, 4) = 0)
                           AND (MOD (fromyear, 100) <> 0)
                        OR (MOD (fromyear, 400) = 0)) THEN
                     'Y'
               END
                  fromisleapyear,
               CASE
                  WHEN (   (MOD (toyear, 4) = 0) AND (MOD (toyear, 100) <> 0)
                        OR (MOD (toyear, 400) = 0)) THEN
                     'Y'
               END
                  toisleapyear
          FROM (SELECT (:todate - :fromdate) AS datedif,
                       TO_CHAR (:fromdate, 'YYYY') AS fromyear,
                       TO_CHAR (:fromdate, 'MM') AS frommonth,
                       TO_CHAR (:todate, 'YYYY') AS toyear,
                       TO_CHAR (:todate, 'MM') AS tomonth
                  FROM DUAL))

Fragment Inside Fragment

You can add FrameLayout to the fragment and replace it with another fragment when it initializes.

This way , you could consider the other fragment to be inside the first fragment.

alert() not working in Chrome

Here is a snippet that does not need ajQuery and will enable alerts in a disabled iframe (like on codepen)

for (var i = 0; i < document.getElementsByTagName('iframe').length; i++) {
    document.getElementsByTagName('iframe')[i].setAttribute('sandbox','allow-modals');
}

Here is a codepen demo working with an alert() after this fix as well: http://codepen.io/nicholasabrams/pen/vNpoBr?editors=001

Set drawable size programmatically

Probably a little late. But here is the solution that finally worked for me in every situation.

The idea is to create a custom drawable with fixed intrinic size and pass the drawing job on to the original drawable.

Drawable icon = new ColorDrawable(){
        Drawable iconOrig = resolveInfo.loadIcon(packageManager);

        @Override
        public void setBounds(int left, int top, int right, int bottom){
            super.setBounds(left, top, right, bottom);//This is needed so that getBounds on this class would work correctly.
            iconOrig.setBounds(left, top, right, bottom);
        }

        @Override
        public void draw(Canvas canvas){
            iconOrig.draw(canvas);
        }

        @Override
        public int getIntrinsicWidth(){
            return  mPlatform.dp2px(30);
        }

        @Override
        public int getIntrinsicHeight(){
            return  mPlatform.dp2px(30);
        }
    };

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

Simply follow the code

public static String getFormatedDate(String strDate,StringsourceFormate,
                                     String destinyFormate) {
    SimpleDateFormat df;
    df = new SimpleDateFormat(sourceFormate);
    Date date = null;
    try {
        date = df.parse(strDate);

    } catch (ParseException e) {
        e.printStackTrace();
    }

    df = new SimpleDateFormat(destinyFormate);
    return df.format(date);

}

and pass the value into the function like that,

getFormatedDate("21:30:00", "HH:mm", "hh:mm aa");

or checkout this documentation SimpleDateFormat for StringsourceFormate and destinyFormate.

Is it possible to do a sparse checkout without checking out the whole repository first?

In git 2.27, it looks like git sparse checkout has evolved. Solution in this answer does not work exactly the same way (compared to git 2.25)

git clone <URL> --no-checkout <directory>
cd <directory>
git sparse-checkout init --cone # to fetch only root files
git sparse-checkout set apps/my_app libs/my_lib # etc, to list sub-folders to checkout
# they are checked out immediately after this command, no need to run git pull

These commands worked better:

git clone --sparse <URL> <directory>
cd <directory>
git sparse-checkout init --cone # to fetch only root files
git sparse-checkout add apps/my_app
git sparse-checkout add libs/my_lib

See also : git-clone --sparse and git-sparse-checkout add

Check if an HTML input element is empty or has no value entered by user

Your first one was basically right. This, FYI, is bad. It does an equality check between a DOM node and a string:

if (document.getElementById('customx') == ""){

DOM nodes are actually their own type of JavaScript object. Thus this comparison would never work at all since it's doing an equality comparison on two distinctly different data types.

Is there a way to instantiate a class by name in Java?

Use java reflection

Creating New Objects There is no equivalent to method invocation for constructors, because invoking a constructor is equivalent to creating a new object (to be the most precise, creating a new object involves both memory allocation and object construction). So the nearest equivalent to the previous example is to say:

import java.lang.reflect.*;

   public class constructor2 {
      public constructor2()
      {
      }

      public constructor2(int a, int b)
      {
         System.out.println(
           "a = " + a + " b = " + b);
      }

      public static void main(String args[])
      {
         try {
           Class cls = Class.forName("constructor2");
           Class partypes[] = new Class[2];
            partypes[0] = Integer.TYPE;
            partypes[1] = Integer.TYPE;
            Constructor ct 
              = cls.getConstructor(partypes);
            Object arglist[] = new Object[2];
            arglist[0] = new Integer(37);
            arglist[1] = new Integer(47);
            Object retobj = ct.newInstance(arglist);
         }
         catch (Throwable e) {
            System.err.println(e);
         }
      }
   }

which finds a constructor that handles the specified parameter types and invokes it, to create a new instance of the object. The value of this approach is that it's purely dynamic, with constructor lookup and invocation at execution time, rather than at compilation time.

How to use Visual Studio Code as Default Editor for Git

git config --global core.editor "code --wait"

OR

git config --global core.editor "code -w"

Check

git config --global e

Your configuration will open in Visual Studio Code

MySQL SELECT DISTINCT multiple columns

Taking a guess at the results you want so maybe this is the query you want then

SELECT DISTINCT a FROM my_table
UNION 
SELECT DISTINCT b FROM my_table
UNION
SELECT DISTINCT c FROM my_table
UNION
SELECT DISTINCT d FROM my_table

How to extract a string using JavaScript Regex?

You need to use the m flag:

multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)

Also put the * in the right place:

"DATE:20091201T220000\r\nSUMMARY:Dad's birthday".match(/^SUMMARY\:(.*)$/gm);
//------------------------------------------------------------------^    ^
//-----------------------------------------------------------------------|

How to add DOM element script to head section?

Best solution I've found:

AppendToHead('script', 'alert("hii"); ');
//or
AppendToHead('script', 'http://example.com/script.js');
//or
AppendToHead('style',  '#myDiv{color:red;} ');
//or
AppendToHead('style',  'http://example.com/style.css');



function AppendToHead(elemntType, content){
    // detect whether provided content is "link" (instead of inline codes)
    var Is_Link = content.split(/\r\n|\r|\n/).length <= 1  &&  content.indexOf("//") > -1 && content.indexOf(" ")<=-1;
    if(Is_Link){
        if (elemntType=='script')    { var x=document.createElement('script');x.id=id;  x.src=content;  x.type='text/javascript'; }
        else if (elemntType=='style'){ var x=document.createElement('link');  x.id=id;  x.href=content; x.type='text/css';  x.rel = 'stylesheet'; }
    }
    else{
        var x = document.createElement(elemntType);
        if (elemntType=='script')    { x.type='text/javascript';    x.innerHTML = content;  }
        else if (elemntType=='style'){ x.type='text/css';    if (x.styleSheet){ x.styleSheet.cssText=content; } else { x.appendChild(document.createTextNode(content)); }   }
    }
    //append in head
    (document.head || document.getElementsByTagName('head')[0]).appendChild(x);
}

How to call a function after delay in Kotlin?

You can use Schedule

inline fun Timer.schedule(
    delay: Long, 
    crossinline action: TimerTask.() -> Unit
): TimerTask (source)

example (thanks @Nguyen Minh Binh - found it here: http://jamie.mccrindle.org/2013/02/exploring-kotlin-standard-library-part-3.html)

import java.util.Timer
import kotlin.concurrent.schedule

Timer("SettingUp", false).schedule(500) { 
   doSomething()
}

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

For Windows, I was able to get it working by enabling TLS for secure communication on the SMTP Virtual server. TLS will not be available on the SMTP virtual server without a certificate. This link will give the steps needed.

https://support.microsoft.com/en-ie/help/4014125/how-to-configure-iis-smtp-for-outgoing-tls-authentication

How to create named and latest tag in Docker?

Variation of Aaron's answer. Using sed without temporary files

#!/bin/bash
VERSION=1.0.0
IMAGE=company/image
ID=$(docker build  -t ${IMAGE}  .  | tail -1 | sed 's/.*Successfully built \(.*\)$/\1/')

docker tag ${ID} ${IMAGE}:${VERSION}
docker tag -f ${ID} ${IMAGE}:latest

Simple (I think) Horizontal Line in WPF?

To draw Horizontal 
************************    
<Rectangle  HorizontalAlignment="Stretch"  VerticalAlignment="Center" Fill="DarkCyan" Height="4"/>

To draw vertical 
*******************
 <Rectangle  HorizontalAlignment="Stretch" VerticalAlignment="Center" Fill="DarkCyan" Height="4" Width="Auto" >
        <Rectangle.RenderTransform>
            <TransformGroup>
                <ScaleTransform/>
                <SkewTransform/>
                <RotateTransform Angle="90"/>
                <TranslateTransform/>
            </TransformGroup>
        </Rectangle.RenderTransform>
    </Rectangle>

Ruby: How to convert a string to boolean

I've frequently used this pattern to extend the core behavior of Ruby to make it easier to deal with converting arbitrary data types to boolean values, which makes it really easy to deal with varying URL parameters, etc.

class String
  def to_boolean
    ActiveRecord::Type::Boolean.new.cast(self)
  end
end

class NilClass
  def to_boolean
    false
  end
end

class TrueClass
  def to_boolean
    true
  end

  def to_i
    1
  end
end

class FalseClass
  def to_boolean
    false
  end

  def to_i
    0
  end
end

class Integer
  def to_boolean
    to_s.to_boolean
  end
end

So let's say you have a parameter foo which can be:

  • an integer (0 is false, all others are true)
  • a true boolean (true/false)
  • a string ("true", "false", "0", "1", "TRUE", "FALSE")
  • nil

Instead of using a bunch of conditionals, you can just call foo.to_boolean and it will do the rest of the magic for you.

In Rails, I add this to an initializer named core_ext.rb in nearly all of my projects since this pattern is so common.

## EXAMPLES

nil.to_boolean     == false
true.to_boolean    == true
false.to_boolean   == false
0.to_boolean       == false
1.to_boolean       == true
99.to_boolean      == true
"true".to_boolean  == true
"foo".to_boolean   == true
"false".to_boolean == false
"TRUE".to_boolean  == true
"FALSE".to_boolean == false
"0".to_boolean     == false
"1".to_boolean     == true
true.to_i          == 1
false.to_i         == 0

How to change webservice url endpoint?

To change the end address property edit your wsdl file

<wsdl:definitions.......
  <wsdl:service name="serviceMethodName">
    <wsdl:port binding="tns:serviceMethodNameSoapBinding" name="serviceMethodName">
      <soap:address location="http://service_end_point_adress"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>

Pyspark: Exception: Java gateway process exited before sending the driver its port number

For Linux (Ubuntu 18.04) with a JAVA_HOME issue, a key is to point it to the master folder:

  1. Set Java 8 as default by: sudo update-alternatives --config java. If Jave 8 is not installed, install by: sudo apt install openjdk-8-jdk.
  2. Set JAVA_HOME environment variable as the master java 8 folder. The location is given by the first command above removing jre/bin/java. Namely: export JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64/". If done on the command line, this will be relevant only for the current session (ref: export command on Linux). To verify: echo $JAVA_HOME.
  3. In order to have this permanently set, add the bolded line above to a file that runs before you start your IDE/Jupyter/python interpreter. This could be by adding the bolded line above to .bashrc. This file loads when a bash is started interactively ref: .bashrc

Where is svcutil.exe in Windows 7?

If you are using vs 2010 then you can get it in

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools

How to play video with AVPlayerViewController (AVKit) in Swift

Objective c

This only works in Xcode 7

Go to .h file and import AVKit/AVKit.h and AVFoundation/AVFoundation.h. Then go .m file and add this code:

NSURL *url=[[NSBundle mainBundle]URLForResource:@"arreg" withExtension:@"mp4"];
AVPlayer *video=[AVPlayer playerWithURL:url];
AVPlayerViewController *controller=[[AVPlayerViewController alloc]init];
controller.player=video;
[self.view addSubview:controller.view];
controller.view.frame=self.view.frame;
[self addChildViewController:controller];
[video play];

BigDecimal to string

The BigDecimal can not be a double. you can use Int number. if you want to display exactly own number, you can use the String constructor of BigDecimal .

like this:

BigDecimal bd1 = new BigDecimal("10.0001");

now, you can display bd1 as 10.0001

So simple. GOOD LUCK.

jQuery calculate sum of values in all text fields

$(".price").each(function(){ 
total_price += parseFloat($(this).val()); 
}); 

please try like this...

Python: 'ModuleNotFoundError' when trying to import module from imported package

FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.

...

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

You need to set it up to something like this:

man
|- __init__.py
|- Mans
   |- __init__.py
   |- man1.py
|- MansTest
   |- __init.__.py
   |- SoftLib
      |- Soft
         |- __init__.py
         |- SoftWork
            |- __init__.py
            |- manModules.py
      |- Unittests
         |- __init__.py
         |- man1test.py

SECOND, for the "ModuleNotFoundError: No module named 'Soft'" error caused by from ...Mans import man1 in man1test.py, the documented solution to that is to add man1.py to sys.path since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path directly, you can also modify PYTHONPATH:

sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

THIRD, for from ...MansTest.SoftLib import Soft which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.

With that said, here's how I got it to work.

man1.py:

from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH

def foo():
    print("called foo in man1.py")
    print("foo call module1 from manModules: " + module1())

man1test.py

# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1

man1.foo()

manModules.py

def module1():
    return "module1 in manModules"

Terminal output:

$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
  ...
    from ...Mans import man1
  File "/temp/man/Mans/man1.py", line 2, in <module>
    from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'

$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules 

As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).

Pass Javascript Variable to PHP POST

There is a lot of ways to achieve this. In regards to the way you are asking, with a hidden form element.

create this form element inside your form:

<input type="hidden" name="total" value="">

So your form like this:

<form id="sampleForm" name="sampleForm" method="post" action="phpscript.php">
<input type="hidden" name="total" id="total" value="">
<a href="#" onclick="setValue();">Click to submit</a>
</form>

Then your javascript something like this:

<script>
function setValue(){
    document.sampleForm.total.value = 100;
    document.forms["sampleForm"].submit();
}
</script>

How do I enumerate through a JObject?

If you look at the documentation for JObject, you will see that it implements IEnumerable<KeyValuePair<string, JToken>>. So, you can iterate over it simply using a foreach:

foreach (var x in obj)
{
    string name = x.Key;
    JToken value = x.Value;
    …
}

PostgreSQL column 'foo' does not exist

We ran into this issue when we created the table using phppgadmin client. With phppgadmin we did not specify any double quotes in column name and still we ran into same issue.

It we create column with caMel case then phpPGAdmin implicitly adds double quotes around the column name. If you create column with all lower case then you will not run into this issue.

You can alter the column in phppgadmin and change the column name to all lower case this issue will go away.

Using jQuery to programmatically click an <a> link

<a href="#" id="myAnchor">Click me</a>

<script type="text/javascript">
$(document).ready(function(){
    $('#myAnchor').click(function(){
       window.location.href = 'index.php';
    });
})
</script>

How do I compare two variables containing strings in JavaScript?

I used below function to compare two strings and It is working good.

function CompareUserId (first, second)
{

   var regex = new RegExp('^' + first+ '$', 'i');
   if (regex.test(second)) 
   {
        return true;
   }
   else 
   {
        return false;
   }
   return false;
}

When and why do I need to use cin.ignore() in C++?

It is better to use scanf(" %[^\n]",str) in c++ than cin.ignore() after cin>> statement.To do that first you have to include < cstdio > header.

How can I execute PHP code from the command line?

If you're going to do PHP in the command line, I recommend you install phpsh, a decent PHP shell. It's a lot more fun.

Anyway, the php command offers two switches to execute code from the command line:

-r <code>        Run PHP <code> without using script tags <?..?>
-R <code>        Run PHP <code> for every input line

You can use php's -r switch as such:

php -r 'echo function_exists("foo") ? "yes" : "no";'

The above PHP command above should output no and returns 0 as you can see:

>>> php -r 'echo function_exists("foo") ? "yes" : "no";'
no
>>> echo $? # print the return value of the previous command
0

Another funny switch is php -a:

-a               Run as interactive shell

It's sort of lame compared to phpsh, but if you don't want to install the awesome interactive shell for PHP made by Facebook to get tab completion, history, and so on, then use -a as such:

>>> php -a
Interactive shell

php > echo function_exists("foo") ? "yes" : "no";
no
php >

If it doesn't work on your box like on my boxes (tested on Ubuntu and Arch Linux), then probably your PHP setup is fuzzy or broken. If you run this command:

php -i | grep 'API'

You should see:

Server API => Command Line Interface

If you don't, this means that maybe another command will provides the CLI SAPI. Try php-cli; maybe it's a package or a command available in your OS.

If you do see that your php command uses the CLI (command-line interface) SAPI (Server API), then run php -h | grep code to find out which crazy switch - as this hasn't changed for year- allows to run code in your version/setup.

Another couple of examples, just to make sure it works on my boxes:

>>> php -r 'echo function_exists("sg_load") ? "yes" : "no";'
no
>>> php -r 'echo function_exists("print_r") ? "yes" : "no";'
yes

Also, note that it is possible that an extension is loaded in the CLI and not in the CGI or Apache SAPI. It is likely that several PHP SAPIs use different php.ini files, e.g., /etc/php/cli/php.ini vs. /etc/php/cgi/php.ini vs. /etc/php/apache/php.ini on a Gentoo Linux box. Find out which ini file is used with php -i | grep ini.

How to Clone Objects

It couldn't be simpler than this:

    public SomeClass Clone () {

        var clonedJson = JsonConvert.SerializeObject (this);

        return JsonConvert.DeserializeObject<SomeClass> (clonedJson);
    }

Just serialize any object to a JSON string and then deserialize it. This will do a deep copy...

How to edit one specific row in Microsoft SQL Server Management Studio 2008?

How to edit one specific row/tuple in Server Management Studio 2008/2012/2014/2016

Step 1: Right button mouse > Select "Edit Top 200 Rows"

Edit top 200 rows

Step 2: Navigate to Query Designer > Pane > SQL (Shortcut: Ctrl+3)

Navigate to Query Designer > Pane > SQL

Step 3: Modify the query

Modify the query

Step 4: Right button mouse > Select "Execute SQL" (Shortcut: Ctrl+R)

enter image description here

how to access parent window object using jquery?

or you can use another approach:

$( "#serverMsg", window.opener.document )

Flutter- wrapping text

Container(
  color: Color.fromRGBO(224, 251, 253, 1.0),
  child: ListTile(
    dense: true,
    title: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        RichText(
          textAlign: TextAlign.left,
          softWrap: true,
          text: TextSpan(children: <TextSpan>
          [
            TextSpan(text: "hello: ",
                style: TextStyle(
                    color: Colors.black, fontWeight: FontWeight.bold)),
            TextSpan(text: "I hope this helps",
                style: TextStyle(color: Colors.black)),
          ]
          ),
        ),
      ],
    ),
  ),
),

Android: show/hide status bar/power bar

I know its a very old question, but just in case anyone lands here looking for the newest supported way to hide status bar on the go programmatically, you can do it as follows:

window.insetsController?.hide(WindowInsets.Type.statusBars())

and to show it again:

window.insetsController?.show(WindowInsets.Type.statusBars())

How to make a dropdown readonly using jquery?

I had the same problem, my solution was to disable all options not selected. Very easy with jQuery:

$('option:not(:selected)').attr('disabled', true);

Edit => If you have multiple dropdowns on same page, disable all not selected options on select-ID as below.

$('#select_field_id option:not(:selected)').attr('disabled', true);

Is it possible to format an HTML tooltip (title attribute)?

No, it's not possible, browsers have their own ways to implement tooltip. All you can do is to create some div that behaves like an HTML tooltip (mostly it's just 'show on hover') with Javascript, and then style it the way you want.

With this, you wouldn't have to worry about browser's zooming in or out, since the text inside the tooltip div is an actual HTML, it would scale accordingly.

See Jonathan's post for some good resource.

How to make circular background using css?

If you want to do it with only 1 element, you can use the ::before and ::after pseudo elements for the same div instead of a wrapper.
See http://css-tricks.com/pseudo-element-roundup/

How to stretch the background image to fill a div

Use: background-size: 100% 100%; To make background image to fit the div size.

Remove sensitive files and their commits from Git history

Here is my solution in windows

git filter-branch --tree-filter "rm -f 'filedir/filename'" HEAD

git push --force

make sure that the path is correct otherwise it won't work

I hope it helps

Pyspark: Filter dataframe based on multiple conditions

Your logic condition is wrong. IIUC, what you want is:

import pyspark.sql.functions as f

df.filter((f.col('d')<5))\
    .filter(
        ((f.col('col1') != f.col('col3')) | 
         (f.col('col2') != f.col('col4')) & (f.col('col1') == f.col('col3')))
    )\
    .show()

I broke the filter() step into 2 calls for readability, but you could equivalently do it in one line.

Output:

+----+----+----+----+---+
|col1|col2|col3|col4|  d|
+----+----+----+----+---+
|   A|  xx|   D|  vv|  4|
|   A|   x|   A|  xx|  3|
|   E| xxx|   B|  vv|  3|
|   F|xxxx|   F| vvv|  4|
|   G| xxx|   G|  xx|  4|
+----+----+----+----+---+

Testing web application on Mac/Safari when I don't own a Mac

The best site to test website and see them realtime on MAC Safari is by using

Browserstack

They have like 25 free minutes of first time testing and then 10 free mins each day..You can even test your pages from your local PC by using their WEB TUNNEL Feature

I tested 7 to 8 pages in browserstack...And I think they have some java debugging tool in the upper right corner that is great help

"Undefined reference to" template class constructor

This is a common question in C++ programming. There are two valid answers to this. There are advantages and disadvantages to both answers and your choice will depend on context. The common answer is to put all the implementation in the header file, but there's another approach will will be suitable in some cases. The choice is yours.

The code in a template is merely a 'pattern' known to the compiler. The compiler won't compile the constructors cola<float>::cola(...) and cola<string>::cola(...) until it is forced to do so. And we must ensure that this compilation happens for the constructors at least once in the entire compilation process, or we will get the 'undefined reference' error. (This applies to the other methods of cola<T> also.)

Understanding the problem

The problem is caused by the fact that main.cpp and cola.cpp will be compiled separately first. In main.cpp, the compiler will implicitly instantiate the template classes cola<float> and cola<string> because those particular instantiations are used in main.cpp. The bad news is that the implementations of those member functions are not in main.cpp, nor in any header file included in main.cpp, and therefore the compiler can't include complete versions of those functions in main.o. When compiling cola.cpp, the compiler won't compile those instantiations either, because there are no implicit or explicit instantiations of cola<float> or cola<string>. Remember, when compiling cola.cpp, the compiler has no clue which instantiations will be needed; and we can't expect it to compile for every type in order to ensure this problem never happens! (cola<int>, cola<char>, cola<ostream>, cola< cola<int> > ... and so on ...)

The two answers are:

  • Tell the compiler, at the end of cola.cpp, which particular template classes will be required, forcing it to compile cola<float> and cola<string>.
  • Put the implementation of the member functions in a header file that will be included every time any other 'translation unit' (such as main.cpp) uses the template class.

Answer 1: Explicitly instantiate the template, and its member definitions

At the end of cola.cpp, you should add lines explicitly instantiating all the relevant templates, such as

template class cola<float>;
template class cola<string>;

and you add the following two lines at the end of nodo_colaypila.cpp:

template class nodo_colaypila<float>;
template class nodo_colaypila<std :: string>;

This will ensure that, when the compiler is compiling cola.cpp that it will explicitly compile all the code for the cola<float> and cola<string> classes. Similarly, nodo_colaypila.cpp contains the implementations of the nodo_colaypila<...> classes.

In this approach, you should ensure that all the of the implementation is placed into one .cpp file (i.e. one translation unit) and that the explicit instantation is placed after the definition of all the functions (i.e. at the end of the file).

Answer 2: Copy the code into the relevant header file

The common answer is to move all the code from the implementation files cola.cpp and nodo_colaypila.cpp into cola.h and nodo_colaypila.h. In the long run, this is more flexible as it means you can use extra instantiations (e.g. cola<char>) without any more work. But it could mean the same functions are compiled many times, once in each translation unit. This is not a big problem, as the linker will correctly ignore the duplicate implementations. But it might slow down the compilation a little.

Summary

The default answer, used by the STL for example and in most of the code that any of us will write, is to put all the implementations in the header files. But in a more private project, you will have more knowledge and control of which particular template classes will be instantiated. In fact, this 'bug' might be seen as a feature, as it stops users of your code from accidentally using instantiations you have not tested for or planned for ("I know this works for cola<float> and cola<string>, if you want to use something else, tell me first and will can verify it works before enabling it.").

Finally, there are three other minor typos in the code in your question:

  • You are missing an #endif at the end of nodo_colaypila.h
  • in cola.h nodo_colaypila<T>* ult, pri; should be nodo_colaypila<T> *ult, *pri; - both are pointers.
  • nodo_colaypila.cpp: The default parameter should be in the header file nodo_colaypila.h, not in this implementation file.

How to remove a directory from git repository?

To add new directory:

mkdir <YOUR-DIRECTORY>

But now Git is not aware by this new directory, because Git keep tracks of file not directories DIRECTORY

git status

Git won't be aware with the change we've made, so we add hidden .keep file to make Git aware by this new change.

touch /YOUR-directory/.keep

Now, if you hit git status Git will be aware with the changes.

And If you want to delete the directory, you should use this command.

rm -r <YOUR-DIRECTORY>

And If you checked by using git status, you will see the directory has been removed.

random number generator between 0 - 1000 in c#

Use this:

static int RandomNumber(int min, int max)
{
    Random random = new Random(); return random.Next(min, max);

}

This is example for you to modify and use in your application.

How to change the new TabLayout indicator color and height

With the design support library you can now change them in the xml:

To change the color of the TabLayout indicator:

app:tabIndicatorColor="@color/color"

To change the height of the TabLayout indicator:

app:tabIndicatorHeight="4dp"