Programs & Examples On #Sparql

SPARQL (pronounced "sparkle", a recursive acronym for SPARQL Protocol and RDF Query Language) is a set of specifications by W3C that provide languages and protocols to query and manipulate RDF graph content on the Web or in an RDF store.

Browse and display files in a git repo without cloning

GitHub is svn compatible so you can use svn ls

svn ls https://github.com/user/repository.git/branches/master/

BitBucket supports git archive so you can download tar archive and list archived files. It is not very efficient but works:

git archive [email protected]:repository HEAD directory | tar -t

pythonw.exe or python.exe?

I was struggling to get this to work for a while. Once you change the extension to .pyw, make sure that you open properties of the file and direct the "open with" path to pythonw.exe.

Where do I find the definition of size_t?

Practically speaking size_t represents the number of bytes you can address. On most modern architectures for the last 10-15 years that has been 32 bits which has also been the size of a unsigned int. However we are moving to 64bit addressing while the uint will most likely stay at 32bits (it's size is not guaranteed in the c++ standard). To make your code that depends on the memory size portable across architectures you should use a size_t. For example things like array sizes should always use size_t's. If you look at the standard containers the ::size() always returns a size_t.

Also note, visual studio has a compile option that can check for these types of errors called "Detect 64-bit Portability Issues".

Android Studio does not show layout preview

This is a common problem . It can be easily solved by changing res/values/styles.xml to

<!-- Base application theme. -->
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
</style>

Steps :

  • Go to res/values/
  • open styles.xml

    • change from -> style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"

    • change to -> style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar"

    (Just prepend "Base." to "Theme".)


  • Save the file and check Preview now.

  • Preview Works Perfeclty now.

Notification bar icon turns white in Android 5 Lollipop

Completely agree with user Daniel Saidi. In Order to have Color for NotificationIcon I'm writing this answer.

For that you've to make icon like Silhouette and make some section Transparent wherever you wants to add your Colors. i.e,

enter image description here

You can add your color using

.setColor(your_color_resource_here)

NOTE : setColor is only available in Lollipop so, you've to check OSVersion

if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    Notification notification = new Notification.Builder(context)
    ...
} else {
    // Lollipop specific setColor method goes here.
    Notification notification = new Notification.Builder(context)
    ...
    notification.setColor(your_color)
    ...            
}

You can also achieve this using Lollipop as the target SDK.

All instruction regarding NotificationIcon given at Google Developer Console Notification Guide Lines.

Preferred Notification Icon Size 24x24dp

mdpi    @ 24.00dp   = 24.00px
hdpi    @ 24.00dp   = 36.00px
xhdpi   @ 24.00dp   = 48.00px

And also refer this link for Notification Icon Sizes for more info.

How to use PDO to fetch results array in PHP?

$st = $data->prepare("SELECT * FROM exampleWHERE example LIKE :search LIMIT 10"); 

Android Studio Gradle Already disposed Module

For an alternative solution, check if you added your app to settings.gradle successfully

include ':app' 

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229


Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

How to solve npm install throwing fsevents warning on non-MAC OS?

If anyone get this error for ionic cordova install . just use this code npm install --no-optional in your cmd. And then run this code npm install -g ionic@latest cordova

How can I make a button have a rounded border in Swift?

@IBOutlet weak var yourButton: UIButton! {
    didSet{
        yourButton.backgroundColor = .clear
        yourButton.layer.cornerRadius = 10
        yourButton.layer.borderWidth = 2
        yourButton.layer.borderColor = UIColor.white.cgColor
    }
}

Omitting one Setter/Getter in Lombok

User the below code for omit/excludes from creating setter and getter. value key should use inside @Getter and @Setter.

@Getter(value = AccessLevel.NONE)
@Setter(value = AccessLevel.NONE)
private int mySecret;

Spring boot 2.3 version, this is working well.

Count the frequency that a value occurs in a dataframe column

n_values = data.income.value_counts()

First unique value count

n_at_most_50k = n_values[0]

Second unique value count

n_greater_50k = n_values[1]

n_values

Output:

<=50K    34014
>50K     11208

Name: income, dtype: int64

Output:

n_greater_50k,n_at_most_50k:-
(11208, 34014)

How to get the last N rows of a pandas DataFrame?

How to get the last N rows of a pandas DataFrame?

If you are slicing by position, __getitem__ (i.e., slicing with[]) works well, and is the most succinct solution I've found for this problem.

pd.__version__
# '0.24.2'

df = pd.DataFrame({'A': list('aaabbbbc'), 'B': np.arange(1, 9)})
df

   A  B
0  a  1
1  a  2
2  a  3
3  b  4
4  b  5
5  b  6
6  b  7
7  c  8

df[-3:]

   A  B
5  b  6
6  b  7
7  c  8

This is the same as calling df.iloc[-3:], for instance (iloc internally delegates to __getitem__).


As an aside, if you want to find the last N rows for each group, use groupby and GroupBy.tail:

df.groupby('A').tail(2)

   A  B
1  a  2
2  a  3
5  b  6
6  b  7
7  c  8

Where does Visual Studio look for C++ header files?

Visual Studio looks for headers in this order:

  • In the current source directory.
  • In the Additional Include Directories in the project properties (Project -> [project name] Properties, under C/C++ | General).
  • In the Visual Studio C++ Include directories under Tools ? Options ? Projects and Solutions ? VC++ Directories.
  • In new versions of Visual Studio (2015+) the above option is deprecated and a list of default include directories is available at Project Properties ? Configuration ? VC++ Directories

In your case, add the directory that the header is to the project properties (Project Properties ? Configuration ? C/C++ ? General ? Additional Include Directories).

selecting unique values from a column

use

SELECT DISTINCT Date FROM buy ORDER BY Date

so MySQL removes duplicates

BTW: using explicit column names in SELECT uses less resources in PHP when you're getting a large result from MySQL

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: http://www.java.com/en/download/manual.jsp (7 Update 25 )

and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.

EDIT:

Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

How I add Headers to http.get or http.post in Typescript and angular 2?

I have used below code in Angular 9. note that it is using http class instead of normal httpClient.

  1. so import Headers from the module, otherwise Headers will be mistaken by typescript headers interface and gives error

    import {Http, Headers, RequestOptionsArgs } from "@angular/http";

  2. and in your method use following sample code and it is breaked down for easier understanding.

    let customHeaders = new Headers({ Authorization: "Bearer " + localStorage.getItem("token")});
    const requestOptions: RequestOptionsArgs = { headers: customHeaders };
    return this.http.get("/api/orders", requestOptions);
    

How can I format bytes a cell in Excel as KB, MB, GB etc?

All the answers here supply values with powers of 10. Here is a format using proper SI units (multiples of 1024, i.e. Mebibytes, Gibibytes, and Tebibytes):

[>1099511627776]#.##,,,," TiB";[>1073741824]#.##,,," GiB";0.##,," MiB"

This supports MiB, GiB, and TiB showing two decimal places.

How to insert a line break <br> in markdown

I know this post is about adding a single line break but I thought I would mention that you can create multiple line breaks with the backslash (\) character:

Hello
\
\
\
World!

This would result in 3 new lines after "Hello". To clarify, that would mean 2 empty lines between "Hello" and "World!". It would display like this:


Hello



World!



Personally I find this cleaner for a large number of line breaks compared to using <br>.

Note that backslashes are not recommended for compatibility reasons. So this may not be supported by your Markdown parser but it's handy when it is.

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

List files ONLY in the current directory

import os
for subdir, dirs, files in os.walk('./'):
    for file in files:
      do some stuff
      print file

You can improve this code with del dirs[:]which will be like following .

import os
for subdir, dirs, files in os.walk('./'):
    del dirs[:]
    for file in files:
      do some stuff
      print file

Or even better if you could point os.walk with current working directory .

import os
cwd = os.getcwd()
for subdir, dirs, files in os.walk(cwd, topdown=True):
    del dirs[:]  # remove the sub directories.
    for file in files:
      do some stuff
      print file

What is context in _.each(list, iterator, [context])?

The context parameter just sets the value of this in the iterator function.

var someOtherArray = ["name","patrick","d","w"];

_.each([1, 2, 3], function(num) { 
    // In here, "this" refers to the same Array as "someOtherArray"

    alert( this[num] ); // num is the value from the array being iterated
                        //    so this[num] gets the item at the "num" index of
                        //    someOtherArray.
}, someOtherArray);

Working Example: http://jsfiddle.net/a6Rx4/

It uses the number from each member of the Array being iterated to get the item at that index of someOtherArray, which is represented by this since we passed it as the context parameter.

If you do not set the context, then this will refer to the window object.

What is a good alternative to using an image map generator?

This one is in my opinion the best one for online (offline however dreamweaver is best): http://www.maschek.hu/imagemap/imgmap

Creating java date object from year,month,day

java.time

Using java.time framework built into Java 8

int year = 2015;
int month = 12;
int day = 22;
LocalDate.of(year, month, day); //2015-12-22
LocalDate.parse("2015-12-22"); //2015-12-22
//with custom formatter 
DateTimeFormatter.ofPattern formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate.parse("22-12-2015", formatter); //2015-12-22

If you need also information about time(hour,minute,second) use some conversion from LocalDate to LocalDateTime

LocalDate.parse("2015-12-22").atStartOfDay() //2015-12-22T00:00

Best way to find the months between two dates

Update 2018-04-20: it seems that OP @Joshkunz was asking for finding which months are between two dates, instead of "how many months" are between two dates. So I am not sure why @JohnLaRooy is upvoted for more than 100 times. @Joshkunz indicated in the comment under the original question he wanted the actual dates [or the months], instead of finding the total number of months.

So it appeared the question wanted, for between two dates 2018-04-11 to 2018-06-01

Apr 2018, May 2018, June 2018 

And what if it is between 2014-04-11 to 2018-06-01? Then the answer would be

Apr 2014, May 2014, ..., Dec 2014, Jan 2015, ..., Jan 2018, ..., June 2018

So that's why I had the following pseudo code many years ago. It merely suggested using the two months as end points and loop through them, incrementing by one month at a time. @Joshkunz mentioned he wanted the "months" and he also mentioned he wanted the "dates", without knowing exactly, it was difficult to write the exact code, but the idea is to use one simple loop to loop through the end points, and incrementing one month at a time.

The answer 8 years ago in 2010:

If adding by a week, then it will approximately do work 4.35 times the work as needed. Why not just:

1. get start date in array of integer, set it to i: [2008, 3, 12], 
       and change it to [2008, 3, 1]
2. get end date in array: [2010, 10, 26]
3. add the date to your result by parsing i
       increment the month in i
       if month is >= 13, then set it to 1, and increment the year by 1
   until either the year in i is > year in end_date, 
           or (year in i == year in end_date and month in i > month in end_date)

just pseduo code for now, haven't tested, but i think the idea along the same line will work.

how to fix Cannot call sendRedirect() after the response has been committed?

The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.

It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.

JAVA 7 OFFICIAL LINK

ADDITIONAL INFO

What Ruby IDE do you prefer?

I prefer TextMate on OS X. But Netbeans (multi-platform) is coming along quite nicely. Plus it comes with its IDE fully functional debugger.

How to remove all CSS classes using jQuery/JavaScript?

Since not all versions of jQuery are created equal, you may run into the same issue I did which means calling $("#item").removeClass(); does not actually remove the class. (Probably a bug)

A more reliable method is to simply use raw JavaScript and remove the class attribute altogether.

document.getElementById("item").removeAttribute("class");

How do I tar a directory of files and folders without including the directory itself?

cd DIRECTORY
tar -czf NAME.tar.gz  *

the asterisk will include everything even hidden ones

Stop UIWebView from "bouncing" vertically?

fixed positioning on mobile safari

This link helped me lot.....Its easy.. There is a demo..

Sorting HTML table with JavaScript

I have edited the code from one of the example here to use jquery. It's still not 100% jquery though. Any thoughts on the two different versions, like what are the pros and cons of each?

function column_sort() {
    getCellValue = (tr, idx) => $(tr).find('td').eq( idx ).text();

    comparer = (idx, asc) => (a, b) => ((v1, v2) => 
        v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
        )(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
    
    table = $(this).closest('table')[0];
    tbody = $(table).find('tbody')[0];

    elm = $(this)[0];
    children = elm.parentNode.children;
    Array.from(tbody.querySelectorAll('tr')).sort( comparer(
        Array.from(children).indexOf(elm), table.asc = !table.asc))
        .forEach(tr => tbody.appendChild(tr) );
}

table.find('thead th').on('click', column_sort);

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

The following worked for me: https://github.com/microsoft/TypeScript/issues/28631#issuecomment-472606019 I fix it by doing something like this:

const Component = (isFoo ? FooComponent : BarComponent) as React.ElementType

Specifying row names when reading in a file

If you used read.table() (or one of it's ilk, e.g. read.csv()) then the easy fix is to change the call to:

read.table(file = "foo.txt", row.names = 1, ....)

where .... are the other arguments you needed/used. The row.names argument takes the column number of the data file from which to take the row names. It need not be the first column. See ?read.table for details/info.

If you already have the data in R and can't be bothered to re-read it, or it came from another route, just set the rownames attribute and remove the first variable from the object (assuming obj is your object)

rownames(obj) <- obj[, 1]  ## set rownames
obj <- obj[, -1]           ## remove the first variable

Android Percentage Layout Height

Just as you said, I'd recommend weights. Percentages would be incredibly useful (don't know why they aren't supported), but one way you could do it is like so:

<LinearLayout
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    >
    <LinearLayout
        android:layout_height="0dp"
        android:layout_width="fill_parent"
        android:layout_weight="1"
        >
    </LinearLayout>
    <View
        android:layout_height="0dp"
        android:layout_width="fill_parent"
        android:layout_weight="1"
    />
</LinearLayout>

The takeaway being that you have an empty View that will take up the remaining space. Not ideal, but it does what you're looking for.

How to call a RESTful web service from Android?

Using Spring for Android with RestTemplate https://spring.io/guides/gs/consuming-rest-android/

// The connection URL 
String url = "https://ajax.googleapis.com/ajax/" + 
    "services/search/web?v=1.0&q={query}";

// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();

// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

// Make the HTTP GET request, marshaling the response to a String
String result = restTemplate.getForObject(url, String.class, "Android");

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

The LoggerFactory class is msising according to the error message:

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

Apparently, the slf4j.jar file is not getting loaded for some reason.

Import JSON file in React

This old chestnut...

In short, you should be using require and letting node handle the parsing as part of the require call, not outsourcing it to a 3rd party module. You should also be taking care that your configs are bulletproof, which means you should check the returned data carefully.

But for brevity's sake, consider the following example:

For Example, let's say I have a config file 'admins.json' in the root of my app containing the following:

admins.json
[{
  "userName": "tech1337",
  "passSalted": "xxxxxxxxxxxx"
}]

Note the quoted keys, "userName", "passSalted"!

I can do the following and get the data out of the file with ease.

let admins = require('~/app/admins.json');
console.log(admins[0].userName);

Now the data is in and can be used as a regular (or array of) object.

How to include clean target in Makefile?

The best thing is probably to create a variable that holds your binaries:

binaries=code1 code2

Then use that in the all-target, to avoid repeating:

all: clean $(binaries)

Now, you can use this with the clean-target, too, and just add some globs to catch object files and stuff:

.PHONY: clean

clean:
    rm -f $(binaries) *.o

Note use of the .PHONY to make clean a pseudo-target. This is a GNU make feature, so if you need to be portable to other make implementations, don't use it.

How to extract text from a PDF file?

I am adding code to accomplish this: It is working fine for me:

# This works in python 3
# required python packages
# tabula-py==1.0.0
# PyPDF2==1.26.0
# Pillow==4.0.0
# pdfminer.six==20170720

import os
import shutil
import warnings
from io import StringIO

import requests
import tabula
from PIL import Image
from PyPDF2 import PdfFileWriter, PdfFileReader
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage

warnings.filterwarnings("ignore")


def download_file(url):
    local_filename = url.split('/')[-1]
    local_filename = local_filename.replace("%20", "_")
    r = requests.get(url, stream=True)
    print(r)
    with open(local_filename, 'wb') as f:
        shutil.copyfileobj(r.raw, f)

    return local_filename


class PDFExtractor():
    def __init__(self, url):
        self.url = url

    # Downloading File in local
    def break_pdf(self, filename, start_page=-1, end_page=-1):
        pdf_reader = PdfFileReader(open(filename, "rb"))
        # Reading each pdf one by one
        total_pages = pdf_reader.numPages
        if start_page == -1:
            start_page = 0
        elif start_page < 1 or start_page > total_pages:
            return "Start Page Selection Is Wrong"
        else:
            start_page = start_page - 1

        if end_page == -1:
            end_page = total_pages
        elif end_page < 1 or end_page > total_pages - 1:
            return "End Page Selection Is Wrong"
        else:
            end_page = end_page

        for i in range(start_page, end_page):
            output = PdfFileWriter()
            output.addPage(pdf_reader.getPage(i))
            with open(str(i + 1) + "_" + filename, "wb") as outputStream:
                output.write(outputStream)

    def extract_text_algo_1(self, file):
        pdf_reader = PdfFileReader(open(file, 'rb'))
        # creating a page object
        pageObj = pdf_reader.getPage(0)

        # extracting extract_text from page
        text = pageObj.extractText()
        text = text.replace("\n", "").replace("\t", "")
        return text

    def extract_text_algo_2(self, file):
        pdfResourceManager = PDFResourceManager()
        retstr = StringIO()
        la_params = LAParams()
        device = TextConverter(pdfResourceManager, retstr, codec='utf-8', laparams=la_params)
        fp = open(file, 'rb')
        interpreter = PDFPageInterpreter(pdfResourceManager, device)
        password = ""
        max_pages = 0
        caching = True
        page_num = set()

        for page in PDFPage.get_pages(fp, page_num, maxpages=max_pages, password=password, caching=caching,
                                      check_extractable=True):
            interpreter.process_page(page)

        text = retstr.getvalue()
        text = text.replace("\t", "").replace("\n", "")

        fp.close()
        device.close()
        retstr.close()
        return text

    def extract_text(self, file):
        text1 = self.extract_text_algo_1(file)
        text2 = self.extract_text_algo_2(file)

        if len(text2) > len(str(text1)):
            return text2
        else:
            return text1

    def extarct_table(self, file):

        # Read pdf into DataFrame
        try:
            df = tabula.read_pdf(file, output_format="csv")
        except:
            print("Error Reading Table")
            return

        print("\nPrinting Table Content: \n", df)
        print("\nDone Printing Table Content\n")

    def tiff_header_for_CCITT(self, width, height, img_size, CCITT_group=4):
        tiff_header_struct = '<' + '2s' + 'h' + 'l' + 'h' + 'hhll' * 8 + 'h'
        return struct.pack(tiff_header_struct,
                           b'II',  # Byte order indication: Little indian
                           42,  # Version number (always 42)
                           8,  # Offset to first IFD
                           8,  # Number of tags in IFD
                           256, 4, 1, width,  # ImageWidth, LONG, 1, width
                           257, 4, 1, height,  # ImageLength, LONG, 1, lenght
                           258, 3, 1, 1,  # BitsPerSample, SHORT, 1, 1
                           259, 3, 1, CCITT_group,  # Compression, SHORT, 1, 4 = CCITT Group 4 fax encoding
                           262, 3, 1, 0,  # Threshholding, SHORT, 1, 0 = WhiteIsZero
                           273, 4, 1, struct.calcsize(tiff_header_struct),  # StripOffsets, LONG, 1, len of header
                           278, 4, 1, height,  # RowsPerStrip, LONG, 1, lenght
                           279, 4, 1, img_size,  # StripByteCounts, LONG, 1, size of extract_image
                           0  # last IFD
                           )

    def extract_image(self, filename):
        number = 1
        pdf_reader = PdfFileReader(open(filename, 'rb'))

        for i in range(0, pdf_reader.numPages):

            page = pdf_reader.getPage(i)

            try:
                xObject = page['/Resources']['/XObject'].getObject()
            except:
                print("No XObject Found")
                return

            for obj in xObject:

                try:

                    if xObject[obj]['/Subtype'] == '/Image':
                        size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
                        data = xObject[obj]._data
                        if xObject[obj]['/ColorSpace'] == '/DeviceRGB':
                            mode = "RGB"
                        else:
                            mode = "P"

                        image_name = filename.split(".")[0] + str(number)

                        print(xObject[obj]['/Filter'])

                        if xObject[obj]['/Filter'] == '/FlateDecode':
                            data = xObject[obj].getData()
                            img = Image.frombytes(mode, size, data)
                            img.save(image_name + "_Flate.png")
                            # save_to_s3(imagename + "_Flate.png")
                            print("Image_Saved")

                            number += 1
                        elif xObject[obj]['/Filter'] == '/DCTDecode':
                            img = open(image_name + "_DCT.jpg", "wb")
                            img.write(data)
                            # save_to_s3(imagename + "_DCT.jpg")
                            img.close()
                            number += 1
                        elif xObject[obj]['/Filter'] == '/JPXDecode':
                            img = open(image_name + "_JPX.jp2", "wb")
                            img.write(data)
                            # save_to_s3(imagename + "_JPX.jp2")
                            img.close()
                            number += 1
                        elif xObject[obj]['/Filter'] == '/CCITTFaxDecode':
                            if xObject[obj]['/DecodeParms']['/K'] == -1:
                                CCITT_group = 4
                            else:
                                CCITT_group = 3
                            width = xObject[obj]['/Width']
                            height = xObject[obj]['/Height']
                            data = xObject[obj]._data  # sorry, getData() does not work for CCITTFaxDecode
                            img_size = len(data)
                            tiff_header = self.tiff_header_for_CCITT(width, height, img_size, CCITT_group)
                            img_name = image_name + '_CCITT.tiff'
                            with open(img_name, 'wb') as img_file:
                                img_file.write(tiff_header + data)

                            # save_to_s3(img_name)
                            number += 1
                except:
                    continue

        return number

    def read_pages(self, start_page=-1, end_page=-1):

        # Downloading file locally
        downloaded_file = download_file(self.url)
        print(downloaded_file)

        # breaking PDF into number of pages in diff pdf files
        self.break_pdf(downloaded_file, start_page, end_page)

        # creating a pdf reader object
        pdf_reader = PdfFileReader(open(downloaded_file, 'rb'))

        # Reading each pdf one by one
        total_pages = pdf_reader.numPages

        if start_page == -1:
            start_page = 0
        elif start_page < 1 or start_page > total_pages:
            return "Start Page Selection Is Wrong"
        else:
            start_page = start_page - 1

        if end_page == -1:
            end_page = total_pages
        elif end_page < 1 or end_page > total_pages - 1:
            return "End Page Selection Is Wrong"
        else:
            end_page = end_page

        for i in range(start_page, end_page):
            # creating a page based filename
            file = str(i + 1) + "_" + downloaded_file

            print("\nStarting to Read Page: ", i + 1, "\n -----------===-------------")

            file_text = self.extract_text(file)
            print(file_text)
            self.extract_image(file)

            self.extarct_table(file)
            os.remove(file)
            print("Stopped Reading Page: ", i + 1, "\n -----------===-------------")

        os.remove(downloaded_file)


# I have tested on these 3 pdf files
# url = "http://s3.amazonaws.com/NLP_Project/Original_Documents/Healthcare-January-2017.pdf"
url = "http://s3.amazonaws.com/NLP_Project/Original_Documents/Sample_Test.pdf"
# url = "http://s3.amazonaws.com/NLP_Project/Original_Documents/Sazerac_FS_2017_06_30%20Annual.pdf"
# creating the instance of class
pdf_extractor = PDFExtractor(url)

# Getting desired data out
pdf_extractor.read_pages(15, 23)

How to get Tensorflow tensor dimensions (shape) as int values?

for a 2-D tensor, you can get the number of rows and columns as int32 using the following code:

rows, columns = map(lambda i: i.value, tensor.get_shape())

How to add background-image using ngStyle (angular2)?

Mostly the image is not displayed because you URL contains spaces. In your case you almost did everything correct. Except one thing - you have not added single quotes like you do if you specify background-image in css I.e.

.bg-img {                \/          \/
    background-image: url('http://...');
}

To do so escape quot character in HTML via \'

                                          \/                                  \/
<div [ngStyle]="{'background-image': 'url(\''+ item.color.catalogImageLink + '\')'}"></div>

Cannot execute script: Insufficient memory to continue the execution of the program

use the command-line tool SQLCMD which is much leaner on memory. It is as simple as:

SQLCMD -d <database-name> -i filename.sql

You need valid credentials to access your SQL Server instance or even to access a database

Taken from here.

git visual diff between branches

Here is how to see the visual diff between whole commits, as opposed to single files, in Visual Studio (tested in VS 2017). Unfortunately, it works only for commits within one branch: In the "Team Explorer", choose the "Branches" view, right-click on the repo, and choose "View history" as in the following image.

enter image description here

Then the history of the current branch appears in the main area. (Where branches that ended as earlier commits on the current branch are marked by labels.) Now select a couple of commits with Ctrl-Left, then right click and select "Compare Commits..." from the pop-up menu.

For more on comparing branches in the Microsoft world, see this stackoverflow question: Differences between git branches using Visual Studio.

Select only rows if its value in a particular column is less than the value in the other column

If you use dplyr package you can do:

library(dplyr)
filter(df, aged <= laclen)

Encoding an image file with base64

import base64
from PIL import Image
from io import BytesIO

with open("image.jpg", "rb") as image_file:
    data = base64.b64encode(image_file.read())

im = Image.open(BytesIO(base64.b64decode(data)))
im.save('image1.png', 'PNG')

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

Expanding on Tony's answer, and also answering Dhaval Ptl's question, to get the true accordion effect and only allow one row to be expanded at a time, an event handler for show.bs.collapse can be added like so:

$('.collapse').on('show.bs.collapse', function () {
    $('.collapse.in').collapse('hide');
});

I modified his example to do this here: http://jsfiddle.net/QLfMU/116/

Remove old Fragment from fragment manager

You need to find reference of existing Fragment and remove that fragment using below code. You need add/commit fragment using one tag ex. "TAG_FRAGMENT".

Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if(fragment != null)
    getSupportFragmentManager().beginTransaction().remove(fragment).commit();

That is it.

Force hide address bar in Chrome on Android

window.scrollTo(0,1);

this will help you but this javascript is may not work in all browsers

What's the best way to determine the location of the current PowerShell script?

For PowerShell 3+

function Get-ScriptDirectory {
    if ($psise) {
        Split-Path $psise.CurrentFile.FullPath
    }
    else {
        $global:PSScriptRoot
    }
}

I've placed this function in my profile. It works in ISE using F8/Run Selection too.

Calling a Javascript Function from Console

you can invoke it using window.function_name() or directly function_name()

Check if a variable exists in a list in Bash

Consider exploiting the keys of associative arrays. I would presume this outperforms both regex/pattern matching and looping, although I haven't profiled it.

declare -A list=( [one]=1 [two]=two [three]='any non-empty value' )
for value in one two three four
do
    echo -n "$value is "
    # a missing key expands to the null string, 
    # and we've set each interesting key to a non-empty value
    [[ -z "${list[$value]}" ]] && echo -n '*not* '
    echo "a member of ( ${!list[*]} )"
done

Output:

one is a member of ( one two three )
two is a member of ( one two three )
three is a member of ( one two three )
four is *not* a member of ( one two three )

How to force a SQL Server 2008 database to go Offline

You need to use WITH ROLLBACK IMMEDIATE to boot other conections out with no regards to what or who is is already using it.

Or use WITH NO_WAIT to not hang and not kill existing connections. See http://www.blackwasp.co.uk/SQLOffline.aspx for details

Why does one use dependency injection?

I think the classic answer is to create a more decoupled application, which has no knowledge of which implementation will be used during runtime.

For example, we're a central payment provider, working with many payment providers around the world. However, when a request is made, I have no idea which payment processor I'm going to call. I could program one class with a ton of switch cases, such as:

class PaymentProcessor{

    private String type;

    public PaymentProcessor(String type){
        this.type = type;
    }

    public void authorize(){
        if (type.equals(Consts.PAYPAL)){
            // Do this;
        }
        else if(type.equals(Consts.OTHER_PROCESSOR)){
            // Do that;
        }
    }
}

Now imagine that now you'll need to maintain all this code in a single class because it's not decoupled properly, you can imagine that for every new processor you'll support, you'll need to create a new if // switch case for every method, this only gets more complicated, however, by using Dependency Injection (or Inversion of Control - as it's sometimes called, meaning that whoever controls the running of the program is known only at runtime, and not complication), you could achieve something very neat and maintainable.

class PaypalProcessor implements PaymentProcessor{

    public void authorize(){
        // Do PayPal authorization
    }
}

class OtherProcessor implements PaymentProcessor{

    public void authorize(){
        // Do other processor authorization
    }
}

class PaymentFactory{

    public static PaymentProcessor create(String type){

        switch(type){
            case Consts.PAYPAL;
                return new PaypalProcessor();

            case Consts.OTHER_PROCESSOR;
                return new OtherProcessor();
        }
    }
}

interface PaymentProcessor{
    void authorize();
}

** The code won't compile, I know :)

How can I create a dynamic button click event on a dynamic button?

Simply add the eventhandler to the button when creating it.

 button.Click += new EventHandler(this.button_Click);

void button_Click(object sender, System.EventArgs e)
{
//your stuff...
}

What causing this "Invalid length for a Base-64 char array"

This isn't an answer, sadly. After running into the intermittent error for some time and finally being annoyed enough to try to fix it, I have yet to find a fix. I have, however, determined a recipe for reproducing my problem, which might help others.

In my case it is SOLELY a localhost problem, on my dev machine that also has the app's DB. It's a .NET 2.0 app I'm editing with VS2005. The Win7 64 bit machine also has VS2008 and .NET 3.5 installed.

Here's what will generate the error, from a variety of forms:

  1. Load a fresh copy of the form.
  2. Enter some data, and/or postback with any of the form's controls. As long as there is no significant delay, repeat all you like, and no errors occur.
  3. Wait a little while (1 or 2 minutes maybe, not more than 5), and try another postback.

A minute or two delay "waiting for localhost" and then "Connection was reset" by the browser, and global.asax's application error trap logs:

Application_Error event: Invalid length for a Base-64 char array.
Stack Trace:
     at System.Convert.FromBase64String(String s)
     at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
     at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState)
     at System.Web.UI.HiddenFieldPageStatePersister.Load()

In this case, it is not the SIZE of the viewstate, but something to do with page and/or viewstate caching that seems to be biting me. Setting <pages> parameters enableEventValidation="false", and viewStateEncryption="Never" in the Web.config did not change the behavior. Neither did setting the maxPageStateFieldLength to something modest.

Differences between unique_ptr and shared_ptr

When wrapping a pointer in a unique_ptr you cannot have multiple copies of unique_ptr. The shared_ptr holds a reference counter which count the number of copies of the stored pointer. Each time a shared_ptr is copied, this counter is incremented. Each time a shared_ptr is destructed, this counter is decremented. When this counter reaches 0, then the stored object is destroyed.

What is the best way to declare global variable in Vue.js?

As you need access to your hostname variable in every component, and to change it to localhost while in development mode, or to production hostname when in production mode, you can define this variable in the prototype.

Like this:

Vue.prototype.$hostname = 'http://localhost:3000'

And $hostname will be available in all Vue instances:

new Vue({
  beforeCreate: function () {
    console.log(this.$hostname)
  }
})

In my case, to automatically change from development to production, I've defined the $hostname prototype according to a Vue production tip variable in the file where I instantiated the Vue.

Like this:

Vue.config.productionTip = false
Vue.prototype.$hostname = (Vue.config.productionTip) ? 'https://hostname' : 'http://localhost:3000'

An example can be found in the docs: Documentation on Adding Instance Properties

More about production tip config can be found here:

Vue documentation for production tip

Pattern matching using a wildcard

If you want to examine elements inside a dataframe you should not be using ls() which only looks at the names of objects in the current workspace (or if used inside a function in the current environment). Rownames or elements inside such objects are not visible to ls() (unless of course you add an environment argument to the ls(.)-call). Try using grep() which is the workhorse function for pattern matching of character vectors:

result <- a[ grep("blue", a$x) , ]  # Note need to use `a$` to get at the `x`

If you want to use subset then consider the closely related function grepl() which returns a vector of logicals can be used in the subset argument:

subset(a, grepl("blue", a$x))
      x
2 blue1
3 blue2

Edit: Adding one "proper" use of glob2rx within subset():

result <- subset(a,  grepl(glob2rx("blue*") , x) )
result
      x
2 blue1
3 blue2

I don't think I actually understood glob2rx until I came back to this question. (I did understand the scoping issues that were ar the root of the questioner's difficulties. Anybody reading this should now scroll down to Gavin's answer and upvote it.)

How to use private Github repo as npm dependency

I wasn't able to make the accepted answer work in a Docker container.

What worked for me was to set the Personal Access Token from github in a file .nextrc

ARG GITHUB_READ_TOKEN
RUN echo -e "machine github.com\n  login $GITHUB_READ_TOKEN" > ~/.netrc 
RUN npm install --only=production --force \
  && npm cache clean --force
RUN rm ~/.netrc

in package.json

"my-lib": "github:username/repo",

Inline CSS styles in React: how to implement a:hover?

onMouseOver and onMouseLeave with setState at first seemed like a bit of overhead to me - but as this is how react works, it seems the easiest and cleanest solution to me.

rendering a theming css serverside for example, is also a good solution and keeps the react components more clean.

if you dont have to append dynamic styles to elements ( for example for a theming ) you should not use inline styles at all but use css classes instead.

this is a traditional html/css rule to keep html / JSX clean and simple.

Java, Shifting Elements in an Array

Just for completeness: Stream solution since Java 8.

final String[] shiftedArray = Arrays.stream(array)
        .skip(1)
        .toArray(String[]::new);

I think I sticked with the System.arraycopy() in your situtation. But the best long-term solution might be to convert everything to Immutable Collections (Guava, Vavr), as long as those collections are short-lived.

What does it mean by select 1 from table?

This means that You want a value "1" as output or Most of the time used as Inner Queries because for some reason you want to calculate the outer queries based on the result of inner queries.. not all the time you use 1 but you have some specific values...

This will statically gives you output as value 1.

Install npm (Node.js Package Manager) on Windows (w/o using Node.js MSI)

I also needed to install npm in Windows and got it through the Chocolatey pacakage manager. For those who haven't heard about it, Chocolatey is a package manager for Windows, that gives you the convenience of an apt-get in Windows environments. To get it go to https://chocolatey.org/ where there's a PowerShell script to download it and install it. After that you can run:

chocolatey install npm

and you're good to go.

Note that the standalone npm is no longer being updated and the last version that is out there is known to have problems on Windows. Another option you can look at is extracting npm from the MSI using LessMSI.

How to execute a bash command stored as a string with quotes and asterisk

To eliminate the need for the cmd variable, you can do this:

eval 'mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'

Best Practice: Software Versioning

I start versioning at the lowest (non hotfix) segement. I do not limit this segment to 10. Unless you are tracking builds then you just need to decide when you want to apply an increment. If you have a QA phase then that might be where you apply an increment to the lowest segment and then the next segement up when it passes QA and is released. Leave the topmost segment for Major behavior/UI changes.

If you are like me you will make it a hybrid of the methods so as to match the pace of your software's progression.

I think the most accepted pattern a.b.c. or a.b.c.d especially if you have QA/Compliance in the mix. I have had so much flack around date being a regular part of versions that I gave it up for mainstream.

I do not track builds so I like to use the a.b.c pattern unless a hotfix is involved. When I have to apply a hotfix then I apply parameter d as a date with time. I adopted the time parameter as d because there is always the potential of several in a day when things really blow up in production. I only apply the d segment (YYYYMMDDHHNN) when I'm diverging for a production fix.

I personally wouldn't be opposed to a software scheme of va.b revc where c is YYYYMMDDHHMM or YYYYMMDD.

All that said. If you can just snag a tool to configure and run with it will keep you from the headache having to marshall the opinion facet of versioning and you can just say "use the tool"... because everyone in the development process is typically so compliant.

IE7 Z-Index Layering Issues

http://www.vancelucas.com/blog/fixing-ie7-z-index-issues-with-jquery/

$(function() {
var zIndexNumber = 1000;
$('div').each(function() {
    $(this).css('zIndex', zIndexNumber);
    zIndexNumber -= 10;
});
});

How to get numbers after decimal point?

Another crazy solution is (without converting in a string):

number = 123.456
temp = 1

while (number*temp)%10 != 0:
    temp = temp *10
    print temp
    print number

temp = temp /10
number = number*temp
number_final = number%temp
print number_final

Why is the console window closing immediately once displayed my output?

To simplify what others are saying: Use Console.ReadKey();.

This makes it so the program is waiting on the user to press a normal key on the keyboard

Source: I use it in my programs for console applications.

How can I set Image source with base64

Try using setAttribute instead:

document.getElementById('img')
    .setAttribute(
        'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
    );

Real answer: (And make sure you remove the line-breaks in the base64.)

SQL Server - Return value after INSERT

After doing an insert into a table with an identity column, you can reference @@IDENTITY to get the value: http://msdn.microsoft.com/en-us/library/aa933167%28v=sql.80%29.aspx

Change the default base url for axios

Putting my two cents here. I wanted to do the same without hardcoding the URL for my specific request. So i came up with this solution.

To append 'api' to my baseURL, I have my default baseURL set as,

axios.defaults.baseURL = '/api/';

Then in my specific request, after explicitly setting the method and url, i set the baseURL to '/'

axios({
    method:'post',
    url:'logout',
    baseURL: '/',
   })
   .then(response => {
      window.location.reload();
   })
   .catch(error => {
       console.log(error);
   });

How can I write a byte array to a file in Java?

As of Java 1.7, there's a new way: java.nio.file.Files.write

import java.nio.file.Files;
import java.nio.file.Paths;

KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
byte[] encoded = key.getEncoded();
Files.write(Paths.get("target-file"), encoded);

Java 1.7 also resolves the embarrassment that Kevin describes: reading a file is now:

byte[] data = Files.readAllBytes(Paths.get("source-file"));

How to use enums in C++

If we want the strict type safety and scoped enum, using enum class is good in C++11.

If we had to work in C++98, we can using the advice given by InitializeSahib,San to enable the scoped enum.

If we also want the strict type safety, the follow code can implement somthing like enum.

#include <iostream>
class Color
{
public:
    static Color RED()
    {
        return Color(0);
    }
    static Color BLUE()
    {
        return Color(1);
    }
    bool operator==(const Color &rhs) const
    {
        return this->value == rhs.value;
    }
    bool operator!=(const Color &rhs) const
    {
        return !(*this == rhs);
    }

private:
    explicit Color(int value_) : value(value_) {}
    int value;
};

int main()
{
    Color color = Color::RED();
    if (color == Color::RED())
    {
        std::cout << "red" << std::endl;
    }
    return 0;
}

The code is modified from the class Month example in book Effective C++ 3rd: Item 18

How do I remove a key from a JavaScript object?

It's as easy as:

delete object.keyname;

or

delete object["keyname"];

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

How to format date with hours, minutes and seconds when using jQuery UI Datepicker?

$("#datepicker").datepicker("option", "dateFormat", "yy-mm-dd ");

For the time picker, you should add timepicker to Datepicker, and it would be formatted with one equivalent command.

EDIT

Use this one that extend jQuery UI Datepicker. You can pick up both date and time.

http://trentrichardson.com/examples/timepicker/

How do you format a Date/Time in TypeScript?

Option 1: Momentjs:

Install:

npm install moment --save

Import:

import * as moment from 'moment';

Usage:

let formattedDate = (moment(yourDate)).format('DD-MMM-YYYY HH:mm:ss')

Option 2: Use DatePipe if you are doing Angular:

Import:

import { DatePipe } from '@angular/common';

Usage:

const datepipe: DatePipe = new DatePipe('en-US')
let formattedDate = datepipe.transform(yourDate, 'DD-MMM-YYYY HH:mm:ss')

How do I delete specific lines in Notepad++?

You can try doing a replace of #region with \n, turning extended search mode on.

Changing directory in Google colab (breaking out of the python interpreter)

use

%cd SwitchFrequencyAnalysis

to change the current working directory for the notebook environment (and not just the subshell that runs your ! command).

you can confirm it worked with the pwd command like this:

!pwd

further information about jupyter / ipython magics: http://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-cd

VBScript - How to make program wait until process has finished?

Probably something like this? (UNTESTED)

Sub Sample()
    Dim strWB4, strMyMacro
    strMyMacro = "Sheet1.my_macro_name"

    '
    '~~> Rest of Code
    '

    'loop through the folder and get the file names
    For Each Fil In FLD.Files
        Set x4WB = x1.Workbooks.Open(Fil)
        x4WB.Application.Visible = True

        x1.Run strMyMacro

        x4WB.Close

        Do Until IsWorkBookOpen(Fil) = False
            DoEvents
        Loop
    Next

    '
    '~~> Rest of Code
    '
End Sub

'~~> Function to check if the file is open
Function IsWorkBookOpen(FileName As String)
    Dim ff As Long, ErrNo As Long

    On Error Resume Next
    ff = FreeFile()
    Open FileName For Input Lock Read As #ff
    Close ff
    ErrNo = Err
    On Error GoTo 0

    Select Case ErrNo
    Case 0:    IsWorkBookOpen = False
    Case 70:   IsWorkBookOpen = True
    Case Else: Error ErrNo
    End Select
End Function

Add one day to date in javascript

Note that Date.getDate only returns the day of the month. You can add a day by calling Date.setDate and appending 1.

// Create new Date instance
var date = new Date()

// Add a day
date.setDate(date.getDate() + 1)

JavaScript will automatically update the month and year for you.

EDIT:
Here's a link to a page where you can find all the cool stuff about the built-in Date object, and see what's possible: Date.

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

Cause you need to add jQuery library to your file:

jQuery UI is just an addon to jQuery which means that
first you need to include the jQuery library → and then the UI.

<script src="path/to/your/jquery.min.js"></script>
<script src="path/to/your/jquery.ui.min.js"></script>

In Java, how can I determine if a char array contains a particular character?

This method does the trick.

boolean contains(char c, char[] array) {
    for (char x : array) {
        if (x == c) {
            return true;
        }
    }
    return false;
}

Example of usage:

class Main {

    static boolean contains(char c, char[] array) {
        for (char x : array) {
            if (x == c) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] a) {
        char[] charArray = new char[] {'h','e','l','l','o'};
        if (!contains('q', charArray)) {
            // Do something...
            System.out.println("Hello world!");
        }
    }

}

Alternative way:

if (!String.valueOf(charArray).contains("q")) {
    // do something...
}

How to trigger HTML button when you press Enter in textbox?

Based on some previous answers, I came up with this:

<form>
  <button id='but' type='submit'>do not click me</button>
  <input type='text' placeholder='press enter'>
</form>

$('#but').click(function(e) {
  alert('button press');
  e.preventDefault();
});

Take a look at the Fiddle

EDIT: If you dont want to add additional html elements, you can do this with JS only:

    $("input").keyup(function(event) {
        if (event.keyCode === 13) {
            $("button").click();
        }
    });     

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

Stored procedures can be executed like below

 string cmd = Constants.StoredProcs.usp_AddRoles.ToString() + " @userId, @roleIdList";
                        int result = db.Database
                                       .ExecuteSqlCommand
                                       (
                                          cmd,
                                           new SqlParameter("@userId", userId),
                                           new SqlParameter("@roleIdList", roleId)
                                       );

How to replace (or strip) an extension from a filename in Python?

Expanding on AnaPana's answer, how to remove an extension using pathlib (Python >= 3.4):

>>> from pathlib import Path

>>> filename = Path('/some/path/somefile.txt')

>>> filename_wo_ext = filename.with_suffix('')

>>> filename_replace_ext = filename.with_suffix('.jpg')

>>> print(filename)
/some/path/somefile.ext    

>>> print(filename_wo_ext)
/some/path/somefile

>>> print(filename_replace_ext)
/some/path/somefile.jpg

Match exact string

"^" For the begining of the line "$" for the end of it. Eg.:

var re = /^abc$/;

Would match "abc" but not "1abc" or "abc1". You can learn more at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

install cx_oracle for python

This just worked for me on Ubuntu 16:

Download ('instantclient-basic-linux.x64-12.2.0.1.0.zip' and 'instantclient-sdk-linux.x64-12.2.0.1.0.zip') from Oracle web site and then do following script (you can do piece by piece and I did as a ROOT):

apt-get install -y python-dev build-essential libaio1
mkdir -p /opt/ora/
cd /opt/ora/

## Now put 2 ZIP files:
# ('instantclient-basic-linux.x64-12.2.0.1.0.zip' and 'instantclient-sdk-linux.x64-12.2.0.1.0.zip') 
# into /opt/ora/ and unzip them -> both will be unzipped into 1 directory: /opt/ora/instantclient_12_2 

rm -rf /etc/profile.d/oracle.sh
echo "export ORACLE_HOME=/opt/ora/instantclient_12_2"  >> /etc/profile.d/oracle.sh
echo "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME"  >> /etc/profile.d/oracle.sh
chmod 777 /etc/profile.d/oracle.sh
source /etc/profile.d/oracle.sh
env | grep -i ora  # This will check current ENVIRONMENT settings for Oracle


rm -rf /etc/ld.so.conf.d/oracle.conf
echo "/opt/ora/instantclient_12_2" >> /etc/ld.so.conf.d/oracle.conf
ldconfig
cd $ORACLE_HOME  
ls -lrth libclntsh*   # This will show which version of 'libclntsh' you have... --> needed for following line:

ln -s libclntsh.so.12.1 libclntsh.so

pip install cx_Oracle   # Maybe not needed but I did it anyway (only pip install cx_Oracle without above steps did not work for me...)

Your python scripts are now ready to use 'cx_Oracle'... Enjoy!

How to set up Automapper in ASP.NET Core

At the latest versions of asp.net core you should use the following initialization:

services.AddAutoMapper(typeof(YourMappingProfileClass));

Performing a query on a result from another query?

Usually you can plug a Query's result (which is basically a table) as the FROM clause source of another query, so something like this will be written:

SELECT COUNT(*), SUM(SUBQUERY.AGE) from
(
  SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
  FROM availables
  INNER JOIN rooms
  ON availables.room_id=rooms.id
  WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
  GROUP BY availables.bookdate
) AS SUBQUERY

Not unique table/alias

Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.

Try

    SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
      FROM Project_Assigned pa
INNER JOIN Account a
        ON pa.AccountID = a.Account_ID
INNER JOIN Project p
        ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
        ON a.Account_ID = c.Account_ID
     WHERE a.Access_Type = 'Client';

How to set space between listView Items in Android

<ListView
    android:clipToPadding="false"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:dividerHeight="10dp"
    android:divider="@null"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</ListView>

and set paddingTop, paddingBottom and dividerHeight to the same value to get equal spacing between all elements and space at the top and bottom of the list.

I set clipToPadding to false to let the views be drawn in this padded area.

I set divider to @null to remove the lines between list elements.

Disable automatic sorting on the first column when using jQuery DataTables

In the newer version of datatables (version 1.10.7) it seems things have changed. The way to prevent DataTables from automatically sorting by the first column is to set the order option to an empty array.

You just need to add the following parameter to the DataTables options:

"order": [] 

Set up your DataTable as follows in order to override the default setting:

$('#example').dataTable( {
    "order": [],
    // Your other options here...
} );

That will override the default setting of "order": [[ 0, 'asc' ]].

You can find more details regarding the order option here: https://datatables.net/reference/option/order

How to access model hasMany Relation with where condition?

//lower for v4 some version

public function videos() {
    $instance =$this->hasMany('Video');
    $instance->getQuery()->where('available','=', 1);
    return $instance
}

//v5

public function videos() {
    return $this->hasMany('Video')->where('available','=', 1);
}

How to get the number of columns in a matrix?

While size(A,2) is correct, I find it's much more readable to first define

rows = @(x) size(x,1); 
cols = @(x) size(x,2);

and then use, for example, like this:

howManyColumns_in_A = cols(A)
howManyRows_in_A    = rows(A)

It might appear as a small saving, but size(.., 1) and size(.., 2) must be some of the most commonly used functions, and they are not optimally readable as-is.

Difference between using Throwable and Exception in a try catch

Throwable is super class of Exception as well as Error. In normal cases we should always catch sub-classes of Exception, so that the root cause doesn't get lost.

Only special cases where you see possibility of things going wrong which is not in control of your Java code, you should catch Error or Throwable.

I remember catching Throwable to flag that a native library is not loaded.

How can I do SELECT UNIQUE with LINQ?

Using query comprehension syntax you could achieve the orderby as follows:

var uniqueColors = (from dbo in database.MainTable
                    where dbo.Property
                    orderby dbo.Color.Name ascending
                    select dbo.Color.Name).Distinct();

How to turn on/off MySQL strict mode in localhost (xampp)?

To change it permanently in Windows (10), edit the my.ini file. To find the my.ini file, look at the path in the Windows server. E.g. for my MySQL 5.7 instance, the service is MYSQL57, and in this service's properties the Path to executable is:

"C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqld.exe" --defaults-file="C:\ProgramData\MySQL\MySQL Server 5.7\my.ini" MySQL57

I.e. edit the my.ini file in C:\ProgramData\MySQL\MySQL Server 5.7\. Note that C:\ProgramData\ is a hidden folder in Windows (10). My file has the following lines of interest:

# Set the SQL mode to strict
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Remove STRICT_TRANS_TABLES, from this sql-mode line, save the file and restart the MYSQL57 service. Verify the result by executing SHOW VARIABLES LIKE 'sql_mode'; in a (new) MySQL Command Line Client window.

(I found the other answers and documents on the web useful, but none of them seem to tell you where to find the my.ini file in Windows.)

Using GregorianCalendar with SimpleDateFormat

tl;dr

LocalDate.parse(
    "23-Mar-2017" ,
    DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) 
)

Avoid legacy date-time classes

The Question and other Answers are now outdated, using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

Using java.time

You seem to be dealing with date-only values. So do not use a date-time class. Instead use LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.

Specify a Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.

Parse a string.

String input = "23-Mar-2017" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f );

Generate a string.

String output = ld.format( f );

If you were given numbers rather than text for the year, month, and day-of-month, use LocalDate.of.

LocalDate ld = LocalDate.of( 2017 , 3 , 23 );  // ( year , month 1-12 , day-of-month )

See this code run live at IdeOne.com.

input: 23-Mar-2017

ld.toString(): 2017-03-23

output: 23-Mar-2017


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to check if variable is array?... or something array-like

PHP 7.1.0 has introduced the iterable pseudo-type and the is_iterable() function, which is specially designed for such a purpose:

This […] proposes a new iterable pseudo-type. This type is analogous to callable, accepting multiple types instead of one single type.

iterable accepts any array or object implementing Traversable. Both of these types are iterable using foreach and can be used with yield from within a generator.

function foo(iterable $iterable) {
    foreach ($iterable as $value) {
        // ...
    }
}

This […] also adds a function is_iterable() that returns a boolean: true if a value is iterable and will be accepted by the iterable pseudo-type, false for other values.

var_dump(is_iterable([1, 2, 3])); // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(is_iterable((function () { yield 1; })())); // bool(true)
var_dump(is_iterable(1)); // bool(false)
var_dump(is_iterable(new stdClass())); // bool(false)

You can also use the function is_array($var) to check if the passed variable is an array:

<?php
    var_dump( is_array(array()) ); // true
    var_dump( is_array(array(1, 2, 3)) ); // true
    var_dump( is_array($_SERVER) ); // true
?>

Read more in How to check if a variable is an array in PHP?

how to display a javascript var in html body

Use document.write().

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <script type="text/javascript">_x000D_
    var number = 123;_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <h1>_x000D_
      the value for number is:_x000D_
      <script type="text/javascript">_x000D_
        document.write(number)_x000D_
      </script>_x000D_
    </h1>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

try to compile

 compile 'com.android.support:cardview-v7:25.3.1'

What does "both" mean in <div style="clear:both">

Description of the possible values:

  • left: No floating elements allowed on the left side
  • right: No floating elements allowed on the right side
  • both: No floating elements allowed on either the left or the right side
  • none: Default. Allows floating elements on both sides
  • inherit: Specifies that the value of the clear property should be inherited from the parent element

Source: w3schools.com

What is the fastest way to transpose a matrix in C++?

intel mkl suggests in-place and out-of-place transposition/copying matrices. here is the link to the documentation. I would recommend trying out of place implementation as faster ten in-place and into the documentation of the latest version of mkl contains some mistakes.

How do I use installed packages in PyCharm?

You should never need to modify the path directly, either through environment variables or sys.path. Whether you use the os (ex. apt-get), or pip in a virtualenv, packages will be installed to a location already on the path.

In your example, GNU Radio is installed to the system Python 2's standard site-packages location, which is already in the path. Pointing PyCharm at the correct interpreter is enough; if it isn't there is something else wrong that isn't apparent. It may be that /usr/bin/python does not point to the same interpreter that GNU Radio was installed in; try pointing specifically at the python2.7 binary. Or, PyCharm used to be somewhat bad at detecting packages; File > Invalidate Caches > Invalidate and Restart would tell it to rescan.

This answer will cover how you should set up a project environment, install packages in different scenarios, and configure PyCharm. I refer multiple times to the Python Packaging User Guide, written by the same group that maintains the official Python packaging tools.


The correct way to develop a Python application is with a virtualenv. Packages and version are installed without affecting the system or other projects. PyCharm has a built-in interface to create a virtualenv and install packages. Or you can create it from the command line and then point PyCharm at it.

$ cd MyProject
$ python2 -m virtualenv env
$ . env/bin/activate
$ pip install -U pip setuptools  # get the latest versions
$ pip install flask  # install other packages

In your PyCharm project, go to File > Settings > Project > Project Interpreter. If you used virtualenvwrapper or PyCharm to create the env, then it should show up in the menu. If not, click the gear, choose Add Local, and locate the Python binary in the env. PyCharm will display all the packages in the selected env.

choose an env

manually locate env


In some cases, such as with GNU Radio, there is no package to install with pip, the package was installed system-wide when you install the rest of GNU Radio (ex. apt-get install gnuradio). In this case, you should still use a virtualenv, but you'll need to make it aware of this system package.

$ python2 -m virtualenv --system-site-packages env

Unfortunately it looks a little messy, because all system packages will now appear in your env, but they are just links, you can still safely install or upgrade packages without affecting the system.


In some cases, you will have multiple local packages you're developing, and will want one project to use the other package. In this case you might think you have to add the local package to the other project's path, but this is not the case. You should install your package in development mode. All this requires is adding a setup.py file to your package, which will be required anyway to properly distribute and deploy the package later.

Minimal setup.py for your first project:

from setuptools import setup, find_packages

setup(
    name='mypackage',
    version='0.1',
    packages=find_packages(),
)

Then install it in your second project's env:

$ pip install -e /path/to/first/project

How can I set the background color of <option> in a <select> element?

Just like normal background-color: #f0f

You just need a way to target it, eg: <option id="myPinkOption">blah</option>

Get push notification while App in foreground iOS

Objective C

enter image description here

For iOS 10 we need integrate willPresentNotification method for show notification banner in foreground.

If app in foreground mode(active)

- (void)userNotificationCenter:(UNUserNotificationCenter* )center willPresentNotification:(UNNotification* )notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
    NSLog( @"Here handle push notification in foreground" ); 
    //For notification Banner - when app in foreground
    
    completionHandler(UNNotificationPresentationOptionAlert);
    
    // Print Notification info
    NSLog(@"Userinfo %@",notification.request.content.userInfo);
}

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can do it faster without any imports just by using magics:

%env CUDA_DEVICE_ORDER=PCI_BUS_ID
%env CUDA_VISIBLE_DEVICES=0

Notice that all env variable are strings, so no need to use ". You can verify that env-variable is set up by running: %env <name_of_var>. Or check all of them with %env.

VHDL - How should I create a clock in a testbench?

How to use a clock and do assertions

This example shows how to generate a clock, and give inputs and assert outputs for every cycle. A simple counter is tested here.

The key idea is that the process blocks run in parallel, so the clock is generated in parallel with the inputs and assertions.

library ieee;
use ieee.std_logic_1164.all;

entity counter_tb is
end counter_tb;

architecture behav of counter_tb is
    constant width : natural := 2;
    constant clk_period : time := 1 ns;

    signal clk : std_logic := '0';
    signal data : std_logic_vector(width-1 downto 0);
    signal count : std_logic_vector(width-1 downto 0);

    type io_t is record
        load : std_logic;
        data : std_logic_vector(width-1 downto 0);
        count : std_logic_vector(width-1 downto 0);
    end record;
    type ios_t is array (natural range <>) of io_t;
    constant ios : ios_t := (
        ('1', "00", "00"),
        ('0', "UU", "01"),
        ('0', "UU", "10"),
        ('0', "UU", "11"),

        ('1', "10", "10"),
        ('0', "UU", "11"),
        ('0', "UU", "00"),
        ('0', "UU", "01")
    );
begin
    counter_0: entity work.counter port map (clk, load, data, count);

    process
    begin
        for i in ios'range loop
            load <= ios(i).load;
            data <= ios(i).data;
            wait until falling_edge(clk);
            assert count = ios(i).count;
        end loop;
        wait;
    end process;

    process
    begin
        for i in 1 to 2 * ios'length loop
            wait for clk_period / 2;
            clk <= not clk;
        end loop;
        wait;
    end process;
end behav;

The counter would look like this:

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all; -- unsigned

entity counter is
    generic (
        width : in natural := 2
    );
    port (
        clk, load : in std_logic;
        data : in std_logic_vector(width-1 downto 0);
        count : out std_logic_vector(width-1 downto 0)
    );
end entity counter;

architecture rtl of counter is
    signal cnt : unsigned(width-1 downto 0);
begin
    process(clk) is
    begin
        if rising_edge(clk) then
            if load = '1' then
                cnt <= unsigned(data);
            else
                cnt <= cnt + 1;
            end if;
        end if;
    end process;
    count <= std_logic_vector(cnt);
end architecture rtl;

Related: https://electronics.stackexchange.com/questions/148320/proper-clock-generation-for-vhdl-testbenches

Convert string into Date type on Python

You can do that with datetime.strptime()

Example:

>>> from datetime import datetime
>>> datetime.strptime('2012-02-10' , '%Y-%m-%d')
datetime.datetime(2012, 2, 10, 0, 0)
>>> _.isoweekday()
5

You can find the table with all the strptime directive here.


To increment by 2 days if .isweekday() == 6, you can use timedelta():

>>> import datetime
>>> date = datetime.datetime.strptime('2012-02-11' , '%Y-%m-%d')
>>> if date.isoweekday() == 6:
...     date += datetime.timedelta(days=2)
... 
>>> date
datetime.datetime(2012, 2, 13, 0, 0)
>>> date.strftime('%Y-%m-%d')   # if you want a string again
'2012-02-13'

maxReceivedMessageSize and maxBufferSize in app.config

Open app.config on client side and add maxBufferSize and maxReceivedMessageSize attributes if it is not available

Original

  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="Service1Soap"/>
      </basicHttpBinding>
    </bindings>

After Edit/Update

  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="Service1Soap" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"/>
      </basicHttpBinding>
    </bindings>

NOT IN vs NOT EXISTS

I always default to NOT EXISTS.

The execution plans may be the same at the moment but if either column is altered in the future to allow NULLs the NOT IN version will need to do more work (even if no NULLs are actually present in the data) and the semantics of NOT IN if NULLs are present are unlikely to be the ones you want anyway.

When neither Products.ProductID or [Order Details].ProductID allow NULLs the NOT IN will be treated identically to the following query.

SELECT ProductID,
       ProductName
FROM   Products p
WHERE  NOT EXISTS (SELECT *
                   FROM   [Order Details] od
                   WHERE  p.ProductId = od.ProductId) 

The exact plan may vary but for my example data I get the following.

Neither NULL

A reasonably common misconception seems to be that correlated sub queries are always "bad" compared to joins. They certainly can be when they force a nested loops plan (sub query evaluated row by row) but this plan includes an anti semi join logical operator. Anti semi joins are not restricted to nested loops but can use hash or merge (as in this example) joins too.

/*Not valid syntax but better reflects the plan*/ 
SELECT p.ProductID,
       p.ProductName
FROM   Products p
       LEFT ANTI SEMI JOIN [Order Details] od
         ON p.ProductId = od.ProductId 

If [Order Details].ProductID is NULL-able the query then becomes

SELECT ProductID,
       ProductName
FROM   Products p
WHERE  NOT EXISTS (SELECT *
                   FROM   [Order Details] od
                   WHERE  p.ProductId = od.ProductId)
       AND NOT EXISTS (SELECT *
                       FROM   [Order Details]
                       WHERE  ProductId IS NULL) 

The reason for this is that the correct semantics if [Order Details] contains any NULL ProductIds is to return no results. See the extra anti semi join and row count spool to verify this that is added to the plan.

One NULL

If Products.ProductID is also changed to become NULL-able the query then becomes

SELECT ProductID,
       ProductName
FROM   Products p
WHERE  NOT EXISTS (SELECT *
                   FROM   [Order Details] od
                   WHERE  p.ProductId = od.ProductId)
       AND NOT EXISTS (SELECT *
                       FROM   [Order Details]
                       WHERE  ProductId IS NULL)
       AND NOT EXISTS (SELECT *
                       FROM   (SELECT TOP 1 *
                               FROM   [Order Details]) S
                       WHERE  p.ProductID IS NULL) 

The reason for that one is because a NULL Products.ProductId should not be returned in the results except if the NOT IN sub query were to return no results at all (i.e. the [Order Details] table is empty). In which case it should. In the plan for my sample data this is implemented by adding another anti semi join as below.

Both NULL

The effect of this is shown in the blog post already linked by Buckley. In the example there the number of logical reads increase from around 400 to 500,000.

Additionally the fact that a single NULL can reduce the row count to zero makes cardinality estimation very difficult. If SQL Server assumes that this will happen but in fact there were no NULL rows in the data the rest of the execution plan may be catastrophically worse, if this is just part of a larger query, with inappropriate nested loops causing repeated execution of an expensive sub tree for example.

This is not the only possible execution plan for a NOT IN on a NULL-able column however. This article shows another one for a query against the AdventureWorks2008 database.

For the NOT IN on a NOT NULL column or the NOT EXISTS against either a nullable or non nullable column it gives the following plan.

Not EXists

When the column changes to NULL-able the NOT IN plan now looks like

Not In - Null

It adds an extra inner join operator to the plan. This apparatus is explained here. It is all there to convert the previous single correlated index seek on Sales.SalesOrderDetail.ProductID = <correlated_product_id> to two seeks per outer row. The additional one is on WHERE Sales.SalesOrderDetail.ProductID IS NULL.

As this is under an anti semi join if that one returns any rows the second seek will not occur. However if Sales.SalesOrderDetail does not contain any NULL ProductIDs it will double the number of seek operations required.

Javascript how to parse JSON array

Just as a heads up...

var data = JSON.parse(responseBody);

has been deprecated.

Postman Learning Center now suggests

var jsonData = pm.response.json();

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.

What does the colon (:) operator do?

It will prints the string"something" three times.

JLabel[] labels = {new JLabel(), new JLabel(), new JLabel()};                   

for ( JLabel label : labels )                  
 {              
   label.setText("something");  

 panel.add(label);             
 }

How do I check particular attributes exist or not in XML?

EDIT

Disregard - you can't use ItemOf (that's what I get for typing before I test). I'd strikethrough the text if I could figure out how...or maybe I'll simply delete the answer, since it was ultimately wrong and useless.

END EDIT

You can use the ItemOf(string) property in the XmlAttributesCollection to see if the attribute exists. It returns null if it's not found.

foreach (XmlNode xNode in nodeListName)
{
    if (xNode.ParentNode.Attributes.ItemOf["split"] != null)
    {
         parentSplit = xNode.ParentNode.Attributes["split"].Value;
    }
}

XmlAttributeCollection.ItemOf Property (String)

Spring mvc @PathVariable

suppose you want to write a url to fetch some order, you can say

www.mydomain.com/order/123

where 123 is orderId.

So now the url you will use in spring mvc controller would look like

/order/{orderId}

Now order id can be declared a path variable

@RequestMapping(value = " /order/{orderId}", method=RequestMethod.GET)
public String getOrder(@PathVariable String orderId){
//fetch order
}

if you use url www.mydomain.com/order/123, then orderId variable will be populated by value 123 by spring

Also note that PathVariable differs from requestParam as pathVariable is part of URL. The same url using request param would look like www.mydomain.com/order?orderId=123

API DOC
Spring Official Reference

How to mark-up phone numbers?

The tel: scheme was used in the late 1990s and documented in early 2000 with RFC 2806 (which was obsoleted by the more-thorough RFC 3966 in 2004) and continues to be improved. Supporting tel: on the iPhone was not an arbitrary decision.

callto:, while supported by Skype, is not a standard and should be avoided unless specifically targeting Skype users.

Me? I'd just start including properly-formed tel: URIs on your pages (without sniffing the user agent) and wait for the rest of the world's phones to catch up :) .

Example:

_x000D_
_x000D_
<a href="tel:+18475555555">1-847-555-5555</a>
_x000D_
_x000D_
_x000D_

How to get substring of NSString?

Here's a slightly less complicated answer:

NSString *myString = @"abcdefg";
NSString *mySmallerString = [myString substringToIndex:4];

See also substringWithRange and substringFromIndex

How to present a modal atop the current view in Swift

This worked for me in Swift 5.0. Set the Storyboard Id in the identity inspector as "destinationVC".

@IBAction func buttonTapped(_ sender: Any) {
    let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: Bundle.main)
    let destVC = storyboard.instantiateViewController(withIdentifier: "destinationVC") as! MyViewController

    destVC.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
    destVC.modalTransitionStyle = UIModalTransitionStyle.crossDissolve

    self.present(destVC, animated: true, completion: nil)
}

How to get current route

For your purposes you can use this.activatedRoute.pathFromRoot.

import {ActivatedRoute} from "@angular/router";
constructor(public activatedRoute: ActivatedRoute){

}

With the help of pathFromRoot you can get the list of parent urls and check if the needed part of the URL matches your condition.

For additional information please check this article http://blog.2muchcoffee.com/getting-current-state-in-angular2-router/ or install ng2-router-helper from npm

npm install ng2-router-helper

Show values from a MySQL database table inside a HTML table on a webpage

Object-Oriented with PHP/5.6.25 and MySQL/5.7.17 using MySQLi [Dynamic]

Learn more about PHP and the MySQLi Library at PHP.net.

First, start a connection to the database. Do this by making all the string variables needed in order to connect, adjust them to fit your environment, then create a new connection object with new mysqli() and initialize it with the previously made variables as its parameters. Now, check the connection for errors and display a message whether any were found or not. Like this:

<?php
$servername = "localhost";
$username = "root";
$password = "yourPassword";
$database = "world";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $database);
echo "Connected successfully<br>";
?>

Next, make a variable that will hold the query as a string, in this case its a select statement with a limit of 100 records to keep the list small. Then, we can execute it by calling the mysqli::query() function from our connection object. Now, it's time to display some data. Start by opening up a <table> tag through echo, then fetch one row at a time in the form of a numerical array with mysqli::fetch_row() which can then be displayed with a simple for loop. mysqli::field_count should be self explanatory. Don't forget to use <td></td> for each value, and also to open and close each row with echo"<tr>" and echo"</tr>. Finally we close the table, and the connection as well with mysqli::close().

<?php
$query = "select * from city limit 100;";
$queryResult = $conn->query($query);
echo "<table>";
while ($queryRow = $queryResult->fetch_row()) {
    echo "<tr>";
    for($i = 0; $i < $queryResult->field_count; $i++){
        echo "<td>$queryRow[$i]</td>";
    }
    echo "</tr>";
}
echo "</table>";
$conn->close();
?>

Named placeholders in string formatting

Based on the answer I created MapBuilder class:

public class MapBuilder {

    public static Map<String, Object> build(Object... data) {
        Map<String, Object> result = new LinkedHashMap<>();

        if (data.length % 2 != 0) {
            throw new IllegalArgumentException("Odd number of arguments");
        }

        String key = null;
        Integer step = -1;

        for (Object value : data) {
            step++;
            switch (step % 2) {
                case 0:
                    if (value == null) {
                        throw new IllegalArgumentException("Null key value");
                    }
                    key = (String) value;
                    continue;
                case 1:
                    result.put(key, value);
                    break;
            }
        }

        return result;
    }

}

then I created class StringFormat for String formatting:

public final class StringFormat {

    public static String format(String format, Object... args) {
        Map<String, Object> values = MapBuilder.build(args);

        for (Map.Entry<String, Object> entry : values.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            format = format.replace("$" + key, value.toString());
        }

        return format;
    }

}

which you could use like that:

String bookingDate = StringFormat.format("From $startDate to $endDate"), 
        "$startDate", formattedStartDate, 
        "$endDate", formattedEndDate
);

How do I abort/cancel TPL Tasks?

You can abort a task like a thread if you can cause the task to be created on its own thread and call Abort on its Thread object. By default, a task runs on a thread pool thread or the calling thread - neither of which you typically want to abort.

To ensure the task gets its own thread, create a custom scheduler derived from TaskScheduler. In your implementation of QueueTask, create a new thread and use it to execute the task. Later, you can abort the thread, which will cause the task to complete in a faulted state with a ThreadAbortException.

Use this task scheduler:

class SingleThreadTaskScheduler : TaskScheduler
{
    public Thread TaskThread { get; private set; }

    protected override void QueueTask(Task task)
    {
        TaskThread = new Thread(() => TryExecuteTask(task));
        TaskThread.Start();
    }

    protected override IEnumerable<Task> GetScheduledTasks() => throw new NotSupportedException(); // Unused
    protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => throw new NotSupportedException(); // Unused
}

Start your task like this:

var scheduler = new SingleThreadTaskScheduler();
var task = Task.Factory.StartNew(action, cancellationToken, TaskCreationOptions.LongRunning, scheduler);

Later, you can abort with:

scheduler.TaskThread.Abort();

Note that the caveat about aborting a thread still applies:

The Thread.Abort method should be used with caution. Particularly when you call it to abort a thread other than the current thread, you do not know what code has executed or failed to execute when the ThreadAbortException is thrown, nor can you be certain of the state of your application or any application and user state that it is responsible for preserving. For example, calling Thread.Abort may prevent static constructors from executing or prevent the release of unmanaged resources.

Setting a checkbox as checked with Vue.js

I experienced this issue and couldn't figure out a fix for a few hours, until I realised I had incorrectly prevented native events from occurring with:

<input type="checkbox" @click.prevent="toggleConfirmedStatus(render.uuid)"
    :checked="confirmed.indexOf(render.uuid) > -1"
    :value="render.uuid"
/>

removing the .prevent from the @click handler fixed my issue.

how to open .mat file without using MATLAB?

Download Notepad++ (notepad-plus-plus.org) it opens nearly any file format and recognizes breaks, comments and does all the same color coding as the original language formatting.

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

The best source I have for this kind of question is this page: http://www.quirksmode.org/js/keys.html

What they say is that the key codes are odd on Safari, and consistent everywhere else (except that there's no keypress event on IE, but I believe keydown works).

Persistent invalid graphics state error when using ggplot2

I ran into this same error and solved it by running:

dev.off()

and then running the plot again. I think the graphics device was messed up earlier somehow by exporting some graphics and it didn't get reset. This worked for me and it's simpler than reinstalling ggplot2.

System.Drawing.Image to stream C#

Use a memory stream

using(MemoryStream ms = new MemoryStream())
{
    image.Save(ms, ...);
    return ms.ToArray();
}

Differences between contentType and dataType in jQuery ajax function

enter image description here

In English:

  • ContentType: When sending data to the server, use this content type. Default is application/x-www-form-urlencoded; charset=UTF-8, which is fine for most cases.
  • Accepts: The content type sent in the request header that tells the server what kind of response it will accept in return. Depends on DataType.
  • DataType: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response. Can be text, xml, html, script, json, jsonp.

How can I create a temp file with a specific extension with .NET?

You can also do the following

string filename = Path.ChangeExtension(Path.GetTempFileName(), ".csv");

and this also works as expected

string filename = Path.ChangeExtension(Path.GetTempPath() + Guid.NewGuid().ToString(), ".csv");

How to print a specific row of a pandas DataFrame?

Sounds like you're calling df.plot(). That error indicates that you're trying to plot a frame that has no numeric data. The data types shouldn't affect what you print().

Use print(df.iloc[159220])

Change column type in pandas

How about this?

a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['one', 'two', 'three'])
df
Out[16]: 
  one  two three
0   a  1.2   4.2
1   b   70  0.03
2   x    5     0

df.dtypes
Out[17]: 
one      object
two      object
three    object

df[['two', 'three']] = df[['two', 'three']].astype(float)

df.dtypes
Out[19]: 
one       object
two      float64
three    float64

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

Another possible cause for this error message is if the HTTP Method is blocked by the server or load balancer.

It seems to be standard security practice to block unused HTTP Methods. We ran into this because HEAD was being blocked by the load balancer (but, oddly, not all of the load balanced servers, which caused it to fail only some of the time). I was able to test that the request itself worked fine by temporarily changing it to use the GET method.

The error code on iOS was: Error requesting App Code: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

Escaping ampersand character in SQL string

I know it sucks. None of the above things were really working, but I found a work around. Please be extra careful to use spaces between the apostrophes [ ' ], otherwise it will get escaped.

SELECT 'Hello ' '&' ' World';

Hello & World

You're welcome ;)

How to revert initial git commit?

All what you have to do is to revert the commit.

git revert {commit_id}'

Then push it

git push origin -f

'Framework not found' in Xcode

Please after adding both framework also open each Bolts and Parse framework and add Parse and Bolts to the project then problem will be solve

ASP.NET Core return JSON with status code

The cleanest solution I have found is to set the following in my ConfigureServices method in Startup.cs (In my case I want the TZ info stripped. I always want to see the date time as the user saw it).

   services.AddControllers()
                .AddNewtonsoftJson(o =>
                {
                    o.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Unspecified;
                });

The DateTimeZoneHandling options are Utc, Unspecified, Local or RoundtripKind

I would still like to find a way to be able to request this on a per-call bases.

something like

  static readonly JsonMediaTypeFormatter _jsonFormatter = new JsonMediaTypeFormatter();
 _jsonFormatter.SerializerSettings = new JsonSerializerSettings()
                {DateTimeZoneHandling = DateTimeZoneHandling.Unspecified};

return Ok("Hello World", _jsonFormatter );

I am converting from ASP.NET and there I used the following helper method

public static ActionResult<T> Ok<T>(T result, HttpContext context)
    {
        var responseMessage = context.GetHttpRequestMessage().CreateResponse(HttpStatusCode.OK, result, _jsonFormatter);
        return new ResponseMessageResult(responseMessage);
    }

VBA Date as integer

You can use bellow code example for date string like mdate and Now() like toDay, you can also calculate deference between both date like Aging

Public Sub test(mdate As String)
    Dim toDay As String
    mdate = Round(CDbl(CDate(mdate)), 0)
    toDay = Round(CDbl(Now()), 0)
    Dim Aging as String
    Aging = toDay - mdate
    MsgBox ("So aging is -" & Aging & vbCr & "from the date - " & _
    Format(mdate, "dd-mm-yyyy")) & " to " & Format(toDay, "dd-mm-yyyy"))
End Sub

NB: Used CDate for convert Date String to Valid Date

I am using this in Office 2007 :)

How to get response using cURL in PHP

am using this simple one

´´´´ class Connect {

public $url;
public $path;
public $username;
public $password;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $this->url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");

    //PROPFIND request that lists all requested properties.
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PROPFIND");
    $response = curl_exec($ch);

    curl_close($ch);

jQuery UI DatePicker - Change Date Format

This works smoothly. Try this.

Paste these links in your head section.

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript"
        src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Following is the JS coding.

 <script>

        $(document).ready(function () {
            $('#completionDate').datepicker({
                dateFormat: 'yy-mm-dd', // enter date format you prefer (e.g. 2018-10-09)
                changeMonth: true,
                changeYear: true,
                yearRange: "-50:+10",
                clickInput: true,

                onSelect: function (date) {
                    loadMusterChit();
                }

            });
        });

    </script>

Insert line break inside placeholder attribute of a textarea?

UPDATE (Jan 2016): The nice little hack might not work on all browsers anymore so I have a new solution with a tiny bit of javascript below.


A Nice Little Hack

It doesn't feel nice, but you can just put the new lines in the html. Like this:

_x000D_
_x000D_
<textarea rows="6" id="myAddress" type="text" placeholder="My Awesome House,
1 Long St
London
Postcode
UK"></textarea>
_x000D_
_x000D_
_x000D_

Notice each line is on a new line (not being wrapped) and each 'tab' indent is 4 spaces. Granted it is not a very nice method, but it seems to work:

http://jsfiddle.net/01taylop/HDfju/

  • It is likely that the indent level of each line will vary depending on the width of your text area.
  • It is important to have resize: none; in the css so that the size of the textarea is fixed (See jsfiddle).

Alternatively When you want a new line, hit return twice (So there is a empty line between your 'new lines'. This 'empty line' created needs to have enough tabs/spaces that would equate to the width of your textarea. It doesn't seem to matter if you have far too many, you just need enough. This is so dirty though and probably not browser compliant. I wish there was an easier way!


A Better Solution

Check out the JSFiddle.

  • This solution positions a div behind the textarea.
  • Some javascript is used to change the background colour of the textarea, hiding or revealing the placeholder appropriately.
  • The inputs and placeholders must have the same font sizes, hence the two mixins.
  • The box-sizing and display: block properties on the textarea are important or the div behind it will not be the same size.
  • Setting resize: vertical and a min-height on the textarea are also important - notice how the placeholder text will wrap and expanding the textarea will keep the white background. However, commenting out the resize property will cause issues when expanding the textarea horizontally.
  • Just make sure the min-height on the textarea is enough to cover your entire placeholder at its smallest width.**

JSFiddle Screenshot

HTML:

<form>
  <input type='text' placeholder='First Name' />
  <input type='text' placeholder='Last Name' />
  <div class='textarea-placeholder'>
    <textarea></textarea>
    <div>
      First Line
      <br /> Second Line
      <br /> Third Line
    </div>
  </div>
</form>

SCSS:

$input-padding: 4px;

@mixin input-font() {
  font-family: 'HelveticaNeue-Light', 'Helvetica Neue Light', 'Helvetica Neue', Helvetica, Arial, 'Lucida Grande', sans-serif;
  font-size: 12px;
  font-weight: 300;
  line-height: 16px;
}

@mixin placeholder-style() {
  color: #999;
  @include input-font();
}

* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

form {
  width: 250px;
}

input,textarea {
  display: block;
  width: 100%;
  padding: $input-padding;
  border: 1px solid #ccc;
}

input {
  margin-bottom: 10px;
  background-color: #fff;

  @include input-font();
}

textarea {
  min-height: 80px;
  resize: vertical;
  background-color: transparent;
  &.data-edits {
    background-color: #fff;
  }
}

.textarea-placeholder {
  position: relative;
  > div {
    position: absolute;
    z-index: -1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    padding: $input-padding;
    background-color: #fff;
    @include placeholder-style();
  }
}

::-webkit-input-placeholder {
  @include placeholder-style();
}
:-moz-placeholder {
  @include placeholder-style();
}
::-moz-placeholder {
  @include placeholder-style();
}
:-ms-input-placeholder {
  @include placeholder-style();
}

Javascript:

$("textarea").on('change keyup paste', function() {
  var length = $(this).val().length;
  if (length > 0) {
    $(this).addClass('data-edits');
  } else {
    $(this).removeClass('data-edits');
  }
});

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

Either the parameter supplied for ZIP_CODE is larger (in length) than ZIP_CODEs column width or the parameter supplied for CITY is larger (in length) than CITYs column width.

It would be interesting to know the values supplied for the two ? placeholders.

ERROR 1049 (42000): Unknown database

Very simple solution. Just rename your database and configure your new database name in your project.

The problem is the when you import your database, you got any errors and then the database will be corrupted. The log files will have the corrupted database name. You can rename your database easily using phpmyadmin for mysql.

phpmyadmin -> operations -> Rename database to

Getting unique values in Excel by using formulas only

Resorting to a PivotTable might not count as using formulas only but seems more practical that most other suggestions so far:

SO1429899 example

Display an array in a readable/hierarchical format

if someone needs to view arrays so cool ;) use this method.. this will print to your browser console

function console($obj)
{
    $js = json_encode($obj);
    print_r('<script>console.log('.$js.')</script>');
}

you can use like this..

console($myObject);

Output will be like this.. so cool eh !!

enter image description here

How can I remove an entry in global configuration with git config?

You can edit the ~/.gitconfig file in your home folder. This is where all --global settings are saved.

How to make IPython notebook matplotlib plot inline

I did the anaconda install but matplotlib is not plotting

It starts plotting when i did this

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline  

Fastest way to iterate over all the chars in a String

Despite @Saint Hill's answer if you consider the time complexity of str.toCharArray(),

the first one is faster even for very large strings. You can run the code below to see it for yourself.

        char [] ch = new char[1_000_000_00];
    String str = new String(ch); // to create a large string

    // ---> from here
    long currentTime = System.nanoTime();
    for (int i = 0, n = str.length(); i < n; i++) {
        char c = str.charAt(i);
    }
    // ---> to here
    System.out.println("str.charAt(i):"+(System.nanoTime()-currentTime)/1000000.0 +" (ms)");

    /**
     *   ch = str.toCharArray() itself takes lots of time   
     */
    // ---> from here
    currentTime = System.nanoTime();
    ch = str.toCharArray();
    for (int i = 0, n = str.length(); i < n; i++) {
        char c = ch[i];
    }
    // ---> to  here
    System.out.println("ch = str.toCharArray() + c = ch[i] :"+(System.nanoTime()-currentTime)/1000000.0 +" (ms)");

output:

str.charAt(i):5.492102 (ms)
ch = str.toCharArray() + c = ch[i] :79.400064 (ms)

React-router: How to manually invoke Link?

In the version 5.x, you can use useHistory hook of react-router-dom:

// Sample extracted from https://reacttraining.com/react-router/core/api/Hooks/usehistory
import { useHistory } from "react-router-dom";

function HomeButton() {
  const history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

How to install grunt and how to build script with it

To setup GruntJS build here is the steps:

  1. Make sure you have setup your package.json or setup new one:

    npm init
    
  2. Install Grunt CLI as global:

    npm install -g grunt-cli
    
  3. Install Grunt in your local project:

    npm install grunt --save-dev
    
  4. Install any Grunt Module you may need in your build process. Just for sake of this sample I will add Concat module for combining files together:

    npm install grunt-contrib-concat --save-dev
    
  5. Now you need to setup your Gruntfile.js which will describe your build process. For this sample I just combine two JS files file1.js and file2.js in the js folder and generate app.js:

    module.exports = function(grunt) {
    
        // Project configuration.
        grunt.initConfig({
            concat: {
                "options": { "separator": ";" },
                "build": {
                    "src": ["js/file1.js", "js/file2.js"],
                    "dest": "js/app.js"
                }
            }
        });
    
        // Load required modules
        grunt.loadNpmTasks('grunt-contrib-concat');
    
        // Task definitions
        grunt.registerTask('default', ['concat']);
    };
    
  6. Now you'll be ready to run your build process by following command:

    grunt
    

I hope this give you an idea how to work with GruntJS build.

NOTE:

You can use grunt-init for creating Gruntfile.js if you want wizard-based creation instead of raw coding for step 5.

To do so, please follow these steps:

npm install -g grunt-init
git clone https://github.com/gruntjs/grunt-init-gruntfile.git ~/.grunt-init/gruntfile
grunt-init gruntfile

For Windows users: If you are using cmd.exe you need to change ~/.grunt-init/gruntfile to %USERPROFILE%\.grunt-init\. PowerShell will recognize the ~ correctly.

How to store a dataframe using Pandas

You can use feather format file. It is extremely fast.

df.to_feather('filename.ft')

Java method to sum any number of ints

Use var args

public long sum(int... numbers){
      if(numbers == null){ return 0L;}
      long result = 0L;
      for(int number: numbers){
         result += number;
      }
      return result;   
}

Is there a way to iterate over a range of integers?

You can also check out github.com/wushilin/stream

It is a lazy stream like concept of java.util.stream.

// It doesn't really allocate the 10 elements.
stream1 := stream.Range(0, 10)

// Print each element.
stream1.Each(print)

// Add 3 to each element, but it is a lazy add.
// You only add when consume the stream
stream2 := stream1.Map(func(i int) int {
    return i + 3
})

// Well, this consumes the stream => return sum of stream2.
stream2.Reduce(func(i, j int) int {
    return i + j
})

// Create stream with 5 elements
stream3 := stream.Of(1, 2, 3, 4, 5)

// Create stream from array
stream4 := stream.FromArray(arrayInput)

// Filter stream3, keep only elements that is bigger than 2,
// and return the Sum, which is 12
stream3.Filter(func(i int) bool {
    return i > 2
}).Sum()

Hope this helps

How to implement a tree data-structure in Java?

For example :

import java.util.ArrayList;
import java.util.List;



/**
 * 
 * @author X2
 *
 * @param <T>
 */
public class HisTree<T> 
{
    private Node<T> root;

    public HisTree(T rootData) 
    {
        root = new Node<T>();
        root.setData(rootData);
        root.setChildren(new ArrayList<Node<T>>());
    }

}

class Node<T> 
{

    private T data;
    private Node<T> parent;
    private List<Node<T>> children;

    public T getData() {
        return data;
    }
    public void setData(T data) {
        this.data = data;
    }
    public Node<T> getParent() {
        return parent;
    }
    public void setParent(Node<T> parent) {
        this.parent = parent;
    }
    public List<Node<T>> getChildren() {
        return children;
    }
    public void setChildren(List<Node<T>> children) {
        this.children = children;
    }
}

How can I get a resource content from a static context?

My Kotlin solution is to use a static Application context:

class App : Application() {
    companion object {
        lateinit var instance: App private set
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
    }
}

And the Strings class, that I use everywhere:

object Strings {
    fun get(@StringRes stringRes: Int, vararg formatArgs: Any = emptyArray()): String {
        return App.instance.getString(stringRes, *formatArgs)
    }
}

So you can have a clean way of getting resource strings

Strings.get(R.string.some_string)
Strings.get(R.string.some_string_with_arguments, "Some argument")

Please don't delete this answer, let me keep one.

Using Mockito's generic "any()" method

As I needed to use this feature for my latest project (at one point we updated from 1.10.19), just to keep the users (that are already using the mockito-core version 2.1.0 or greater) up to date, the static methods from the above answers should be taken from ArgumentMatchers class:

import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.ArgumentMatchers.any;

Please keep this in mind if you are planning to keep your Mockito artefacts up to date as possibly starting from version 3, this class may no longer exist:

As per 2.1.0 and above, Javadoc of org.mockito.Matchers states:

Use org.mockito.ArgumentMatchers. This class is now deprecated in order to avoid a name clash with Hamcrest * org.hamcrest.Matchers class. This class will likely be removed in version 3.0.

I have written a little article on mockito wildcards if you're up for further reading.

How to get a subset of a javascript object's properties

An Array of Objects

const aListOfObjects = [{
    prop1: 50,
    prop2: "Nothing",
    prop3: "hello",
    prop4: "What's up",
  },
  {
    prop1: 88,
    prop2: "Whatever",
    prop3: "world",
    prop4: "You get it",
  },
]

Making a subset of an object or objects can be achieved by destructuring the object this way.

const sections = aListOfObjects.map(({prop1, prop2}) => ({prop1, prop2}));

Maximum length of the textual representation of an IPv6 address?

Answered my own question:

IPv6 addresses are normally written as eight groups of four hexadecimal digits, where each group is separated by a colon (:).

So that's 39 characters max.

Angularjs $q.all

The issue seems to be that you are adding the deffered.promise when deffered is itself the promise you should be adding:

Try changing to promises.push(deffered); so you don't add the unwrapped promise to the array.

 UploadService.uploadQuestion = function(questions){

            var promises = [];

            for(var i = 0 ; i < questions.length ; i++){

                var deffered  = $q.defer();
                var question  = questions[i]; 

                $http({

                    url   : 'upload/question',
                    method: 'POST',
                    data  : question
                }).
                success(function(data){
                    deffered.resolve(data);
                }).
                error(function(error){
                    deffered.reject();
                });

                promises.push(deffered);
            }

            return $q.all(promises);
        }

How do I write a custom init for a UIView subclass in Swift?

The init(frame:) version is the default initializer. You must call it only after initializing your instance variables. If this view is being reconstituted from a Nib then your custom initializer will not be called, and instead the init?(coder:) version will be called. Since Swift now requires an implementation of the required init?(coder:), I have updated the example below and changed the let variable declarations to var and optional. In this case, you would initialize them in awakeFromNib() or at some later time.

class TestView : UIView {
    var s: String?
    var i: Int?
    init(s: String, i: Int) {
        self.s = s
        self.i = i
        super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

How to add custom validation to an AngularJS form?

Update:

Improved and simplified version of previous directive (one instead of two) with same functionality:

.directive('myTestExpression', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ctrl) {
            var expr = attrs.myTestExpression;
            var watches = attrs.myTestExpressionWatch;

            ctrl.$validators.mytestexpression = function (modelValue, viewValue) {
                return expr == undefined || (angular.isString(expr) && expr.length < 1) || $parse(expr)(scope, { $model: modelValue, $view: viewValue }) === true;
            };

            if (angular.isString(watches)) {
                angular.forEach(watches.split(",").filter(function (n) { return !!n; }), function (n) {
                    scope.$watch(n, function () {
                        ctrl.$validate();
                    });
                });
            }
        }
    };
}])

Example usage:

<input ng-model="price1" 
       my-test-expression="$model > 0" 
       my-test-expression-watch="price2,someOtherWatchedPrice" />
<input ng-model="price2" 
       my-test-expression="$model > 10" 
       my-test-expression-watch="price1" 
       required />

Result: Mutually dependent test expressions where validators are executed on change of other's directive model and current model.

Test expression has local $model variable which you should use to compare it to other variables.

Previously:

I've made an attempt to improve @Plantface code by adding extra directive. This extra directive very useful if our expression needs to be executed when changes are made in more than one ngModel variables.

.directive('ensureExpression', ['$parse', function($parse) {
    return {
        restrict: 'A',
        require: 'ngModel',
        controller: function () { },
        scope: true,
        link: function (scope, element, attrs, ngModelCtrl) {
            scope.validate = function () {
                var booleanResult = $parse(attrs.ensureExpression)(scope);
                ngModelCtrl.$setValidity('expression', booleanResult);
            };

            scope.$watch(attrs.ngModel, function(value) {
                scope.validate();
            });
        }
    };
}])

.directive('ensureWatch', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        require: 'ensureExpression',
        link: function (scope, element, attrs, ctrl) {
            angular.forEach(attrs.ensureWatch.split(",").filter(function (n) { return !!n; }), function (n) {
                scope.$watch(n, function () {
                    scope.validate();
                });
            });
        }
    };
}])

Example how to use it to make cross validated fields:

<input name="price1"
       ng-model="price1" 
       ensure-expression="price1 > price2" 
       ensure-watch="price2" />
<input name="price2" 
       ng-model="price2" 
       ensure-expression="price2 > price3" 
       ensure-watch="price3" />
<input name="price3" 
       ng-model="price3" 
       ensure-expression="price3 > price1 && price3 > price2" 
       ensure-watch="price1,price2" />

ensure-expression is executed to validate model when ng-model or any of ensure-watch variables is changed.

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

My Mac OS didn't like that it didn't find the env variable set in the settings file:

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('MY_SERVER_ENV_VAR_NAME')

but after adding the env var to my local Mac OS dev environment, the error disappeared:

export MY_SERVER_ENV_VAR_NAME ='fake dev security key that is longer than 50 characters.'

In my case, I also needed to add the --settings param:

python3 manage.py check --deploy --settings myappname.settings.production

where production.py is a file containing production specific settings inside a settings folder.

Query to list all users of a certain group

memberOf (in AD) is stored as a list of distinguishedNames. Your filter needs to be something like:

(&(objectCategory=user)(memberOf=cn=MyCustomGroup,ou=ouOfGroup,dc=subdomain,dc=domain,dc=com))

If you don't yet have the distinguished name, you can search for it with:

(&(objectCategory=group)(cn=myCustomGroup))

and return the attribute distinguishedName. Case may matter.

How to run test methods in specific order in JUnit4?

With JUnit 5.4, you can specify the order :

@Test
@Order(2)
public void sendEmailTestGmail() throws MessagingException {

you just need to annotate your class

@TestMethodOrder(OrderAnnotation.class)

https://junit.org/junit5/docs/current/user-guide/#writing-tests-test-execution-order

i'm using this in my project and it works very well !

Can dplyr package be used for conditional mutating?

Use ifelse

df %>%
  mutate(g = ifelse(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               ifelse(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA)))

Added - if_else: Note that in dplyr 0.5 there is an if_else function defined so an alternative would be to replace ifelse with if_else; however, note that since if_else is stricter than ifelse (both legs of the condition must have the same type) so the NA in that case would have to be replaced with NA_real_ .

df %>%
  mutate(g = if_else(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               if_else(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA_real_)))

Added - case_when Since this question was posted dplyr has added case_when so another alternative would be:

df %>% mutate(g = case_when(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4) ~ 2,
                            a == 0 | a == 1 | a == 4 | a == 3 |  c == 4 ~ 3,
                            TRUE ~ NA_real_))

Added - arithmetic/na_if If the values are numeric and the conditions (except for the default value of NA at the end) are mutually exclusive, as is the case in the question, then we can use an arithmetic expression such that each term is multiplied by the desired result using na_if at the end to replace 0 with NA.

df %>%
  mutate(g = 2 * (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)) +
             3 * (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
         g = na_if(g, 0))

Simple PHP form: Attachment to email (code golf)

A combination of this http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php#attachment

with the php upload file example would work. In the upload file example instead of using move_uploaded_file to move it from the temporary folder you would just open it:

$attachment = chunk_split(base64_encode(file_get_contents($tmp_file))); 

where $tmp_file = $_FILES['userfile']['tmp_name'];

and send it as an attachment like the rest of the example.

All in one file / self contained:

<? if(isset($_POST['submit'])){
//process and email
}else{
//display form
}
?>

I think its a quick exercise to get what you need working based on the above two available examples.

P.S. It needs to get uploaded somewhere before Apache passes it along to PHP to do what it wants with it. That would be your system's temp folder by default unless it was changed in the config file.

"Port 4200 is already in use" when running the ng serve command

I also faced the same error msg, so i tried ng serve --port 12012 and it worked fine.

Ranges of floating point datatype in C?

As dasblinkenlight already answered, the numbers come from the way that floating point numbers are represented in IEEE-754, and Andreas has a nice breakdown of the maths.

However - be careful that the precision of floating point numbers isn't exactly 6 or 15 significant decimal digits as the table suggests, since the precision of IEEE-754 numbers depends on the number of significant binary digits.

  • float has 24 significant binary digits - which depending on the number represented translates to 6-8 decimal digits of precision.

  • double has 53 significant binary digits, which is approximately 15 decimal digits.

Another answer of mine has further explanation if you're interested.

FileNotFoundException while getting the InputStream object from HttpURLConnection

For anybody else stumbling over this, the same happened to me while trying to send a SOAP request header to a SOAP service. The issue was a wrong order in the code, I requested the input stream first before sending the XML body. In the code snipped below, the line InputStream in = conn.getInputStream(); came immediately after ByteArrayOutputStream out = new ByteArrayOutputStream(); which is the incorrect order of things.

ByteArrayOutputStream out = new ByteArrayOutputStream();
// send SOAP request as part of HTTP body 
byte[] data = request.getHttpBody().getBytes("UTF-8");
conn.getOutputStream().write(data); 

if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
  Log.d(TAG, "http response code is " + conn.getResponseCode());
  return null;
}

InputStream in = conn.getInputStream();

FileNotFound in this case was an unfortunate way to encode HTTP response code 400.

Using pickle.dump - TypeError: must be str, not bytes

Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.

import pickle

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

user = MyUser('Peter')

print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'

with open(filename,'wb') as file_object:
    file_object.write(serialized)

with open(filename,'rb') as file_object:
    raw_data = file_object.read()

deserialized = pickle.loads(raw_data)


print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")

Command not found after npm install in zsh

FOR MAC: I tried some of the above but to no avail, could not get anything to work.

I did have BREW INSTALLED, so although this not be the best approach, with zsh, I did:

  1. sudo chown -R $(whoami) /usr/local/share/man/man8 (for brew access)
  2. brew update && brew install npm (I had had node installed)
  3. npm -v (to confirm install)
  4. nano ~/.zshrc (to empty file changes and save)

This worked for me. Hope this helps someone. #1 bothers me, but I will live with for now.

How to set dialog to show in full screen?

try

Dialog dialog=new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen)

What is the difference between npm install and npm run build?

The main difference is ::

npm install is a npm cli-command which does the predefined thing i.e, as written by Churro, to install dependencies specified inside package.json

npm run command-name or npm run-script command-name ( ex. npm run build ) is also a cli-command predefined to run your custom scripts with the name specified in place of "command-name". So, in this case npm run build is a custom script command with the name "build" and will do anything specified inside it (for instance echo 'hello world' given in below example package.json).

Ponits to note::

  1. One more thing, npm build and npm run build are two different things, npm run build will do custom work written inside package.json and npm build is a pre-defined script (not available to use directly)

  2. You cannot specify some thing inside custom build script (npm run build) script and expect npm build to do the same. Try following thing to verify in your package.json:

    { "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build":"echo 'hello build'" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": {}, "dependencies": {} }

and run npm run build and npm build one by one and you will see the difference. For more about commands kindly follow npm documentation.

Cheers!!

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

@article = user.articles.build(:title => "MainTitle")
@article.save

SQL Inner-join with 3 tables?

SELECT table1.col,table2.col,table3.col 
FROM table1 
INNER JOIN 
(table2 INNER JOIN table3 
ON table3.id=table2.id) 
ON table1.id(f-key)=table2.id
AND //add any additional filters HERE

Select all elements with a "data-xxx" attribute without using jQuery

document.querySelectorAll("[data-foo]")

will get you all elements with that attribute.

document.querySelectorAll("[data-foo='1']")

will only get you ones with a value of 1.

How to run the sftp command with a password from Bash script?

You have a few options other than using public key authentication:

  1. Use keychain
  2. Use sshpass (less secured but probably that meets your requirement)
  3. Use expect (least secured and more coding needed)

If you decide to give sshpass a chance here is a working script snippet to do so:

export SSHPASS=your-password-here
sshpass -e sftp -oBatchMode=no -b - sftp-user@remote-host << !
   cd incoming
   put your-log-file.log
   bye
!

FTP/SFTP access to an Amazon S3 Bucket

Or spin Linux instance for SFTP Gateway in your AWS infrastructure that saves uploaded files to your Amazon S3 bucket.

Supported by Thorntech

Principal Component Analysis (PCA) in Python

For the sake def plot_pca(data): will work, it is necessary to replace the lines

data_resc, data_orig = PCA(data)
ax1.plot(data_resc[:, 0], data_resc[:, 1], '.', mfc=clr1, mec=clr1)

with lines

newData, data_resc, data_orig = PCA(data)
ax1.plot(newData[:, 0], newData[:, 1], '.', mfc=clr1, mec=clr1)

Git commit date

You can use the git show command.

To get the last commit date from git repository in a long(Unix epoch timestamp):

  • Command: git show -s --format=%ct
  • Result: 1605103148

Note: You can visit the git-show documentation to get a more detailed description of the options.

Jquery - How to make $.post() use contentType=application/json?

I know this is a late answer, I actually have a shortcut method that I use for posting/reading to/from MS based services.. it works with MVC as well as ASMX etc...

Use:

$.msajax(
  '/services/someservice.asmx/SomeMethod'
  ,{}  /*empty object for nothing, or object to send as Application/JSON */
  ,function(data,jqXHR) {
    //use the data from the response.
  }
  ,function(err,jqXHR) {
    //additional error handling.
  }
);
//sends a json request to an ASMX or WCF service configured to reply to JSON requests.
(function ($) {
  var tries = 0; //IE9 seems to error out the first ajax call sometimes... will retry up to 5 times

  $.msajax = function (url, data, onSuccess, onError) {
    return $.ajax({
      'type': "POST"
      , 'url': url
      , 'contentType': "application/json"
      , 'dataType': "json"
      , 'data': typeof data == "string" ? data : JSON.stringify(data || {})
      ,beforeSend: function(jqXHR) {
        jqXHR.setRequestHeader("X-MicrosoftAjax","Delta=true");
      }
      , 'complete': function(jqXHR, textStatus) {
        handleResponse(jqXHR, textStatus, onSuccess, onError, function(){
          setTimeout(function(){
            $.msajax(url, data, onSuccess, onError);
          }, 100 * tries); //try again
        });
      }
    });
  }

  $.msajax.defaultErrorMessage = "Error retreiving data.";


  function logError(err, errorHandler, jqXHR) {
    tries = 0; //reset counter - handling error response

    //normalize error message
    if (typeof err == "string") err = { 'Message': err };

    if (console && console.debug && console.dir) {
      console.debug("ERROR processing jQuery.msajax request.");
      console.dir({ 'details': { 'error': err, 'jqXHR':jqXHR } });
    }

    try {
      errorHandler(err, jqXHR);
    } catch (e) {}
    return;
  }


  function handleResponse(jqXHR, textStatus, onSuccess, onError, onRetry) {
    var ret = null;
    var reterr = null;
    try {
      //error from jqXHR
      if (textStatus == "error") {
        var errmsg = $.msajax.defaultErrorMessage || "Error retreiving data.";

        //check for error response from the server
        if (jqXHR.status >= 300 && jqXHR.status < 600) {
          return logError( jqXHR.statusText || msg, onError, jqXHR);
        }

        if (tries++ < 5) return onRetry();

        return logError( msg, onError, jqXHR);
      }

      //not an error response, reset try counter
      tries = 0;

      //check for a redirect from server (usually authentication token expiration).
      if (jqXHR.responseText.indexOf("|pageRedirect||") > 0) {
        location.href = decodeURIComponent(jqXHR.responseText.split("|pageRedirect||")[1].split("|")[0]).split('?')[0];
        return;
      }

      //parse response using ajax enabled parser (if available)
      ret = ((JSON && JSON.parseAjax) || $.parseJSON)(jqXHR.responseText);

      //invalid response
      if (!ret) throw jqXHR.responseText;  

      // d property wrap as of .Net 3.5
      if (ret.d) ret = ret.d;

      //has an error
      reterr = (ret && (ret.error || ret.Error)) || null; //specifically returned an "error"

      if (ret && ret.ExceptionType) { //Microsoft Webservice Exception Response
        reterr = ret
      }

    } catch (err) {
      reterr = {
        'Message': $.msajax.defaultErrorMessage || "Error retreiving data."
        ,'debug': err
      }
    }

    //perform final logic outside try/catch, was catching error in onSuccess/onError callbacks
    if (reterr) {
      logError(reterr, onError, jqXHR);
      return;
    }

    onSuccess(ret, jqXHR);
  }

} (jQuery));

NOTE: I also have a JSON.parseAjax method that is modified from json.org's JS file, that adds handling for the MS "/Date(...)/" dates...

The modified json2.js file isn't included, it uses the script based parser in the case of IE8, as there are instances where the native parser breaks when you extend the prototype of array and/or object, etc.

I've been considering revamping this code to implement the promises interfaces, but it's worked really well for me.

How to interpret "loss" and "accuracy" for a machine learning model

Just to clarify the Training/Validation/Test data sets: The training set is used to perform the initial training of the model, initializing the weights of the neural network.

The validation set is used after the neural network has been trained. It is used for tuning the network's hyperparameters, and comparing how changes to them affect the predictive accuracy of the model. Whereas the training set can be thought of as being used to build the neural network's gate weights, the validation set allows fine tuning of the parameters or architecture of the neural network model. It's useful as it allows repeatable comparison of these different parameters/architectures against the same data and networks weights, to observe how parameter/architecture changes affect the predictive power of the network.

Then the test set is used only to test the predictive accuracy of the trained neural network on previously unseen data, after training and parameter/architecture selection with the training and validation data sets.

How to set JFrame to appear centered, regardless of monitor resolution?

If you use NetBeans, simply click on the frame on the design view, then the code tab on its properties. Next, check 'Generate Center'. That will get the job done.

How to set TLS version on apache HttpClient

Using -Dhttps.protocols=TLSv1.2 JVM argument didn't work for me. What worked is the following code

RequestConfig.Builder requestBuilder = RequestConfig.custom();
//other configuration, for example
requestBuilder = requestBuilder.setConnectTimeout(1000);

SSLContext sslContext = SSLContextBuilder.create().useProtocol("TLSv1.2").build();

HttpClientBuilder builder = HttpClientBuilder.create();
builder.setDefaultRequestConfig(requestBuilder.build());
builder.setProxy(new HttpHost("your.proxy.com", 3333)); //if you have proxy
builder.setSSLContext(sslContext);

HttpClient client = builder.build();

Use the following JVM argument to verify

-Djavax.net.debug=all

How to scroll HTML page to given anchor?

You can use jQuerys .animate(), .offset() and scrollTop. Like

$(document.body).animate({
    'scrollTop':   $('#anchorName2').offset().top
}, 2000);

example link: http://jsbin.com/unasi3/edit

If you don't want to animate use .scrollTop() like

$(document.body).scrollTop($('#anchorName2').offset().top);

or javascripts native location.hash like

location.hash = '#' + anchorid;

Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0?

I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.

I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.

  1. Go to the "Manage NuGet Packages"
  2. Select the Installed Package "Microsoft ASP.NET Web API 2.1"
  3. Click Manage and check the projects that I manually added before.

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

You can just do that too, it seems to work well too. sc create "Servicename" binPath= "Path\To\your\App.exe" DisplayName= "My Custom Service"

You can open the registry and add a string named Description in your service's registry key to add a little more descriptive information about it. It will be shown in services.msc.

Override intranet compatibility mode IE8

Try putting the following in the header:

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

Courtesy Paul Irish's HTML5 Boilerplate (but it works in XHTML Transitional, too).

node.js - request - How to "emitter.setMaxListeners()"?

Although adding something to nodejs module is possible, it seems to be not the best way (if you try to run your code on other computer, the program will crash with the same error, obviously).

I would rather set max listeners number in your own code:

var options = {uri:headingUri, headers:headerData, maxRedirects:100};
request.setMaxListeners(0);
request.get(options, function (error, response, body) {
}

Need to perform Wildcard (*,?, etc) search on a string using Regex

All upper code is not correct to the end.

This is because when searching zz*foo* or zz* you will not get correct results.

And if you search "abcd*" in "abcd" in TotalCommander will he find a abcd file so all upper code is wrong.

Here is the correct code.

public string WildcardToRegex(string pattern)
{             
    string result= Regex.Escape(pattern).
        Replace(@"\*", ".+?").
        Replace(@"\?", "."); 

    if (result.EndsWith(".+?"))
    {
        result = result.Remove(result.Length - 3, 3);
        result += ".*";
    }

    return result;
}

iOS: How to store username/password within an app?

try this one:

 KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"YourAppLogin" accessGroup:nil];
[keychainItem setObject:@"password you are saving" forKey:kSecValueData]; 
[keychainItem setObject:@"username you are saving" forKey:kSecAttrAccount];

may it will help.

Is there 'byte' data type in C++?

Using C++11 there is a nice version for a manually defined byte type:

enum class byte : std::uint8_t {};

That's at least what the GSL does.

Starting with C++17 (almost) this very version is defined in the standard as std::byte (thanks Neil Macintosh for both).

How to run batch file from network share without "UNC path are not supported" message?

Instead of launching the batch directly from explorer - create a shortcut to the batch and set the starting directory in the properties of the shortcut to a local path like %TEMP% or something.

To delete the symbolic link, use the rmdir command.

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

I had this problem in a unit test which opened a lot of connections to the DB via a connection pool and then "stopped" the connection pool (ManagedDataSource actually) to release the connections at the end of the each test. I always ran out of connections at some point in the suite of tests.

Added a Thread.sleep(500) in the teardown() of my tests and this resolved the issue. I think that what was happening was that the connection pool stop() releases the active connections in another thread so that if the main thread keeps running tests the cleanup thread(s) got so far behind that the Oracle server ran out of connections. Adding the sleep allows the background threads to release the pooled connections.

This is much less of an issue in the real world because the DB servers are much bigger and there is a healthy mix of operations (not just endless DB connect/disconnect operations).

Test if object implements interface

A variation on @AndrewKennan's answer I ended up using recently for types obtained at runtime:

if (serviceType.IsInstanceOfType(service))
{
    // 'service' does implement the 'serviceType' type
}

Vim 80 column layout concerns

You also can draw line to see 80 limit:

let &colorcolumn=join(range(81,999),",")
let &colorcolumn="80,".join(range(400,999),",")

Result:

enter image description here

How to parse JSON without JSON.NET library?

using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace OTL
{
    /// <summary>
    /// Before usage: Define your class, sample:
    /// [DataContract]
    ///public class MusicInfo
    ///{
    ///   [DataMember(Name="music_name")]
    ///   public string Name { get; set; }
    ///   [DataMember]
    ///   public string Artist{get; set;}
    ///}
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class OTLJSON<T> where T : class
    {
        /// <summary>
        /// Serializes an object to JSON
        /// Usage: string serialized = OTLJSON&lt;MusicInfo&gt;.Serialize(musicInfo);
        /// </summary>
        /// <param name="instance"></param>
        /// <returns></returns>
        public static string Serialize(T instance)
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            using (var stream = new MemoryStream())
            {
                serializer.WriteObject(stream, instance);
                return Encoding.Default.GetString(stream.ToArray());
            }
        }

        /// <summary>
        /// DeSerializes an object from JSON
        /// Usage:  MusicInfo deserialized = OTLJSON&lt;MusicInfo&gt;.Deserialize(json);
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T Deserialize(string json)
        {
            if (string.IsNullOrEmpty(json))
                throw new Exception("Json can't empty");
            else
                try
                {
                    using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
                    {

                        var serializer = new DataContractJsonSerializer(typeof(T));
                        return serializer.ReadObject(stream) as T;
                    }
                }
                catch (Exception e)
                {
                    throw new Exception("Json can't convert to Object because it isn't correct format.");
                }
        }
    }
}

What is the email subject length limit?

I don't believe that there is a formal limit here, and I'm pretty sure there isn't any hard limit specified in the RFC either, as you found.

I think that some pretty common limitations for subject lines in general (not just e-mail) are:

  • 80 Characters
  • 128 Characters
  • 256 Characters

Obviously, you want to come up with something that is reasonable. If you're writing an e-mail client, you may want to go with something like 256 characters, and obviously test thoroughly against big commercial servers out there to make sure they serve your mail correctly.

Hope this helps!