Programs & Examples On #Stemming

The process for reducing inflected words to their stem.

How do I do word Stemming or Lemmatization?

I highly recommend using Spacy (base text parsing & tagging) and Textacy (higher level text processing built on top of Spacy).

Lemmatized words are available by default in Spacy as a token's .lemma_ attribute and text can be lemmatized while doing a lot of other text preprocessing with textacy. For example while creating a bag of terms or words or generally just before performing some processing that requires it.

I'd encourage you to check out both before writing any code, as this may save you a lot of time!

Swift - encode URL

This is working for me in Swift 5. The usage case is taking a URL from the clipboard or similar which may already have escaped characters but which also contains Unicode characters which could cause URLComponents or URL(string:) to fail.

First, create a character set that includes all URL-legal characters:

extension CharacterSet {

    /// Characters valid in at least one part of a URL.
    ///
    /// These characters are not allowed in ALL parts of a URL; each part has different requirements. This set is useful for checking for Unicode characters that need to be percent encoded before performing a validity check on individual URL components.
    static var urlAllowedCharacters: CharacterSet {
        // Start by including hash, which isn't in any set
        var characters = CharacterSet(charactersIn: "#")
        // All URL-legal characters
        characters.formUnion(.urlUserAllowed)
        characters.formUnion(.urlPasswordAllowed)
        characters.formUnion(.urlHostAllowed)
        characters.formUnion(.urlPathAllowed)
        characters.formUnion(.urlQueryAllowed)
        characters.formUnion(.urlFragmentAllowed)

        return characters
    }
}

Next, extend String with a method to encode URLs:

extension String {

    /// Converts a string to a percent-encoded URL, including Unicode characters.
    ///
    /// - Returns: An encoded URL if all steps succeed, otherwise nil.
    func encodedUrl() -> URL? {        
        // Remove preexisting encoding,
        guard let decodedString = self.removingPercentEncoding,
            // encode any Unicode characters so URLComponents doesn't choke,
            let unicodeEncodedString = decodedString.addingPercentEncoding(withAllowedCharacters: .urlAllowedCharacters),
            // break into components to use proper encoding for each part,
            let components = URLComponents(string: unicodeEncodedString),
            // and reencode, to revert decoding while encoding missed characters.
            let percentEncodedUrl = components.url else {
            // Encoding failed
            return nil
        }

        return percentEncodedUrl
    }

}

Which can be tested like:

let urlText = "https://www.example.com/??/search?q=123&foo=bar&multi=eggs+and+ham&hangul=??&spaced=lovely%20spam&illegal=<>#top"
let url = encodedUrl(from: urlText)

Value of url at the end: https://www.example.com/%ED%8F%B4%EB%8D%94/search?q=123&foo=bar&multi=eggs+and+ham&hangul=%ED%95%9C%EA%B8%80&spaced=lovely%20spam&illegal=%3C%3E#top

Note that both %20 and + spacing are preserved, Unicode characters are encoded, the %20 in the original urlText is not double encoded, and the anchor (fragment, or #) remains.

Edit: Now checking for validity of each component.

How do I run PHP code when a user clicks on a link?

There is the only better way is AJAX as everyone is suggest in their posts. The alternative is using IFrames like below:

<iframe name="f1" id="f1"> </iframe>

<a href='yourpage.php' target='f1'>Click </a>

Now you will get the output in IFrame (you can place IFrame wherever you need in the page or event hide it and the result from the script).

Hope for non Ajax solution this is better.

export html table to csv

You don't need PHP script on server side. Do that in the client side only, in browsers that accept Data URIs:

data:application/csv;charset=utf-8,content_encoded_as_url

The Data URI will be something like:

data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333

You can call this URI by:

  • using window.open
  • or setting the window.location
  • or by the href of an anchor
  • by adding the download attribute it will work in chrome, still have to test in IE.

To test, simply copy the URIs above and paste in your browser address bar. Or test the anchor below in a HTML page:

<a download="somedata.csv" href="data:application/csv;charset=utf-8,Col1%2CCol2%2CCol3%0AVal1%2CVal2%2CVal3%0AVal11%2CVal22%2CVal33%0AVal111%2CVal222%2CVal333">Example</a>

To create the content, getting the values from the table, you can use table2CSV mentioned by MelanciaUK and do:

var csv = $table.table2CSV({delivery:'value'});
window.location.href = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(csv);

How to convert AAR to JAR

 The 'aar' bundle is the binary distribution of an Android Library Project. .aar file 
 consists a JAR file and some resource files. You can convert it
 as .jar file using this steps

1) Copy the .aar file in a separate folder and Rename the .aar file to .zip file using 
 any winrar or zip Extractor software.

2) Now you will get a .zip file. Right click on the .zip file and select "Extract files". 
 Will get a folder which contains "classes.jar, resource, manifest, R.java,
 proguard(optional), libs(optional), assets(optional)".

3) Rename the classes.jar file as yourjarfilename.jar and use this in your project.

Note: If you want to get only .jar file from your .aar file use the above way. Suppose If you want to include the manifest.xml and resources with your .jar file means you can just right click on your .aar file and save it as .jar file directly instead of saving it as a .zip. To view the .jar file which you have extracted, download JD-GUI(Java Decompiler). Then drag and drop your .jar file into this JD_GUI, you can see the .class file in readable formats like a .java file.

enter image description here enter image description here

Print all but the first three columns

Perl solution which does not add leading or trailing whitespace:

perl -lane 'splice @F,0,3; print join " ",@F' file

The perl @F autosplit array starts at index 0 while awk fields start with $1


Perl solution for comma-delimited data:

perl -F, -lane 'splice @F,0,3; print join ",",@F' file

Python solution:

python -c "import sys;[sys.stdout.write(' '.join(line.split()[3:]) + '\n') for line in sys.stdin]" < file

What is pipe() function in Angular

RxJS Operators are functions that build on the observables foundation to enable sophisticated manipulation of collections.

For example, RxJS defines operators such as map(), filter(), concat(), and flatMap().

You can use pipes to link operators together. Pipes let you combine multiple functions into a single function.

The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.

What is a void pointer in C++?

A void* pointer is used when you want to indicate a pointer to a hunk of memory without specifying the type. C's malloc returns such a pointer, expecting you to cast it to a particular type immediately. It really isn't useful until you cast it to another pointer type. You're expected to know which type to cast it to, the compiler has no reflection capability to know what the underlying type should be.

Count number of rows within each group

Following @Joshua's suggestion, here's one way you might count the number of observations in your df dataframe where Year = 2007 and Month = Nov (assuming they are columns):

nrow(df[,df$YEAR == 2007 & df$Month == "Nov"])

and with aggregate, following @GregSnow:

aggregate(x ~ Year + Month, data = df, FUN = length)

How to retrieve inserted id after inserting row in SQLite using Python?

All credits to @Martijn Pieters in the comments:

You can use the function last_insert_rowid():

The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.

How to read string from keyboard using C?

You have no storage allocated for word - it's just a dangling pointer.

Change:

char * word;

to:

char word[256];

Note that 256 is an arbitrary choice here - the size of this buffer needs to be greater than the largest possible string that you might encounter.

Note also that fgets is a better (safer) option then scanf for reading arbitrary length strings, in that it takes a size argument, which in turn helps to prevent buffer overflows:

 fgets(word, sizeof(word), stdin);

filename and line number of Python script

Handy if used in a common file - prints file name, line number and function of the caller:

import inspect
def getLineInfo():
    print(inspect.stack()[1][1],":",inspect.stack()[1][2],":",
          inspect.stack()[1][3])

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

i had the same problem unable to execute multipledex files in android --lorg\xhtml\CSS

i deleted 2external jars files in lib folder--core-renderer-3043e0f89ffb2.jar

core-renderer-minimal-e70d6a.jar and my project built fine again...

How do I make a batch file terminate upon encountering an error?

Add || goto :label to each line, and then define a :label.

For example, create this .cmd file:

@echo off

echo Starting very complicated batch file...
ping -invalid-arg || goto :error
echo OH noes, this shouldn't have succeeded.
goto :EOF

:error
echo Failed with error #%errorlevel%.
exit /b %errorlevel%

See also question about exiting batch file subroutine.

Java Spring - How to use classpath to specify a file location?

Spring has org.springframework.core.io.Resource which is designed for such situations. From context.xml you can pass classpath to the bean

<bean class="test.Test1">
        <property name="path" value="classpath:/test/test1.xml" />
    </bean>

and you get it in your bean as Resource:

public void setPath(Resource path) throws IOException {
    File file = path.getFile();
    System.out.println(file);
    }

output

D:\workspace1\spring\target\test-classes\test\test1.xml

Now you can use it in new FileReader(file)

Responsive Images with CSS

the best way i found was to set the image you want to view responsively as a background image and sent a css property for the div as cover.

background-image : url('YOUR URL');
background-size : cover

Render HTML string as real HTML in a React component

In my case, I used react-render-html

First install the package by npm i --save react-render-html

then,

import renderHTML from 'react-render-html';

renderHTML("<a class='github' href='https://github.com'><b>GitHub</b></a>")

Pausing a batch file for amount of time

ping -n 11 -w 1000 127.0.0.1 > nul

Update

Beginner's mistake. Ping doesn't wait 1000 ms before or after an request, but inbetween requests. So to wait 10 seconds, you'll have to do 11 pings to have 10 'gaps' of a second inbetween.

Using VBA to get extended file attributes

You can get this with .BuiltInDocmementProperties.

For example:

Public Sub PrintDocumentProperties()
    Dim oApp As New Excel.Application
    Dim oWB As Workbook
    Set oWB = ActiveWorkbook

    Dim title As String
    title = oWB.BuiltinDocumentProperties("Title")

    Dim lastauthor As String
    lastauthor = oWB.BuiltinDocumentProperties("Last Author")

    Debug.Print title
    Debug.Print lastauthor
End Sub

See this page for all the fields you can access with this: http://msdn.microsoft.com/en-us/library/bb220896.aspx

If you're trying to do this outside of the client (i.e. with Excel closed and running code from, say, a .NET program), you need to use DSOFile.dll.

How to set custom ActionBar color / style?

in the style.xml add this code

<resources>
    <style name="MyTheme" parent="@android:style/Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/MyAction</item>
    </style>

    <style name="MyActionBarTheme" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">#333333</item>
    </style>
</resources>

exit application when click button - iOS

exit(X), where X is a number (according to the doc) should work. But it is not recommended by Apple and won't be accepted by the AppStore. Why? Because of these guidelines (one of my app got rejected):

We found that your app includes a UI control for quitting the app. This is not in compliance with the iOS Human Interface Guidelines, as required by the App Store Review Guidelines.

Please refer to the attached screenshot/s for reference.

The iOS Human Interface Guidelines specify,

"Always Be Prepared to Stop iOS applications stop when people press the Home button to open a different application or use a device feature, such as the phone. In particular, people don’t tap an application close button or select Quit from a menu. To provide a good stopping experience, an iOS application should:

Save user data as soon as possible and as often as reasonable because an exit or terminate notification can arrive at any time.

Save the current state when stopping, at the finest level of detail possible so that people don’t lose their context when they start the application again. For example, if your app displays scrolling data, save the current scroll position."

> It would be appropriate to remove any mechanisms for quitting your app.

Plus, if you try to hide that function, it would be understood by the user as a crash.

How can I specify a [DllImport] path at runtime?

set the dll path in the config file

<add key="dllPath" value="C:\Users\UserName\YourApp\myLibFolder\myDLL.dll" />

before calling the dll in you app, do the following

string dllPath= ConfigurationManager.AppSettings["dllPath"];    
   string appDirectory = Path.GetDirectoryName(dllPath);
   Directory.SetCurrentDirectory(appDirectory);

then call the dll and you can use like below

 [DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int DLLFunction(int Number1, int Number2);

Div Background Image Z-Index Issue

For z-index to work, you also need to give it a position:

header {
    width: 100%;
    height: 100px;
    background: url(../img/top.png) repeat-x;
    z-index: 110;
    position: relative;
}

How do I use this JavaScript variable in HTML?

You can create an element with an id and then assign that length value to that element.

_x000D_
_x000D_
var name = prompt("What's your name?");_x000D_
var lengthOfName = name.length_x000D_
document.getElementById('message').innerHTML = lengthOfName;
_x000D_
<p id='message'></p>
_x000D_
_x000D_
_x000D_

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

Or use a cast with split to uniform type of str

unique, counts = numpy.unique(str(a).split(), return_counts=True)

How do you open a file in C++?

You need to use an ifstream if you just want to read (use an ofstream to write, or an fstream for both).

To open a file in text mode, do the following:

ifstream in("filename.ext", ios_base::in); // the in flag is optional

To open a file in binary mode, you just need to add the "binary" flag.

ifstream in2("filename2.ext", ios_base::in | ios_base::binary ); 

Use the ifstream.read() function to read a block of characters (in binary or text mode). Use the getline() function (it's global) to read an entire line.

Detecting when user scrolls to bottom of div with jQuery

If you are not using Math.round() function the solution suggested by Dr.Molle will not work in some cases when a browser window has a zoom.

For example $(this).scrollTop() + $(this).innerHeight() = 600

$(this)[0].scrollHeight yields = 599.99998

600 >= 599.99998 fails.

Here is the correct code:

jQuery(function($) {
    $('#flux').on('scroll', function() {
        if(Math.round($(this).scrollTop() + $(this).innerHeight(), 10) >= Math.round($(this)[0].scrollHeight, 10)) {
            alert('end reached');
        }
    })
});

You may also add some extra margin pixels if you do not need a strict condition

var margin = 4

jQuery(function($) {
    $('#flux').on('scroll', function() {
        if(Math.round($(this).scrollTop() + $(this).innerHeight(), 10) >= Math.round($(this)[0].scrollHeight, 10) - margin) {
            alert('end reached');
        }
    })
});

Media Queries: How to target desktop, tablet, and mobile?

This is only for those who haven't done 'mobile-first' design to their websites yet and looking for a quick temporary solution.

For Mobile Phones

@media (max-width:480px){}

For Tablets

@media (max-width:960px){}

For Laptops/Desktop

@media (min-width:1025px){}

For Hi-Res Laptops

@media (max-width:1280px){}

.htaccess file to allow access to images folder to view pictures?

Create a .htaccess file in the images folder and add this

<IfModule mod_rewrite.c>
RewriteEngine On
# directory browsing
Options All +Indexes
</IfModule>

you can put this Options All -Indexes in the project file .htaccess ,file to deny direct access to other folders.

This does what you want

How can I get a channel ID from YouTube?

Channel id with the current youtube version is obtained very easily if you login to YouYube website and select 'My channel'

My channel

Your channel ID will be displayed on the address bar of your browser channel id

CSS to hide INPUT BUTTON value text

This following has worked best for me:

HTML:

<input type="submit"/>

CSS:

input[type=submit] {
    background: url(http://yourURLhere) no-repeat;
    border: 0;
    display: block;
    font-size:0;
    height: 38px;
    width: 171px;
}

If you don't set value on your <input type="submit"/> it will place the default text "Submit" inside your button. SO, just set the font-size: 0; on your submit and then make sure you set a height and width for your input type so that your image will display. DON'T forget media queries for your submit if you need them, for example:

CSS:

@media (min-width:600px) {
  input[type=submit] {
    width:200px;
    height: 44px;
  }
}

This means when the screen is at exactly 600px wide or greater the button will change it's dimensions

Is it better to use "is" or "==" for number comparison in Python?

== is what you want, "is" just happens to work on your examples.

Include files from parent or other directory

In laymans terms, and practicality, I see this as an old DOS trick/thing. Whoa! What was that? DOS? Never heard of it!

".." backs you out of the current sub-directory one time to a higher folder/directory, and .. enter typed twice backs you out too 2 higher parent folders. Keep adding the ".. enter" back to back and you will soon find yourself at the top level of the directory.

As for Newbies to understand this better, consider this (in terms of the home PC or "C:\ drive" if you know what that means, rather than the web-servers/host "root directory" ). While your at it, Consider your website existing somewhere on your home PC's hard drive, buried in some folder under the C:\ drive. Lastly, you can think of it as ".." is back one directory and "/" is forward one directory/folder.

Now! If you are using the command prompt and are within the "myDocuments" folder of your PC you must back out of that folder to get closer to the higher directory "C:\" by typing the "../". If you wanted to access a file that is located in the widows directory while you are still in the myDocuments folder you would theoretically type ../windows; in reality of DOS command prompt you would simply type .., but I am setting you up for the web. The / redirects forward to another directory naturally.

Using "myDocuments" lets pretend that you created 2 folders within it called "PHP1" and "PHP2", in such we now have the folders:

  • C:\myDocuments\PHP1
  • C:\myDocuments\PHP2

In PHP1 you place a file called index.php. and in PHP2 folder you placed a file called Found.php. it now becomes:

  • C:\myDocuments\PHP1\index.php
  • C:\myDocuments\PHP2\found.php

Inside the C:\myDocuments\PHP1\index.php file you would need to edit and type something like:

<?php include ('../php2/found.php')?>

The ../ is positional thus it considers your current file location "C:\myDocuments\PHP1\index.php" and is a directive telling it to back out of PHP1 directory and enter or move forward into PHP2 directory to look for the Found.php file. But does it read it? See my thoughts on trouble shooting below.

Now! suppose you have 1 folder PHP1 and a sub-folder PHP2:

  • C:\myDocuments\PHP1\PHP2

you would simply reference/code

<?php include('/PHP2/found.php') ?>

as PHP2 exist as a sub-directory, below or within PHP1 directory.

If the above does not work it may have something to do with access/htaccess or permission to the directory or a typo. To enhance this...getting into trouble shooting...If the "found.php" file has errors/typo's within it, it will crash upon rendering at the error, such could be the reason (require/require_once) that you are experiencing the illusion that it is not changing directories or accessing the file. At last thought on the matter, you may need to instantiate your functions or references in order to use the included/require "whatever" by creating a new variable or object such as

$newObject = new nameobject("origianlThingy");

Remember, just because you are including/requiring something, sometimes means just that, it is included/required to run, but it might need to be recreated to make it active or access it. New will surely re-create an instance of it "if it is readable" and make it available within the current document while preserving the original. However you should reference the newly created variable $newObject in all instances....if its global.

To put this in perspective of some web host account; the web host is some whopping over sized hard-drive (like that on your PC) and your domain is nothing more than a folder they have assigned to you. Your folder is called the root. Inside that folder you can do anything you are allowed to do. your "one of many ways" to move between directories/folders is to use the ../ however many times to back out of your current in reference to folder position you want to find.

In my drunken state I realize that I know too much to be sane, and not enough to be insane!"

Clear dropdownlist with JQuery

Just use .empty():

// snip...
}).done(function (data) {
    // Clear drop down list
    $(dropdown).empty(); // <<<<<< No more issue here
    // Fill drop down list with new data
    $(data).each(function () {
        // snip...

There's also a more concise way to build up the options:

// snip...
$(data).each(function () {
    $("<option />", {
        val: this.value,
        text: this.text
    }).appendTo(dropdown);
});

What does EntityManager.flush do and why do I need to use it?

The EntityManager.flush() operation can be used the write all changes to the database before the transaction is committed. By default JPA does not normally write changes to the database until the transaction is committed. This is normally desirable as it avoids database access, resources and locks until required. It also allows database writes to be ordered, and batched for optimal database access, and to maintain integrity constraints and avoid deadlocks. This means that when you call persist, merge, or remove the database DML INSERT, UPDATE, DELETE is not executed, until commit, or until a flush is triggered.

Escape quotes in JavaScript

You can use the escape() and unescape() jQuery methods. Like below,

Use escape(str); to escape the string and recover again using unescape(str_esc);.

How do I remove duplicate items from an array in Perl?

Method 1: Use a hash

Logic: A hash can have only unique keys, so iterate over array, assign any value to each element of array, keeping element as key of that hash. Return keys of the hash, its your unique array.

my @unique = keys {map {$_ => 1} @array};

Method 2: Extension of method 1 for reusability

Better to make a subroutine if we are supposed to use this functionality multiple times in our code.

sub get_unique {
    my %seen;
    grep !$seen{$_}++, @_;
}
my @unique = get_unique(@array);

Method 3: Use module List::MoreUtils

use List::MoreUtils qw(uniq);
my @unique = uniq(@array);

python NameError: global name '__file__' is not defined

This error comes when you append this line os.path.join(os.path.dirname(__file__)) in python interactive shell.

Python Shell doesn't detect current file path in __file__ and it's related to your filepath in which you added this line

So you should write this line os.path.join(os.path.dirname(__file__)) in file.py. and then run python file.py, It works because it takes your filepath.

String contains another two strings

So what is that you are really after? If you want to make sure that something has hit for damage (in this case), why are you not using string.Format

string a = string.Format("You hit someone for {d} damage", damage);

In this way, you have the ability to have the damage qualifier that you are looking for, and are able to calculate that for other parts.

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

It depends on the encoding of your string (ASCII, UTF-8, ...).

For example:

byte[] b1 = System.Text.Encoding.UTF8.GetBytes (myString);
byte[] b2 = System.Text.Encoding.ASCII.GetBytes (myString);

A small sample why encoding matters:

string pi = "\u03a0";
byte[] ascii = System.Text.Encoding.ASCII.GetBytes (pi);
byte[] utf8 = System.Text.Encoding.UTF8.GetBytes (pi);

Console.WriteLine (ascii.Length); //Will print 1
Console.WriteLine (utf8.Length); //Will print 2
Console.WriteLine (System.Text.Encoding.ASCII.GetString (ascii)); //Will print '?'

ASCII simply isn't equipped to deal with special characters.

Internally, the .NET framework uses UTF-16 to represent strings, so if you simply want to get the exact bytes that .NET uses, use System.Text.Encoding.Unicode.GetBytes (...).

See Character Encoding in the .NET Framework (MSDN) for more information.

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

Mailbox unavailable. The server response was: 5.7.1 Unable to relay for [email protected]

As a picture is worth a thousand words..

When you find the IIS6 manager (I have found that searching for IIS may return 2 results) go to the SMTP server properties then 'Access' then press the relay button.

Then you can either select all or only allow certain ip's like 127.0.0.1

SMTP Relay

Python Math - TypeError: 'NoneType' object is not subscriptable

lista = list.sort(lista)

This should be

lista.sort()

The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don't call your lists list. That clobbers the builtin list type.

Aside #2: I'm not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don't know why you're calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..


The exception TypeError: 'NoneType' object is not subscriptable happens because the value of lista is actually None. You can reproduce TypeError that you get in your code if you try this at the Python command line:

None[0]

The reason that lista gets set to None is because the return value of list.sort() is None... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).

If you do not want to alter the original version you can use

other_list = sorted(lista)

Rounding a double value to x number of decimal places in swift

With Swift 5, according to your needs, you can choose one of the 9 following styles in order to have a rounded result from a Double.


#1. Using FloatingPoint rounded() method

In the simplest case, you may use the Double rounded() method.

let roundedValue1 = (0.6844 * 1000).rounded() / 1000
let roundedValue2 = (0.6849 * 1000).rounded() / 1000
print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685

#2. Using FloatingPoint rounded(_:) method

let roundedValue1 = (0.6844 * 1000).rounded(.toNearestOrEven) / 1000
let roundedValue2 = (0.6849 * 1000).rounded(.toNearestOrEven) / 1000
print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685

#3. Using Darwin round function

Foundation offers a round function via Darwin.

import Foundation

let roundedValue1 = round(0.6844 * 1000) / 1000
let roundedValue2 = round(0.6849 * 1000) / 1000
print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685

#4. Using a Double extension custom method built with Darwin round and pow functions

If you want to repeat the previous operation many times, refactoring your code can be a good idea.

import Foundation

extension Double {
    func roundToDecimal(_ fractionDigits: Int) -> Double {
        let multiplier = pow(10, Double(fractionDigits))
        return Darwin.round(self * multiplier) / multiplier
    }
}

let roundedValue1 = 0.6844.roundToDecimal(3)
let roundedValue2 = 0.6849.roundToDecimal(3)
print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685

#5. Using NSDecimalNumber rounding(accordingToBehavior:) method

If needed, NSDecimalNumber offers a verbose but powerful solution for rounding decimal numbers.

import Foundation

let scale: Int16 = 3

let behavior = NSDecimalNumberHandler(roundingMode: .plain, scale: scale, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true)

let roundedValue1 = NSDecimalNumber(value: 0.6844).rounding(accordingToBehavior: behavior)
let roundedValue2 = NSDecimalNumber(value: 0.6849).rounding(accordingToBehavior: behavior)

print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685

#6. Using NSDecimalRound(_:_:_:_:) function

import Foundation

let scale = 3

var value1 = Decimal(0.6844)
var value2 = Decimal(0.6849)

var roundedValue1 = Decimal()
var roundedValue2 = Decimal()

NSDecimalRound(&roundedValue1, &value1, scale, NSDecimalNumber.RoundingMode.plain)
NSDecimalRound(&roundedValue2, &value2, scale, NSDecimalNumber.RoundingMode.plain)

print(roundedValue1) // returns 0.684
print(roundedValue2) // returns 0.685

#7. Using NSString init(format:arguments:) initializer

If you want to return a NSString from your rounding operation, using NSString initializer is a simple but efficient solution.

import Foundation

let roundedValue1 = NSString(format: "%.3f", 0.6844)
let roundedValue2 = NSString(format: "%.3f", 0.6849)
print(roundedValue1) // prints 0.684
print(roundedValue2) // prints 0.685

#8. Using String init(format:_:) initializer

Swift’s String type is bridged with Foundation’s NSString class. Therefore, you can use the following code in order to return a String from your rounding operation:

import Foundation

let roundedValue1 = String(format: "%.3f", 0.6844)
let roundedValue2 = String(format: "%.3f", 0.6849)
print(roundedValue1) // prints 0.684
print(roundedValue2) // prints 0.685

#9. Using NumberFormatter

If you expect to get a String? from your rounding operation, NumberFormatter offers a highly customizable solution.

import Foundation

let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.decimal
formatter.roundingMode = NumberFormatter.RoundingMode.halfUp
formatter.maximumFractionDigits = 3

let roundedValue1 = formatter.string(from: 0.6844)
let roundedValue2 = formatter.string(from: 0.6849)
print(String(describing: roundedValue1)) // prints Optional("0.684")
print(String(describing: roundedValue2)) // prints Optional("0.685")

Fitting polynomial model to data in R

To get a third order polynomial in x (x^3), you can do

lm(y ~ x + I(x^2) + I(x^3))

or

lm(y ~ poly(x, 3, raw=TRUE))

You could fit a 10th order polynomial and get a near-perfect fit, but should you?

EDIT: poly(x, 3) is probably a better choice (see @hadley below).

C# 4.0 optional out/ref arguments

There actually is a way to do this that is allowed by C#. This gets back to C++, and rather violates the nice Object-Oriented structure of C#.

USE THIS METHOD WITH CAUTION!

Here's the way you declare and write your function with an optional parameter:

unsafe public void OptionalOutParameter(int* pOutParam = null)
{
    int lInteger = 5;
    // If the parameter is NULL, the caller doesn't care about this value.
    if (pOutParam != null) 
    { 
        // If it isn't null, the caller has provided the address of an integer.
        *pOutParam = lInteger; // Dereference the pointer and assign the return value.
    }
}

Then call the function like this:

unsafe { OptionalOutParameter(); } // does nothing
int MyInteger = 0;
unsafe { OptionalOutParameter(&MyInteger); } // pass in the address of MyInteger.

In order to get this to compile, you will need to enable unsafe code in the project options. This is a really hacky solution that usually shouldn't be used, but if you for some strange, arcane, mysterious, management-inspired decision, REALLY need an optional out parameter in C#, then this will allow you to do just that.

Inline list initialization in VB.NET

Collection initializers are only available in VB.NET 2010, released 2010-04-12:

Dim theVar = New List(Of String) From { "one", "two", "three" }

java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty on Linux, or why is the default truststore empty

Not the answer to the original question but when trying to resolve a similar issue, I found that the Mac OS X update to Maverics screwed up the java install (the cacert actually). Remove sudo rm -rf /Library/Java/JavaVirtualMachines/*.jdk and reinstall from http://www.oracle.com/technetwork/java/javase/downloads/index.html

Node.js: Python not found exception due to node-sass and node-gyp

node-gyp requires old Python 2 - link

If you don't have it installed - check other answers about installing windows-build-tools.

If you are like me and have both old and new Python versions installed, chances are that node-gyp tries to use Python 3. And that results in the following SyntaxError: invalid syntax error.

I found an article about having two Python versions installed. And they recommend renaming Python 2.* executable to python2.exe - link.

So it looks like node-gyp is expecting to find old Python 2 executable renamed. Hence the error message:

...
gyp verb check python checking for Python executable "python2" in the PATH
gyp verb `which` failed Error: not found: python2
...

Once I renamed C:\Python27\python.exe to C:\Python27\python2.exe it worked without errors.

Of course, both C:\Python27\ and C:\Python39\ have to be in PATH variable. And no need in setting old Python version in npm config. Your default Python still will be the new one.

Regex to check whether a string contains only numbers

var pattern = /[0-9!"£$%^&*()_+-=]/;

This tries to avoid some scenarios, just in case:

Overflowing any buffers the original string might get passed to. Slowness or oddities caused by denormal numbers like 1E-323. Passing Infinity when a finite number is expected (try 1E309 or -1E309).

var.replace is not a function

Replace wouldn't replace numbers. It replaces strings only.

This should work.

function trim(str) {
    return str.toString().replace(/^\s+|\s+$/g,'');
}

If you only want to trim the string. You can simply use "str.trim()"

How do I turn off the mysql password validation?

Further to the answer from ktbos:

I modified the mysqld.cnf file and mysql failed to start. It turned out that I was modifying the wrong file!

So be sure the file you modify contains segment tags like [mysqld_safe] and [mysqld]. Under the latter I did as suggested and added the line:

validate_password_policy=LOW

This worked perfectly to resolve my issue of not requiring special characters within the password.

Get first day of week in SQL Server

Set DateFirst 1;

Select 
    Datepart(wk, TimeByDay) [Week]
    ,Dateadd(d,
                CASE 
                WHEN  Datepart(dw, TimeByDay) = 1 then 0
                WHEN  Datepart(dw, TimeByDay) = 2 then -1
                WHEN  Datepart(dw, TimeByDay) = 3 then -2
                WHEN  Datepart(dw, TimeByDay) = 4 then -3
                WHEN  Datepart(dw, TimeByDay) = 5 then -4
                WHEN  Datepart(dw, TimeByDay) = 6 then -5
                WHEN  Datepart(dw, TimeByDay) = 7 then -6
                END
                , TimeByDay) as StartOfWeek

from TimeByDay_Tbl

This is my logic. Set the first of the week to be Monday then calculate what is the day of the week a give day is, then using DateAdd and Case I calculate what the date would have been on the previous Monday of that week.

How to add a set path only for that batch file executing?

Just like any other environment variable, with SET:

SET PATH=%PATH%;c:\whatever\else

If you want to have a little safety check built in first, check to see if the new path exists first:

IF EXIST c:\whatever\else SET PATH=%PATH%;c:\whatever\else

If you want that to be local to that batch file, use setlocal:

setlocal
set PATH=...
set OTHERTHING=...

@REM Rest of your script

Read the docs carefully for setlocal/endlocal , and have a look at the other references on that site - Functions is pretty interesting too and the syntax is tricky.

The Syntax page should get you started with the basics.

How to build a Debian/Ubuntu package from source?

How can I check if I have listed all the dependencies correctly?

The pbuilder is an excellent tool for checking both build dependencies and dependencies by setting up a clean base system within a chroot environment. By compiling the package within pbuilder, you can easily check the build dependencies, and by testing it within a pbuilder environment, you can check the dependencies.

What is the IntelliJ shortcut key to create a javadoc comment?

Typing /** + then pressing Enter above a method signature will create Javadoc stubs for you.

Why are #ifndef and #define used in C++ header files?

They are called ifdef or include guards.

If writing a small program it might seems that it is not needed, but as the project grows you could intentionally or unintentionally include one file many times, which can result in compilation warning like variable already declared.

#ifndef checks whether HEADERFILE_H is not declared.
#define will declare HEADERFILE_H once #ifndef generates true.
#endif is to know the scope of #ifndef i.e end of #ifndef

If it is not declared which means #ifndef generates true then only the part between #ifndef and #endif executed otherwise not. This will prevent from again declaring the identifiers, enums, structure, etc...

CodeIgniter: How to get Controller, Action, URL information

If you using $this->uri->segment , if urls rewriting rules change, segments name matching will be lost.

C# Listbox Item Double Click Event

WinForms

Add an event handler for the Control.DoubleClick event for your ListBox, and in that event handler open up a MessageBox displaying the selected item.

E.g.:

 private void ListBox1_DoubleClick(object sender, EventArgs e)
 {
     if (ListBox1.SelectedItem != null)
     {
         MessageBox.Show(ListBox1.SelectedItem.ToString());
     }
 }

Where ListBox1 is the name of your ListBox.

Note that you would assign the event handler like this:

ListBox1.DoubleClick += new EventHandler(ListBox1_DoubleClick);

WPF
Pretty much the same as above, but you'd use the MouseDoubleClick event instead:

ListBox1.MouseDoubleClick += new RoutedEventHandler(ListBox1_MouseDoubleClick);

And the event handler:

 private void ListBox1_MouseDoubleClick(object sender, RoutedEventArgs e)
 {
     if (ListBox1.SelectedItem != null)
     {
         MessageBox.Show(ListBox1.SelectedItem.ToString());
     }
 }

Edit: Sisya's answer checks to see if the double-click occurred over an item, which would need to be incorporated into this code to fix the issue mentioned in the comments (MessageBox shown if ListBox is double-clicked while an item is selected, but not clicked over an item).

Hope this helps!

Razor View throwing "The name 'model' does not exist in the current context"

In my case, I recently updated from MVC 4 to MVC 5, which screws up the web.config pretty badly. This article helped tremendously.

http://www.asp.net/mvc/overview/releases/how-to-upgrade-an-aspnet-mvc-4-and-web-api-project-to-aspnet-mvc-5-and-web-api-2

The bottom line is that you need to check all your version number references in your web.config and Views/web.config to make sure that they are referencing the correct upgraded versions associated with MVC 5.

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

Here is a working example.

Keypoints are:

  • Declaration of Accounts
  • Use of JsonProperty attribute

.

using (WebClient wc = new WebClient())
{
    var json = wc.DownloadString("http://coderwall.com/mdeiters.json");
    var user = JsonConvert.DeserializeObject<User>(json);
}

-

public class User
{
    /// <summary>
    /// A User's username. eg: "sergiotapia, mrkibbles, matumbo"
    /// </summary>
    [JsonProperty("username")]
    public string Username { get; set; }

    /// <summary>
    /// A User's name. eg: "Sergio Tapia, John Cosack, Lucy McMillan"
    /// </summary>
    [JsonProperty("name")]
    public string Name { get; set; }

    /// <summary>
    /// A User's location. eh: "Bolivia, USA, France, Italy"
    /// </summary>
    [JsonProperty("location")]
    public string Location { get; set; }

    [JsonProperty("endorsements")]
    public int Endorsements { get; set; } //Todo.

    [JsonProperty("team")]
    public string Team { get; set; } //Todo.

    /// <summary>
    /// A collection of the User's linked accounts.
    /// </summary>
    [JsonProperty("accounts")]
    public Account Accounts { get; set; }

    /// <summary>
    /// A collection of the User's awarded badges.
    /// </summary>
    [JsonProperty("badges")]
    public List<Badge> Badges { get; set; }
}

public class Account
{
    public string github;
}

public class Badge
{
    [JsonProperty("name")]
    public string Name;
    [JsonProperty("description")]
    public string Description;
    [JsonProperty("created")]
    public string Created;
    [JsonProperty("badge")]
    public string BadgeUrl;
}

Error: Local workspace file ('angular.json') could not be found

I was having this error message inside a docker container. I resolved it adding:

WORKDIR /usr/src

to Dockerfile.

javascript push multidimensional array

Use []:

cookie_value_add.push([productID,itemColorTitle, itemColorPath]);

or

arrayToPush.push([value1, value2, ..., valueN]);

How to change target build on Android project?

I had this problem too. What worked for me was to first un-check the previously selected SDK version before checking the new desired version. Then click okay.

Java HTML Parsing

Let's not forget Jerry, its jQuery in java: a fast and concise Java Library that simplifies HTML document parsing, traversing and manipulating; includes usage of css3 selectors.

Example:

Jerry doc = jerry(html);
doc.$("div#jodd p.neat").css("color", "red").addClass("ohmy");

Example:

doc.form("#myform", new JerryFormHandler() {
    public void onForm(Jerry form, Map<String, String[]> parameters) {
        // process form and parameters
    }
});

Of course, these are just some quick examples to get the feeling how it all looks like.

Swift - How to detect orientation changes

Another way to detect device orientations is with the function traitCollectionDidChange(_:). The system calls this method when the iOS interface environment changes.

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?)
{
    super.traitCollectionDidChange(previousTraitCollection)
    //...
}

Furthermore, you can use function willTransition(to:with:) ( which is called before traitCollectionDidChange(_:) ), to get information just before the orientation is applied.

 override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator)
{
    super.willTransition(to: newCollection, with: coordinator)
    //...
}

How to remove decimal part from a number in C#

Use Decimal.Truncate

It removes the fractional part from the decimal.

int i = (int)Decimal.Truncate(12.66m)

IntelliJ - Convert a Java project/module into a Maven project/module

The easiest way is to add the project as a Maven project directly. To do this, in the project explorer on the left, right-click on the POM file for the project, towards the bottom of the context menu, you will see an option called 'Add as Maven Project', click it. This will automatically convert the project to a Maven project

Why can't I push to this bare repository?

This related question's answer provided the solution for me... it was just a dumb mistake:

Remember to commit first!

https://stackoverflow.com/a/7572252

If you have not yet committed to your local repo, there is nothing to push, but the Git error message you get back doesn't help you too much.

Facebook share link without JavaScript

You could use

<a href="https://www.facebook.com/sharer/sharer.php?u=#url" target="_blank">Share</a>

Currently there is no sharing option without passing current url as a parameter. You can use an indirect way to achieve this.

  1. Create a server side page for example: "/sharer.aspx"
  2. Link this page whenever you want the share functionality.
  3. In the "sharer.aspx" get the refering url, and redirect user to "https://www.facebook.com/sharer/sharer.php?u={referer}"

Example ASP .Net code:

public partial class Sharer : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var referer = Request.UrlReferrer.ToString();

        if(string.IsNullOrEmpty(referer))
        {
            // some error logic
            return;
        }

        Response.Clear();
        Response.Redirect("https://www.facebook.com/sharer/sharer.php?u=" + HttpUtility.UrlEncode(referer));
        Response.End();
    }
}

How to make a <ul> display in a horizontal row

As @alex said, you could float it right, but if you wanted to keep the markup the same, float it to the left!

#ul_top_hypers li {
    float: left;
}

How to add an action to a UIAlertView button using Swift iOS

func showAlertAction(title: String, message: String){
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: {(action:UIAlertAction!) in
        print("Action")
    }))
    alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: nil))
    self.present(alert, animated: true, completion: nil)
}

Center Align on a Absolutely Positioned Div

Or you can use relative units, e.g.

#thing {
    position: absolute;
    width: 50vw;
    right: 25vw;
}

What's the difference between equal?, eql?, ===, and ==?

I'm going to heavily quote the Object documentation here, because I think it has some great explanations. I encourage you to read it, and also the documentation for these methods as they're overridden in other classes, like String.

Side note: if you want to try these out for yourself on different objects, use something like this:

class Object
  def all_equals(o)
    ops = [:==, :===, :eql?, :equal?]
    Hash[ops.map(&:to_s).zip(ops.map {|s| send(s, o) })]
  end
end

"a".all_equals "a" # => {"=="=>true, "==="=>true, "eql?"=>true, "equal?"=>false}

== — generic "equality"

At the Object level, == returns true only if obj and other are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.

This is the most common comparison, and thus the most fundamental place where you (as the author of a class) get to decide if two objects are "equal" or not.

=== — case equality

For class Object, effectively the same as calling #==, but typically overridden by descendants to provide meaningful semantics in case statements.

This is incredibly useful. Examples of things which have interesting === implementations:

  • Range
  • Regex
  • Proc (in Ruby 1.9)

So you can do things like:

case some_object
when /a regex/
  # The regex matches
when 2..4
  # some_object is in the range 2..4
when lambda {|x| some_crazy_custom_predicate }
  # the lambda returned true
end

See my answer here for a neat example of how case+Regex can make code a lot cleaner. And of course, by providing your own === implementation, you can get custom case semantics.

eql?Hash equality

The eql? method returns true if obj and other refer to the same hash key. This is used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition by aliasing eql? to their overridden == method, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:

1 == 1.0     #=> true
1.eql? 1.0   #=> false

So you're free to override this for your own uses, or you can override == and use alias :eql? :== so the two methods behave the same way.

equal? — identity comparison

Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).

This is effectively pointer comparison.

How to pass a variable to the SelectCommand of a SqlDataSource?

See if it works if you just remove the DbType="Guid" from the markup.

Modifying CSS class property values on the fly with JavaScript / jQuery

Nice question. A lot of the answers here had a solution directly contradicting what you were asking

"I know how to use jQuery to assign width, height, etc. to an element, but what I'm trying to do is actually change the value defined in the stylesheet so that the dynamically-created value can be assigned to multiple elements.
"

jQuery .css styles elements inline: it doesn't change the physical CSS rule! If you want to do this, I would suggest using a vanilla JavaScript solution:

document.styleSheets[0].cssRules[0].cssText = "\
     #myID {
         myRule: myValue;
         myOtherRule: myOtherValue;
     }";

This way, you're setting the stylesheet css rule, not appending an inline style.

Hope this helps!

What version of JBoss I am running?

The version of JBoss should also be visible in the boot log file. Standard install would have that (for linux) in

/var/log/jboss/boot.log

$ head boot.log

08:30:07,477 INFO  [Server] Starting JBoss (MX MicroKernel)...
08:30:07,478 INFO  [Server] Release ID: JBoss [Trinity] 4.2.2.GA (build: SVNTag=JBoss_4_2_2_GA date=200710221139)
08:30:07,478 DEBUG [Server] Using config: org.jboss.system.server.ServerConfigImpl@4277158a
08:30:07,478 DEBUG [Server] Server type: class org.jboss.system.server.ServerImpl
08:30:07,478 DEBUG [Server] Server loaded through: org.jboss.system.server.NoAnnotationURLClassLoader
08:30:07,478 DEBUG [Server] Boot URLs:

so required info int the above case is

Release ID: JBoss [Trinity] 4.2.2.GA (build: SVNTag=JBoss_4_2_2_GA date=200710221139)

How to decrease prod bundle size?

Use latest angular cli version and use command ng build --prod --build-optimizer It will definitely reduce the build size for prod env.

This is what the build optimizer does under the hood:

The build optimizer has two main jobs. First, we are able to mark parts of your application as pure,this improves the tree shaking provided by the existing tools, removing additional parts of your application that aren’t needed.

The second thing the build optimizer does is to remove Angular decorators from your application’s runtime code. Decorators are used by the compiler, and aren’t needed at runtime and can be removed. Each of these jobs decrease the size of your JavaScript bundles, and increase the boot speed of your application for your users.

Note : One update for Angular 5 and up, the ng build --prod automatically take care of above process :)

Keras input explanation: input_shape, units, batch_size, dim, etc

Units:

The amount of "neurons", or "cells", or whatever the layer has inside it.

It's a property of each layer, and yes, it's related to the output shape (as we will see later). In your picture, except for the input layer, which is conceptually different from other layers, you have:

  • Hidden layer 1: 4 units (4 neurons)
  • Hidden layer 2: 4 units
  • Last layer: 1 unit

Shapes

Shapes are consequences of the model's configuration. Shapes are tuples representing how many elements an array or tensor has in each dimension.

Ex: a shape (30,4,10) means an array or tensor with 3 dimensions, containing 30 elements in the first dimension, 4 in the second and 10 in the third, totaling 30*4*10 = 1200 elements or numbers.

The input shape

What flows between layers are tensors. Tensors can be seen as matrices, with shapes.

In Keras, the input layer itself is not a layer, but a tensor. It's the starting tensor you send to the first hidden layer. This tensor must have the same shape as your training data.

Example: if you have 30 images of 50x50 pixels in RGB (3 channels), the shape of your input data is (30,50,50,3). Then your input layer tensor, must have this shape (see details in the "shapes in keras" section).

Each type of layer requires the input with a certain number of dimensions:

  • Dense layers require inputs as (batch_size, input_size)
    • or (batch_size, optional,...,optional, input_size)
  • 2D convolutional layers need inputs as:
    • if using channels_last: (batch_size, imageside1, imageside2, channels)
    • if using channels_first: (batch_size, channels, imageside1, imageside2)
  • 1D convolutions and recurrent layers use (batch_size, sequence_length, features)

Now, the input shape is the only one you must define, because your model cannot know it. Only you know that, based on your training data.

All the other shapes are calculated automatically based on the units and particularities of each layer.

Relation between shapes and units - The output shape

Given the input shape, all other shapes are results of layers calculations.

The "units" of each layer will define the output shape (the shape of the tensor that is produced by the layer and that will be the input of the next layer).

Each type of layer works in a particular way. Dense layers have output shape based on "units", convolutional layers have output shape based on "filters". But it's always based on some layer property. (See the documentation for what each layer outputs)

Let's show what happens with "Dense" layers, which is the type shown in your graph.

A dense layer has an output shape of (batch_size,units). So, yes, units, the property of the layer, also defines the output shape.

  • Hidden layer 1: 4 units, output shape: (batch_size,4).
  • Hidden layer 2: 4 units, output shape: (batch_size,4).
  • Last layer: 1 unit, output shape: (batch_size,1).

Weights

Weights will be entirely automatically calculated based on the input and the output shapes. Again, each type of layer works in a certain way. But the weights will be a matrix capable of transforming the input shape into the output shape by some mathematical operation.

In a dense layer, weights multiply all inputs. It's a matrix with one column per input and one row per unit, but this is often not important for basic works.

In the image, if each arrow had a multiplication number on it, all numbers together would form the weight matrix.

Shapes in Keras

Earlier, I gave an example of 30 images, 50x50 pixels and 3 channels, having an input shape of (30,50,50,3).

Since the input shape is the only one you need to define, Keras will demand it in the first layer.

But in this definition, Keras ignores the first dimension, which is the batch size. Your model should be able to deal with any batch size, so you define only the other dimensions:

input_shape = (50,50,3)
    #regardless of how many images I have, each image has this shape        

Optionally, or when it's required by certain kinds of models, you can pass the shape containing the batch size via batch_input_shape=(30,50,50,3) or batch_shape=(30,50,50,3). This limits your training possibilities to this unique batch size, so it should be used only when really required.

Either way you choose, tensors in the model will have the batch dimension.

So, even if you used input_shape=(50,50,3), when keras sends you messages, or when you print the model summary, it will show (None,50,50,3).

The first dimension is the batch size, it's None because it can vary depending on how many examples you give for training. (If you defined the batch size explicitly, then the number you defined will appear instead of None)

Also, in advanced works, when you actually operate directly on the tensors (inside Lambda layers or in the loss function, for instance), the batch size dimension will be there.

  • So, when defining the input shape, you ignore the batch size: input_shape=(50,50,3)
  • When doing operations directly on tensors, the shape will be again (30,50,50,3)
  • When keras sends you a message, the shape will be (None,50,50,3) or (30,50,50,3), depending on what type of message it sends you.

Dim

And in the end, what is dim?

If your input shape has only one dimension, you don't need to give it as a tuple, you give input_dim as a scalar number.

So, in your model, where your input layer has 3 elements, you can use any of these two:

  • input_shape=(3,) -- The comma is necessary when you have only one dimension
  • input_dim = 3

But when dealing directly with the tensors, often dim will refer to how many dimensions a tensor has. For instance a tensor with shape (25,10909) has 2 dimensions.


Defining your image in Keras

Keras has two ways of doing it, Sequential models, or the functional API Model. I don't like using the sequential model, later you will have to forget it anyway because you will want models with branches.

PS: here I ignored other aspects, such as activation functions.

With the Sequential model:

from keras.models import Sequential  
from keras.layers import *  

model = Sequential()    

#start from the first hidden layer, since the input is not actually a layer   
#but inform the shape of the input, with 3 elements.    
model.add(Dense(units=4,input_shape=(3,))) #hidden layer 1 with input

#further layers:    
model.add(Dense(units=4)) #hidden layer 2
model.add(Dense(units=1)) #output layer   

With the functional API Model:

from keras.models import Model   
from keras.layers import * 

#Start defining the input tensor:
inpTensor = Input((3,))   

#create the layers and pass them the input tensor to get the output tensor:    
hidden1Out = Dense(units=4)(inpTensor)    
hidden2Out = Dense(units=4)(hidden1Out)    
finalOut = Dense(units=1)(hidden2Out)   

#define the model's start and end points    
model = Model(inpTensor,finalOut)

Shapes of the tensors

Remember you ignore batch sizes when defining layers:

  • inpTensor: (None,3)
  • hidden1Out: (None,4)
  • hidden2Out: (None,4)
  • finalOut: (None,1)

Simple PHP form: Attachment to email (code golf)

PEAR::Mail_Mime? Sure, PEAR dependency of (min) 2 files (just mail_mime itself if you edit it to remove the pear dependencies), but it works well. Additionally, most servers have PEAR installed to some extent, and in the best cases they have Pear/Mail and Pear/Mail_Mime. Something that cannot be said for most other libraries offering the same functionality.

You may also consider looking in to PHP's IMAP extension. It's a little more complicated, and requires more setup (not enabled or installed by default), but is must more efficient at compilng and sending messages to an IMAP capable server.

how can I display tooltip or item information on mouse over?

Use the title attribute while alt is important for SEO stuff.

How to append in a json file in Python?

Assuming you have a test.json file with the following content:

{"67790": {"1": {"kwh": 319.4}}}

Then, the code below will load the json file, update the data inside using dict.update() and dump into the test.json file:

import json

a_dict = {'new_key': 'new_value'}

with open('test.json') as f:
    data = json.load(f)

data.update(a_dict)

with open('test.json', 'w') as f:
    json.dump(data, f)

Then, in test.json, you'll have:

{"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}

Hope this is what you wanted.

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

There is not a big choice of elements that might get auto-assigned with a scrollTop value as we scroll a webpage.

So I wrote this little function to iterate through the probable elements and return the one we seek.

var grab=function (){
    var el=$();
        $('body#my_body, html, document').each(function(){
            if ($(this).scrollTop()>0) {
                el= ($(this));
                return false;
            }
        })
    return el;
}
//alert(grab().scrollTop());

In Google chrome it would get us the body, in IE - HTML.

(Note, we don't need to set overflow:auto explicitly on our html or body that way.)

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

One contending technology you've omitted is Server-Sent Events / Event Source. What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet? has a good discussion of all of these. Keep in mind that some of these are easier than others to integrate with on the server side.

How to view query error in PDO PHP

/* Provoke an error -- the BONES table does not exist */

$sth = $dbh->prepare('SELECT skull FROM bones');
$sth->execute();

echo "\nPDOStatement::errorInfo():\n";
$arr = $sth->errorInfo();
print_r($arr);

output

Array
(
    [0] => 42S02
    [1] => -204
    [2] => [IBM][CLI Driver][DB2/LINUX] SQL0204N  "DANIELS.BONES" is an undefined name.  SQLSTATE=42704
)

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

The major difference between the two is that $_SERVER['SERVER_NAME'] is a server controlled variable, while $_SERVER['HTTP_HOST'] is a user-controlled value.

The rule of thumb is to never trust values from the user, so $_SERVER['SERVER_NAME'] is the better choice.

As Gumbo pointed out, Apache will construct SERVER_NAME from user-supplied values if you don't set UseCanonicalName On.

Edit: Having said all that, if the site is using a name-based virtual host, the HTTP Host header is the only way to reach sites that aren't the default site.

How do I draw a circle in iOS Swift?

I find Core Graphics to be pretty simple for Swift 3:

if let cgcontext = UIGraphicsGetCurrentContext() {
    cgcontext.strokeEllipse(in: CGRect(x: center.x-diameter/2, y: center.y-diameter/2, width: diameter, height: diameter))
}

Confused about __str__ on list in Python

Because of the infinite superiority of Python over Java, Python has not one, but two toString operations.

One is __str__, the other is __repr__

__str__ will return a human readable string. __repr__ will return an internal representation.

__repr__ can be invoked on an object by calling repr(obj) or by using backticks `obj`.

When printing lists as well as other container classes, the contained elements will be printed using __repr__.

assign multiple variables to the same value in Javascript

Put the varible in an array and Use a for Loop to assign the same value to multiple variables.

  myArray[moveUP, moveDown, moveLeft];

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

        myArray[i] = true;

    }

Issue pushing new code in Github

This is happen when you try to push initially.Because in your GitHub repo have readMe.md or any other new thing which is not in your local repo. First you have to merge unrelated history of your github repo.To do that

git pull origin master --allow-unrelated-histories

then you can get the other files from repo(readMe.md or any)using this

git pull origin master

After that

git push -u origin master

Now you successfully push your all the changes into Github repo.I'm not expert in git but every time these step work for me.

oracle SQL how to remove time from date

You can use TRUNC on DateTime to remove Time part of the DateTime. So your where clause can be:

AND TRUNC(p1.PA_VALUE) >= TO_DATE('25/10/2012', 'DD/MM/YYYY')

The TRUNCATE (datetime) function returns date with the time portion of the day truncated to the unit specified by the format model.

What does LayoutInflater in Android do?

What inflater does

It takes a xml layout as input (say) and converts it to View object.

Why needed

Let us think a scenario where we need to create a custom listview. Now each row should be custom. But how can we do it. Its not possible to assign a xml layout to a row of listview. So, we create a View object. Thus we can access the elements in it (textview,imageview etc) and also assign the object as row of listview

So, whenever we need to assign view type object somewhere and we have our custom xml design we just convert it to object by inflater and use it.

If hasClass then addClass to parent

You probably want to change the condition to if ($(this).hasClass('active'))

Also, hasClass and addClass take classnames, not selectors.
Therefore, you shouldn't include a ..

Finding a branch point with Git?

If you like terse commands,

git rev-list $(git rev-list --first-parent ^branch_name master | tail -n1)^^! 

Here's an explanation.

The following command gives you the list of all commits in master that occurred after branch_name was created

git rev-list --first-parent ^branch_name master 

Since you only care about the earliest of those commits you want the last line of the output:

git rev-list ^branch_name --first-parent master | tail -n1

The parent of the earliest commit that's not an ancestor of "branch_name" is, by definition, in "branch_name," and is in "master" since it's an ancestor of something in "master." So you've got the earliest commit that's in both branches.

The command

git rev-list commit^^!

is just a way to show the parent commit reference. You could use

git log -1 commit^

or whatever.

PS: I disagree with the argument that ancestor order is irrelevant. It depends on what you want. For example, in this case

_C1___C2_______ master
  \    \_XXXXX_ branch A (the Xs denote arbitrary cross-overs between master and A)
   \_____/ branch B

it makes perfect sense to output C2 as the "branching" commit. This is when the developer branched out from "master." When he branched, branch "B" wasn't even merged in his branch! This is what the solution in this post gives.

If what you want is the last commit C such that all paths from origin to the last commit on branch "A" go through C, then you want to ignore ancestry order. That's purely topological and gives you an idea of since when you have two versions of the code going at the same time. That's when you'd go with merge-base based approaches, and it will return C1 in my example.

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

You should use

 SSLContext.getInstance("TLSv1.2"); 

for specific protocol version.

The second exception occured because default socketFactory used fallback SSLv3 protocol for failures.

You can use NoSSLFactory from main answer here for its suppression How to disable SSLv3 in android for HttpsUrlConnection?

Also you should init SSLContext with all your certificates(client and trusted ones if you need them)

But all of that is useless without using

ProviderInstaller.installIfNeeded(getContext())

Here is more information with proper usage scenario https://developer.android.com/training/articles/security-gms-provider.html

Hope it helps.

Move SQL Server 2008 database files to a new folder location

You forgot to mention the name of your database (is it "my"?).

ALTER DATABASE my SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

ALTER DATABASE my SET OFFLINE;

ALTER DATABASE my MODIFY FILE 
(
   Name = my_Data,
   Filename = 'D:\DATA\my.MDF'
);

ALTER DATABASE my MODIFY FILE 
(
   Name = my_Log, 
   Filename = 'D:\DATA\my_1.LDF'
);

Now here you must manually move the files from their current location to D:\Data\ (and remember to rename them manually if you changed them in the MODIFY FILE command) ... then you can bring the database back online:

ALTER DATABASE my SET ONLINE;

ALTER DATABASE my SET MULTI_USER;

This assumes that the SQL Server service account has sufficient privileges on the D:\Data\ folder. If not you will receive errors at the SET ONLINE command.

Running Facebook application on localhost

Ok I'm not sure what's up with these answers but I'll let you know what worked for me as advised by a senior dev at my work. I'm working in Ruby on Rails and using Facebook's JavaScript code to get access tokens.

Problem: To do authentication, Facebook is taking the url from your address bar and comparing that with what they have on file. They don't allow you to use localhost:3000 for whatever reason. However, you can use a completely made-up domain name like yoursite.dev by running a local server and pointing yoursite.dev to 127.0.0.1:3000 or wherever your localhost was pointing to.

Step 1: Install or update Nginx

$ brew install nginx (install) or $ brew upgrade nginx (update)

Step 2: Open up your nginx config file

/usr/local/etc/nginx/nginx.conf (usually here)

/opt/boxen/config/nginx/nginx.conf(if you use Boxen)

Step 3 Add this bit of code into your http {} block

Replace proxy_pass with wherever you want to point yoursite.dev to. In my case it was replacing localhost:3000 or the equivalent 127.0.0.1:3000

server {
  listen       yoursite.dev:80;
  server_name  yoursite.dev;
  location / {
    proxy_pass http://127.0.0.1:3000;
  }
}

Step 4: Edit your hosts file, in /etc/hosts on Mac to include

127.0.0.1   yoursite.dev

This file directs domains to localhost. Nginx listens in on localhost and redirects if it matches a rule.

Step 5: Every time you use your dev environment going forward, you use the yoursite.dev in the address bar instead of localhost:3000 so Facebook logs you in correctly.

How to do sed like text replace with python?

If you are using Python3 the following module will help you: https://github.com/mahmoudadel2/pysed

wget https://raw.githubusercontent.com/mahmoudadel2/pysed/master/pysed.py

Place the module file into your Python3 modules path, then:

import pysed
pysed.replace(<Old string>, <Replacement String>, <Text File>)
pysed.rmlinematch(<Unwanted string>, <Text File>)
pysed.rmlinenumber(<Unwanted Line Number>, <Text File>)

Dynamic height for DIV

set height: auto; If you want to have minimum height to x then you can write

height:auto;
min-height:30px;
height:auto !important;        /* for IE as it does not support min-height */
height:30px;                   /* for IE as it does not support min-height */

How to create dispatch queue in Swift 3

Update for swift 5

Serial Queue

let serialQueue = DispatchQueue.init(label: "serialQueue")
serialQueue.async {
    // code to execute
}

Concurrent Queue

let concurrentQueue = DispatchQueue.init(label: "concurrentQueue", qos: .background, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil)

concurrentQueue.async {
// code to execute
}

From Apple documentation:

Parameters

label

A string label to attach to the queue to uniquely identify it in debugging tools such as Instruments, sample, stackshots, and crash reports. Because applications, libraries, and frameworks can all create their own dispatch queues, a reverse-DNS naming style (com.example.myqueue) is recommended. This parameter is optional and can be NULL.

qos

The quality-of-service level to associate with the queue. This value determines the priority at which the system schedules tasks for execution. For a list of possible values, see DispatchQoS.QoSClass.

attributes

The attributes to associate with the queue. Include the concurrent attribute to create a dispatch queue that executes tasks concurrently. If you omit that attribute, the dispatch queue executes tasks serially.

autoreleaseFrequency

The frequency with which to autorelease objects created by the blocks that the queue schedules. For a list of possible values, see DispatchQueue.AutoreleaseFrequency.

target

The target queue on which to execute blocks. Specify DISPATCH_TARGET_QUEUE_DEFAULT if you want the system to provide a queue that is appropriate for the current object.

How to run function in AngularJS controller on document ready?

$scope.$on('$ViewData', function(event) {
//Your code.
});

What is the difference between a field and a property?

when you have a class which is "Car". The properties are color,shape..

Where as fields are variables defined within the scope of a class.

Run CSS3 animation only once (at page loading)

If I understand correctly that you want to play the animation on A only once youu have to add

animation-iteration-count: 1

to the style for the a.

Add carriage return to a string

string s2 = s1.Replace(",", ",\r\n");

Select Tag Helper in ASP.NET Core MVC

You can also use IHtmlHelper.GetEnumSelectList.

    // Summary:
    //     Returns a select list for the given TEnum.
    //
    // Type parameters:
    //   TEnum:
    //     Type to generate a select list for.
    //
    // Returns:
    //     An System.Collections.Generic.IEnumerable`1 containing the select list for the
    //     given TEnum.
    //
    // Exceptions:
    //   T:System.ArgumentException:
    //     Thrown if TEnum is not an System.Enum or if it has a System.FlagsAttribute.
    IEnumerable<SelectListItem> GetEnumSelectList<TEnum>() where TEnum : struct;

How to change JDK version for an Eclipse project

If you are using maven build tool then add the below properties to it and doing a maven update will solve the problem

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

How to enumerate a range of numbers starting at 1

Python 3

Official Python documentation: enumerate(iterable, start=0)

You don't need to write your own generator as other answers here suggest. The built-in Python standard library already contains a function that does exactly what you want:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

The built-in function is equivalent to this:

def enumerate(sequence, start=0):
  n = start
  for elem in sequence:
    yield n, elem
    n += 1

Xcode 4 - "Valid signing identity not found" error on provisioning profiles on a new Macintosh install

Make sure your certificate is in the "login" keychain. Highlight the login keychain if you don't see it, search for it. Then drag the cert over the words "login". Close and re-open Xcode, ta-da.

Using Html.ActionLink to call action on different controller

If you grab the MVC Futures assembly (which I would highly recommend) you can then use a generic when creating the ActionLink and a lambda to construct the route:

<%=Html.ActionLink<Product>(c => c.Action( o.Value ), "Details" ) %>

You can get the futures assembly here: http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471

JPA: unidirectional many-to-one and cascading delete

Create a bi-directional relationship, like this:

@Entity
public class Parent implements Serializable {

    @Id
    @GeneratedValue
    private long id;

    @OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE)
    private Set<Child> children;
}

Integer value comparison

well i might be late on this but i would like to share something:

Given the input: System.out.println(isGreaterThanZero(-1));

public static boolean isGreaterThanZero(Integer value) {
    return value == null?false:value.compareTo(0) > 0;
}

Returns false

public static boolean isGreaterThanZero(Integer value) {
    return value == null?false:value.intValue() > 0;
}

Returns true So i think in yourcase 'compareTo' will be more accurate.

Get the number of rows in a HTML table

In the DOM, a tr element is (implicitly or explicitly) a child of tbody, thead, or tfoot, not a child of table (hence the 0 you got). So a general answer is:

var count = $('#gvPerformanceResult > * > tr').length;

This includes the rows of the table but excludes rows of any inner table.

Get week of year in JavaScript like in PHP

If you are already in an Angular project you could use $filter('date').

For example:

var myDate = new Date();
var myWeek = $filter('date')(myDate, 'ww');

How to list branches that contain a given commit?

The answer for git branch -r --contains <commit> works well for normal remote branches, but if the commit is only in the hidden head namespace that GitHub creates for PRs, you'll need a few more steps.

Say, if PR #42 was from deleted branch and that PR thread has the only reference to the commit on the repo, git branch -r doesn't know about PR #42 because refs like refs/pull/42/head aren't listed as a remote branch by default.

In .git/config for the [remote "origin"] section add a new line:

fetch = +refs/pull/*/head:refs/remotes/origin/pr/*

(This gist has more context.)

Then when you git fetch you'll get all the PR branches, and when you run git branch -r --contains <commit> you'll see origin/pr/42 contains the commit.

Why isn't .ico file defined when setting window's icon?

I had the same problem too, but I found a solution.

root.mainloop()

from tkinter import *
    
# must add
root = Tk()
root.title("Calculator")
root.iconbitmap(r"image/icon.ico")
    
root.mainloop()

In the example, what python needed is an icon file, so when you dowload an icon as .png it won't work cause it needs an .ico file. So you need to find converters to convert your icon from png to ico.

Android getText from EditText field

Sample code for How to get text from EditText.

Android Java Syntax

EditText text = (EditText)findViewById(R.id.vnosEmaila);
String value = text.getText().toString();

Kotlin Syntax

val text = findViewById<View>(R.id.vnosEmaila) as EditText
val value = text.text.toString()

How to use and style new AlertDialog from appCompat 22.1 and above

When creating the AlertDialog you can set a theme to use.

Example - Creating the Dialog

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyAlertDialogStyle);
builder.setTitle("AppCompatDialog");
builder.setMessage("Lorem ipsum dolor...");
builder.setPositiveButton("OK", null);
builder.setNegativeButton("Cancel", null);
builder.show();

styles.xml - Custom style

<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <!-- Used for the buttons -->
    <item name="colorAccent">#FFC107</item>
    <!-- Used for the title and text -->
    <item name="android:textColorPrimary">#FFFFFF</item>
    <!-- Used for the background -->
    <item name="android:background">#4CAF50</item>
</style>

Result

styled alertdialog

Edit

In order to change the Appearance of the Title, you can do the following. First add a new style:

<style name="MyTitleTextStyle">
    <item name="android:textColor">#FFEB3B</item>
    <item name="android:textAppearance">@style/TextAppearance.AppCompat.Title</item>
</style>

afterwards simply reference this style in your MyAlertDialogStyle:

<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    ...
    <item name="android:windowTitleStyle">@style/MyTitleTextStyle</item>
</style>

This way you can define a different textColor for the message via android:textColorPrimary and a different for the title via the style.

Measuring text height to be drawn on Canvas ( Android )

You must use Rect.width() and Rect.Height() which returned from getTextBounds() instead. That works for me.

Post-increment and pre-increment within a 'for' loop produce same output

Both i++ and ++i is executed after printf("%d", i) is executed at each time, so there's no difference.

Enable Hibernate logging

I answer to myself. As suggested by Vadzim, I must consider the jboss-logging.xml file and insert these lines:

<logger category="org.hibernate">
     <level name="TRACE"/>
</logger>

Instead of DEBUG level I wrote TRACE. Now don't look only the console but open the server.log file (debug messages aren't sent to the console but you can configure this mode!).

Send and Receive a file in socket programming in Linux with C/C++ (GCC/G++)

Minimal runnable POSIX read + write example

Usage:

  1. get two computers on a LAN.

    For example, this will work if both computers are connected to your home router in most cases, which is how I tested it.

  2. On the server computer:

    1. Find the server local IP with ifconfig, e.g. 192.168.0.10

    2. Run:

      ./server output.tmp 12345
      
  3. On the client computer:

    printf 'ab\ncd\n' > input.tmp
    ./client input.tmp 192.168.0.10 12345
    
  4. Outcome: a file output.tmp is created on the sever computer containing 'ab\ncd\n'!

server.c

/*
Receive a file over a socket.

Saves it to output.tmp by default.

Interface:

    ./executable [<output_file> [<port>]]

Defaults:

- output_file: output.tmp
- port: 12345
*/

#define _XOPEN_SOURCE 700

#include <stdio.h>
#include <stdlib.h>

#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h> /* getprotobyname */
#include <netinet/in.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <unistd.h>

int main(int argc, char **argv) {
    char *file_path = "output.tmp";
    char buffer[BUFSIZ];
    char protoname[] = "tcp";
    int client_sockfd;
    int enable = 1;
    int filefd;
    int i;
    int server_sockfd;
    socklen_t client_len;
    ssize_t read_return;
    struct protoent *protoent;
    struct sockaddr_in client_address, server_address;
    unsigned short server_port = 12345u;

    if (argc > 1) {
        file_path = argv[1];
        if (argc > 2) {
            server_port = strtol(argv[2], NULL, 10);
        }
    }

    /* Create a socket and listen to it.. */
    protoent = getprotobyname(protoname);
    if (protoent == NULL) {
        perror("getprotobyname");
        exit(EXIT_FAILURE);
    }
    server_sockfd = socket(
        AF_INET,
        SOCK_STREAM,
        protoent->p_proto
    );
    if (server_sockfd == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }
    if (setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) < 0) {
        perror("setsockopt(SO_REUSEADDR) failed");
        exit(EXIT_FAILURE);
    }
    server_address.sin_family = AF_INET;
    server_address.sin_addr.s_addr = htonl(INADDR_ANY);
    server_address.sin_port = htons(server_port);
    if (bind(
            server_sockfd,
            (struct sockaddr*)&server_address,
            sizeof(server_address)
        ) == -1
    ) {
        perror("bind");
        exit(EXIT_FAILURE);
    }
    if (listen(server_sockfd, 5) == -1) {
        perror("listen");
        exit(EXIT_FAILURE);
    }
    fprintf(stderr, "listening on port %d\n", server_port);

    while (1) {
        client_len = sizeof(client_address);
        puts("waiting for client");
        client_sockfd = accept(
            server_sockfd,
            (struct sockaddr*)&client_address,
            &client_len
        );
        filefd = open(file_path,
                O_WRONLY | O_CREAT | O_TRUNC,
                S_IRUSR | S_IWUSR);
        if (filefd == -1) {
            perror("open");
            exit(EXIT_FAILURE);
        }
        do {
            read_return = read(client_sockfd, buffer, BUFSIZ);
            if (read_return == -1) {
                perror("read");
                exit(EXIT_FAILURE);
            }
            if (write(filefd, buffer, read_return) == -1) {
                perror("write");
                exit(EXIT_FAILURE);
            }
        } while (read_return > 0);
        close(filefd);
        close(client_sockfd);
    }
    return EXIT_SUCCESS;
}

client.c

/*
Send a file over a socket.

Interface:

    ./executable [<input_path> [<sever_hostname> [<port>]]]

Defaults:

- input_path: input.tmp
- server_hostname: 127.0.0.1
- port: 12345
*/

#define _XOPEN_SOURCE 700

#include <stdio.h>
#include <stdlib.h>

#include <arpa/inet.h>
#include <fcntl.h>
#include <netdb.h> /* getprotobyname */
#include <netinet/in.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <unistd.h>

int main(int argc, char **argv) {
    char protoname[] = "tcp";
    struct protoent *protoent;
    char *file_path = "input.tmp";
    char *server_hostname = "127.0.0.1";
    char *server_reply = NULL;
    char *user_input = NULL;
    char buffer[BUFSIZ];
    in_addr_t in_addr;
    in_addr_t server_addr;
    int filefd;
    int sockfd;
    ssize_t i;
    ssize_t read_return;
    struct hostent *hostent;
    struct sockaddr_in sockaddr_in;
    unsigned short server_port = 12345;

    if (argc > 1) {
        file_path = argv[1];
        if (argc > 2) {
            server_hostname = argv[2];
            if (argc > 3) {
                server_port = strtol(argv[3], NULL, 10);
            }
        }
    }

    filefd = open(file_path, O_RDONLY);
    if (filefd == -1) {
        perror("open");
        exit(EXIT_FAILURE);
    }

    /* Get socket. */
    protoent = getprotobyname(protoname);
    if (protoent == NULL) {
        perror("getprotobyname");
        exit(EXIT_FAILURE);
    }
    sockfd = socket(AF_INET, SOCK_STREAM, protoent->p_proto);
    if (sockfd == -1) {
        perror("socket");
        exit(EXIT_FAILURE);
    }
    /* Prepare sockaddr_in. */
    hostent = gethostbyname(server_hostname);
    if (hostent == NULL) {
        fprintf(stderr, "error: gethostbyname(\"%s\")\n", server_hostname);
        exit(EXIT_FAILURE);
    }
    in_addr = inet_addr(inet_ntoa(*(struct in_addr*)*(hostent->h_addr_list)));
    if (in_addr == (in_addr_t)-1) {
        fprintf(stderr, "error: inet_addr(\"%s\")\n", *(hostent->h_addr_list));
        exit(EXIT_FAILURE);
    }
    sockaddr_in.sin_addr.s_addr = in_addr;
    sockaddr_in.sin_family = AF_INET;
    sockaddr_in.sin_port = htons(server_port);
    /* Do the actual connection. */
    if (connect(sockfd, (struct sockaddr*)&sockaddr_in, sizeof(sockaddr_in)) == -1) {
        perror("connect");
        return EXIT_FAILURE;
    }

    while (1) {
        read_return = read(filefd, buffer, BUFSIZ);
        if (read_return == 0)
            break;
        if (read_return == -1) {
            perror("read");
            exit(EXIT_FAILURE);
        }
        /* TODO use write loop: https://stackoverflow.com/questions/24259640/writing-a-full-buffer-using-write-system-call */
        if (write(sockfd, buffer, read_return) == -1) {
            perror("write");
            exit(EXIT_FAILURE);
        }
    }
    free(user_input);
    free(server_reply);
    close(filefd);
    exit(EXIT_SUCCESS);
}

GitHub upstream.

Further comments

Possible improvements:

  • Currently output.tmp gets overwritten each time a send is done.

    This begs for the creation of a simple protocol that allows to pass a filename so that multiple files can be uploaded, e.g.: filename up to the first newline character, max filename 256 chars, and the rest until socket closure are the contents. Of course, that would require sanitation to avoid a path transversal vulnerability.

    Alternatively, we could make a server that hashes the files to find filenames, and keeps a map from original paths to hashes on disk (on a database).

  • Only one client can connect at a time.

    This is specially harmful if there are slow clients whose connections last for a long time: the slow connection halts everyone down.

    One way to work around that is to fork a process / thread for each accept, start listening again immediately, and use file lock synchronization on the files.

  • Add timeouts, and close clients if they take too long. Or else it would be easy to do a DoS.

    poll or select are some options: How to implement a timeout in read function call?

A simple HTTP wget implementation is shown at: How to make an HTTP get request in C without libcurl?

Tested on Ubuntu 15.10.

Merge up to a specific commit

Run below command into the current branch folder to merge from this <commit-id> to current branch, --no-commit do not make a new commit automatically

git merge --no-commit <commit-id>

git merge --continue can only be run after the merge has resulted in conflicts.

git merge --abort Abort the current conflict resolution process, and try to reconstruct the pre-merge state.

jQuery using append with effects

I was in need of a similar kind of solution, wanted to add data on a wall like facebook, when posted,use prepend() to add the latest post on top, thought might be useful for others..

$("#statusupdate").submit( function () {    
          $.post(
           'ajax.php',
            $(this).serialize(),
            function(data){

                $("#box").prepend($(data).fadeIn('slow'));                  
                $("#status").val('');
            }
          );
           event.preventDefault();   
        });   

the code in ajax.php is

if (isset($_POST))
{

    $feed = $_POST['feed'];
    echo "<p id=\"result\" style=\"width:200px;height:50px;background-color:lightgray;display:none;\">$feed</p>";


}

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

It is because you haven't qualified Cells(1, 1) with a worksheet object, and the same holds true for Cells(10, 2). For the code to work, it should look something like this:

Dim ws As Worksheet

Set ws = Sheets("SheetName")
Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents

Alternately:

With Sheets("SheetName")
    Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

EDIT: The Range object will inherit the worksheet from the Cells objects when the code is run from a standard module or userform. If you are running the code from a worksheet code module, you will need to qualify Range also, like so:

ws.Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents

or

With Sheets("SheetName")
    .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With

What's the best way to join on the same table twice?

SELECT
    T1.ID
    T1.PhoneNumber1,
    T1.PhoneNumber2
    T2A.SomeOtherField AS "SomeOtherField of PhoneNumber1",
    T2B.SomeOtherField AS "SomeOtherField of PhoneNumber2"  
FROM
    Table1 T1
    LEFT JOIN Table2 T2A ON T1.PhoneNumber1 = T2A.PhoneNumber
    LEFT JOIN Table2 T2B ON T1.PhoneNumber2 = T2B.PhoneNumber
WHERE
    T1.ID = 'FOO';

LEFT JOIN or JOIN also return same result. Tested success with PostgreSQL 13.1.1 .

enter image description here

How to import a new font into a project - Angular 5

the answer is already exist above, but I would like to add some thing.. you can specify the following in your @font-face

@font-face {
  font-family: 'Name You Font';
  src: url('assets/font/xxyourfontxxx.eot');
  src: local('Cera Pro Medium'), local('CeraPro-Medium'),
  url('assets/font/xxyourfontxxx.eot?#iefix') format('embedded-opentype'),
  url('assets/font/xxyourfontxxx.woff') format('woff'),
  url('assets/font/xxyourfontxxx.ttf') format('truetype');
  font-weight: 500;
  font-style: normal;
}

So you can just indicate your fontfamily name that you already choosed

NOTE: the font-weight and font-style depend on your .woff .ttf ... files

How to display HTML <FORM> as inline element?

You can accomplish what you want, I think, simply by including the submit button within the paragraph:

     <pre>
     <p>Read this sentence  <input  type='submit' value='or push this button'/></p>
     </pre>   

Numpy array dimensions

It is .shape:

ndarray.shape
Tuple of array dimensions.

Thus:

>>> a.shape
(2, 2)

ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db'

If you are in a MySQL shell, exit it by typing exit, which will return you to the command prompt.

Now start MySQL by using exactly the following command:

sudo mysql -u root -p

If your username is something other than root, replace 'root' in the above command with your username:

sudo mysql -u <your-user-name> -p

It will then ask you the MySQL account/password, and your MySQL won't show any access privilege issue then on.

What primitive data type is time_t?

You can use the function difftime. It returns the difference between two given time_t values, the output value is double (see difftime documentation).

time_t actual_time;
double actual_time_sec;
actual_time = time(0);
actual_time_sec = difftime(actual_time,0); 
printf("%g",actual_time_sec);

Finding height in Binary Search Tree

int height(Node* root) {
        if(root==NULL) return -1;
        return max(height(root->left),height(root->right))+1;
}

Take of maximum height from left and right subtree and add 1 to it.This also handles the base case(height of Tree with 1 node is 0).

Django TemplateDoesNotExist?

I'm embarrassed to admit this, but the problem for me was that a template had been specified as ….hml instead of ….html. Watch out!

AngularJS - Multiple ng-view in single template

I believe you can accomplish it by just having single ng-view. In the main template you can have ng-include sections for sub views, then in the main controller define model properties for each sub template. So that they will bind automatically to ng-include sections. This is same as having multiple ng-view

You can check the example given in ng-include documentation

in the example when you change the template from dropdown list it changes the content. Here assume you have one main ng-view and instead of manually selecting sub content by selecting drop down, you do it as when main view is loaded.

Insert Data Into Temp Table with Query

SQL Server R2 2008 needs the AS clause as follows:

SELECT * 
INTO #temp
FROM (
    SELECT col1, col2
    FROM table1
) AS x

The query failed without the AS x at the end.


EDIT

It's also needed when using SS2016, had to add as t to the end.

 Select * into #result from (SELECT * FROM  #temp where [id] = @id) as t //<-- as t

Checking for a null int value from a Java ResultSet

For convenience, you can create a wrapper class around ResultSet that returns null values when ResultSet ordinarily would not.

public final class ResultSetWrapper {

    private final ResultSet rs;

    public ResultSetWrapper(ResultSet rs) {
        this.rs = rs;
    }

    public ResultSet getResultSet() {
        return rs;
    }

    public Boolean getBoolean(String label) throws SQLException {
        final boolean b = rs.getBoolean(label);
        if (rs.wasNull()) {
            return null;
        }
        return b;
    }

    public Byte getByte(String label) throws SQLException {
        final byte b = rs.getByte(label);
        if (rs.wasNull()) {
            return null;
        }
        return b;
    }

    // ...

}

What does 'public static void' mean in Java?

Public - means that the class (program) is available for use by any other class.

Static - creates a class. Can also be applied to variables and methods,making them class methods/variables instead of just local to a particular instance of the class.

Void - this means that no product is returned when the class completes processing. Compare this with helper classes that provide a return value to the main class,these operate like functions; these do not have void in the declaration.

Why use the 'ref' keyword when passing an object?

Think of variables (e.g. foo) of reference types (e.g. List<T>) as holding object identifiers of the form "Object #24601". Suppose the statement foo = new List<int> {1,5,7,9}; causes foo to hold "Object #24601" (a list with four items). Then calling foo.Length will ask Object #24601 for its length, and it will respond 4, so foo.Length will equal 4.

If foo is passed to a method without using ref, that method might make changes to Object #24601. As a consequence of such changes, foo.Length might no longer equal 4. The method itself, however, will be unable to change foo, which will continue to hold "Object #24601".

Passing foo as a ref parameter will allow the called method to make changes not just to Object #24601, but also to foo itself. The method might create a new Object #8675309 and store a reference to that in foo. If it does so, foo would no longer hold "Object #24601", but instead "Object #8675309".

In practice, reference-type variables don't hold strings of the form "Object #8675309"; they don't even hold anything that can meaningfully converted into a number. Even though each reference-type variable will hold some bit pattern, there is no fixed relationship between the bit patterns stored in such variables and the objects they identify. There is no way code could extract information from an object or a reference to it, and later determine whether another reference identified the same object, unless the code either held or knew of a reference that identified the original object.

Is it a good idea to index datetime field in mysql?

MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.

Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).

Add items in array angular 4

Yes there is a way to do it.

First declare a class.

//anyfile.ts
export class Custom
{
  name: string, 
  empoloyeeID: number
}

Then in your component import the class

import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit {
 name: string;
 empoloyeeID : number;
 empList: Array<Custom> = [];
 constructor() {

 }

 ngOnInit() {
 }
 onEmpCreate(){
   //console.log(this.name,this.empoloyeeID);
   let customObj = new Custom();
   customObj.name = "something";
   customObj.employeeId = 12; 
   this.empList.push(customObj);
   this.name ="";
   this.empoloyeeID = 0; 
 }
}

Another way would be to interfaces read the documentation once - https://www.typescriptlang.org/docs/handbook/interfaces.html

Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

Alternatively, you could use the jQuery 1.2 inArray function, which should work across browsers:

jQuery.inArray( value, array [, fromIndex ] )

TSQL CASE with if comparison in SELECT statement

Should be:

SELECT registrationDate, 
       (SELECT CASE
        WHEN COUNT(*)< 2 THEN 'Ama'
        WHEN COUNT(*)< 5 THEN 'SemiAma' 
        WHEN COUNT(*)< 7 THEN 'Good'  
        WHEN COUNT(*)< 9 THEN 'Better' 
        WHEN COUNT(*)< 12 THEN 'Best'
        ELSE 'Outstanding'
        END as a FROM Articles 
        WHERE Articles.userId = Users.userId) as ranking,
        (SELECT COUNT(*) 
        FROM Articles 
        WHERE userId = Users.userId) as articleNumber,
hobbies, etc...
FROM USERS

Multidimensional Lists in C#

Please show more of your code.

If that last piece of code declares and initializes the list variable outside the loop you're basically reusing the same list object, thus adding everything into one list.

Also show where .Capacity and .Count comes into play, how did you get those values?

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness:

return Stream.of(id, name).allMatch(Objects::isNull);

This remains quite easy to maintain while avoiding the reflection hammer. This will return true for null attributes.

How to compare two NSDates: Which is more recent?

Let's assume two dates:

NSDate *date1;
NSDate *date2;

Then the following comparison will tell which is earlier/later/same:

if ([date1 compare:date2] == NSOrderedDescending) {
    NSLog(@"date1 is later than date2");
} else if ([date1 compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");
} else {
    NSLog(@"dates are the same");
}

Please refer to the NSDate class documentation for more details.

HTML how to clear input using javascript?

For me this is the best way:

<form id="myForm">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br><br>
  <input type="button" onclick="myFunction()" value="Reset form">
</form>

<script>
function myFunction() {
    document.getElementById("myForm").reset();
}
</script>

How to create an email form that can send email using html

Html by itself will not send email. You will need something that connects to a SMTP server to send an email. Hence Outlook pops up with mailto: else your form goes to the server which has a script that sends email.

How to find the index of an element in an array in Java?

This way should work, change "char" to "Character":

public static void main(String[] args){
  Character[] list = {'m', 'e', 'y'};
  System.out.println(Arrays.asList(list).indexOf('e')); // print "1"
}

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

if you don't want to use parser :

int a;
String s;
Scanner scan = new Scanner(System.in);

System.out.println("enter a no");
a = scan.nextInt();
System.out.println("no is =" + a);
scan.nextLine(); // This line you have to add (It consumes the \n character)
System.out.println("enter a string");
s = scan.nextLine();
System.out.println("string is=" + s);

Command to get time in milliseconds

Perl can be used for this, even on exotic platforms like AIX. Example:

#!/usr/bin/perl -w

use strict;
use Time::HiRes qw(gettimeofday);

my ($t_sec, $usec) = gettimeofday ();
my $msec= int ($usec/1000);

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
    localtime ($t_sec);

printf "%04d-%02d-%02d %02d:%02d:%02d %03d\n",
    1900+$year, 1+$mon, $mday, $hour, $min, $sec, $msec;

Export Postgresql table data using pgAdmin

Just right click on a table and select "backup". The popup will show various options, including "Format", select "plain" and you get plain SQL.

pgAdmin is just using pg_dump to create the dump, also when you want plain SQL.

It uses something like this:

pg_dump --user user --password --format=plain --table=tablename --inserts --attribute-inserts etc.

How can I view the source code for a function?

As long as the function is written in pure R not C/C++/Fortran, one may use the following. Otherwise the best way is debugging and using "jump into":

> functionBody(functionName)

iOS Remote Debugging

Note: I have no affiliation with Ghostlab creators Vanamco whatsoever.

It was important to me to be able to debug Chrome-specific problems, so I set out to find something that could help me with that. I ended up happily throwing my money at Ghostlab 3. I can test Chrome and Safari mobile browsers as if I was viewing them on my desktop. It just gives me a LAN address to use for any device I’d like to debug. Each application using that address will appear in the list in Ghostlab.

enter image description here

enter image description here

Highly recommended.

Cannot open include file: 'unistd.h': No such file or directory

If you're using ZLib in your project, then you need to find :

#if 1

in zconf.h and replace(uncomment) it with :

#if HAVE_UNISTD_H /* ...the rest of the line

If it isn't ZLib I guess you should find some alternative way to do this. GL.

Calculate the date yesterday in JavaScript

Try this

var d = new Date();
d.setDate(d.getDate() - 1);

How to set the style -webkit-transform dynamically using JavaScript?

The JavaScript style names are WebkitTransformOrigin and WebkitTransform

element.style.webkitTransform = "rotate(-2deg)";

Check the DOM extension reference for WebKit here.

SQL query, store result of SELECT in local variable

You can create table variables:

DECLARE @result1 TABLE (a INT, b INT, c INT)

INSERT INTO @result1
SELECT a, b, c
FROM table1

SELECT a AS val FROM @result1
UNION
SELECT b AS val FROM @result1
UNION
SELECT c AS val FROM @result1

This should be fine for what you need.

Android Firebase, simply get one child object's data

just fetch specific node data and its working perfect for me

mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {


        for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
            Log.e(TAG, "======="+postSnapshot.child("email").getValue());
            Log.e(TAG, "======="+postSnapshot.child("name").getValue());
        }
    }

    @Override
    public void onCancelled(DatabaseError error) {
        // Failed to read value
        Log.e(TAG, "Failed to read app title value.", error.toException());
    }
});

How can I echo the whole content of a .html file in PHP?

Just use:

<?php
    include("/path/to/file.html");
?>

That will echo it as well. This also has the benefit of executing any PHP in the file.

If you need to do anything with the contents, use file_get_contents(),

For example,

<?php
    $pagecontents = file_get_contents("/path/to/file.html");

    echo str_replace("Banana", "Pineapple", $pagecontents);

?>

This doesn't execute code in that file, so be careful if you expect that to work.

I usually use:

include($_SERVER['DOCUMENT_ROOT']."/path/to/file/as/in/url.html");

as then I can move files without breaking the includes.

event.preventDefault() function not working in IE

return false in your listener should work in all browsers.

$('orderNowForm').addEvent('submit', function () {
    // your code
    return false;
}

What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools?

The other answers here clearly explained what does it mean.I like to explain its use.

You can select an element in the elements tab and switch to console tab in chrome. Just type $0 or $1 or whatever number and press enter and the element will be displayed in the console for your use.

screenshot of chrome dev tools

How to change the remote a branch is tracking?

This is the easiest command:

git push --set-upstream <new-origin> <branch-to-track>

For example, given the command git remote -v produces something like:

origin  ssh://[email protected]/~myself/projectr.git (fetch)
origin  ssh://[email protected]/~myself/projectr.git (push)
team    ssh://[email protected]/vbs/projectr.git (fetch)
team    ssh://[email protected]/vbs/projectr.git (push)

To change to tracking the team instead:

git push --set-upstream team master

How to force ViewPager to re-instantiate its items

Had the same problem. For me it worked to call

viewPage.setAdapter( adapter );

again which caused reinstantiating the pages again.

How to use LINQ to select object with minimum or maximum property value

IF you want to select object with minimum or maximum property value. another way is to use Implementing IComparable.

public struct Money : IComparable<Money>
{
   public Money(decimal value) : this() { Value = value; }
   public decimal Value { get; private set; }
   public int CompareTo(Money other) { return Value.CompareTo(other.Value); }
}

Max Implementation will be.

var amounts = new List<Money> { new Money(20), new Money(10) };
Money maxAmount = amounts.Max();

Min Implementation will be.

var amounts = new List<Money> { new Money(20), new Money(10) };
Money maxAmount = amounts.Min();

In this way, you can compare any object and get the Max and Min while returning the object type.

Hope This will help someone.

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

Microsoft listed the following methods for getting the a View definition: http://technet.microsoft.com/en-us/library/ms175067.aspx


USE AdventureWorks2012;
GO
SELECT definition, uses_ansi_nulls, uses_quoted_identifier, is_schema_bound
FROM sys.sql_modules
WHERE object_id = OBJECT_ID('HumanResources.vEmployee'); 
GO

USE AdventureWorks2012; 
GO
SELECT OBJECT_DEFINITION (OBJECT_ID('HumanResources.vEmployee')) 
AS ObjectDefinition; 
GO

EXEC sp_helptext 'HumanResources.vEmployee';

Dataset - Vehicle make/model/year (free)

How about Freebase? I think they have an API available, too.

http://www.freebase.com/

How to insert a SQLite record with a datetime set to 'now' in Android application?

Works for me perfect:

    values.put(DBHelper.COLUMN_RECEIVEDATE, geo.getReceiveDate().getTime());

Save your date as a long.

How to speed up insertion performance in PostgreSQL

I spent around 6 hours on the same issue today. Inserts go at a 'regular' speed (less than 3sec per 100K) up until to 5MI (out of total 30MI) rows and then the performance sinks drastically (all the way down to 1min per 100K).

I will not list all of the things that did not work and cut straight to the meat.

I dropped a primary key on the target table (which was a GUID) and my 30MI or rows happily flowed to their destination at a constant speed of less than 3sec per 100K.

Escaping backslash in string - javascript

Escape the backslash character.

foo.split('\\')

How do I remove the title bar from my app?

do this in you manifest file:

<application 
    android:icon="@drawable/icon" 
    android:label="@string/app_name" 
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen">

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

docker mounting volumes on host

Let me add my own answer, because I believe the others are missing the point of Docker.

Using VOLUME in the Dockerfile is the Right Way™, because you let Docker know that a certain directory contains permanent data. Docker will create a volume for that data and never delete it, even if you remove all the containers that use it.

It also bypasses the union file system, so that the volume is in fact an actual directory that gets mounted (read-write or readonly) in the right place in all the containers that share it.

Now, in order to access that data from the host, you only need to inspect your container:

# docker inspect myapp
[{
    .
    .
    .
    "Volumes": {
        "/var/www": "/var/lib/docker/vfs/dir/b3ef4bc28fb39034dd7a3aab00e086e6...",
        "/var/cache/nginx": "/var/lib/docker/vfs/dir/62499e6b31cb3f7f59bf00d8a16b48d2...",
        "/var/log/nginx": "/var/lib/docker/vfs/dir/71896ce364ef919592f4e99c6e22ce87..."
    },
    "VolumesRW": {
        "/var/www": false,
        "/var/cache/nginx": true,
        "/var/log/nginx": true
    }
}]

What I usually do is make symlinks in some standard place such as /srv, so that I can easily access the volumes and manage the data they contain (only for the volumes you care about):

ln -s /var/lib/docker/vfs/dir/b3ef4bc28fb39034dd7a3aab00e086e6... /srv/myapp-www
ln -s /var/lib/docker/vfs/dir/71896ce364ef919592f4e99c6e22ce87... /srv/myapp-log

Spring Rest POST Json RequestBody Content type not supported

try to add jackson dependency

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.9.3</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.3</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.3</version>
        <exclusions>
            <exclusion>
                <artifactId>jackson-annotations</artifactId>
                <groupId>com.fasterxml.jackson.core</groupId>
            </exclusion>
        </exclusions>
    </dependency>

How to attach a process in gdb

Try one of these:

gdb -p 12271
gdb /path/to/exe 12271

gdb /path/to/exe
(gdb) attach 12271

How to install easy_install in Python 2.7.1 on Windows 7

for 32-bit Python, the installer is here. after you run the installer, you will have easy_install.exe in your \Python27\Scripts directory

if you are looking for 64-bit installers, this is an excellent resource:

http://www.lfd.uci.edu/~gohlke/pythonlibs/

the author has installers for both Setuptools and Distribute. Either one will give you easy_install.exe

"Data too long for column" - why?

I try to create a table with a field as 200 characters and I've added two rows with early 160 characters and it's OK. Are you sure your rows are less than 200 characters?

Show SqlFiddle

PHP Fatal error: Class 'PDO' not found

This error is caused by PDO not being available to PHP.

If you are getting the error on the command line, or not via the same interface your website uses for PHP, you are potentially invoking a different version of PHP, or utlising a different php.ini configuration file when checking phpinfo().

Ensure PDO is loaded, and the PDO drivers for your database are also loaded.

How do I output the difference between two specific revisions in Subversion?

See svn diff in the manual:

svn diff -r 8979:11390 http://svn.collab.net/repos/svn/trunk/fSupplierModel.php

How to compare two files in Notepad++ v6.6.8

I give the answer because I need to compare 2 files in notepad++ and there is no option available.

So first enable the plugin manager as asked by question here, Then follow this step to compare 2 files which is free in this software.

1.open notepad++, go to

Plugin -> Plugin Manager -> Show Plugin Manager

2.Show the available plugin list, choose Compare and Install

3.Restart Notepad++.

http://www.technicaloverload.com/compare-two-files-using-notepad/

Unable to open project... cannot be opened because the project file cannot be parsed

It sounds like you're going to have to create a new project in Xcode, go into the old directory, and drag all your source files, nibs, and resources into the Xcode files sidebar in the new project. It shouldn't take more than a few minutes, unless you really did a lot of work with custom build settings or targets. Either that, or revert to the last check-in in your source control and manually add any code files which changed between now and then.

Parameterize an SQL IN clause

In SQL Server 2016+ you could use STRING_SPLIT function:

DECLARE @names NVARCHAR(MAX) = 'ruby,rails,scruffy,rubyonrails';

SELECT * 
FROM Tags
WHERE Name IN (SELECT [value] FROM STRING_SPLIT(@names, ','))
ORDER BY [Count] DESC;

or:

DECLARE @names NVARCHAR(MAX) = 'ruby,rails,scruffy,rubyonrails';

SELECT t.*
FROM Tags t
JOIN STRING_SPLIT(@names,',')
  ON t.Name = [value]
ORDER BY [Count] DESC;

LiveDemo

The accepted answer will of course work and it is one of the way to go, but it is anti-pattern.

E. Find rows by list of values

This is replacement for common anti-pattern such as creating a dynamic SQL string in application layer or Transact-SQL, or by using LIKE operator:

SELECT ProductId, Name, Tags
FROM Product
WHERE ',1,2,3,' LIKE '%,' + CAST(ProductId AS VARCHAR(20)) + ',%';

Addendum:

To improve the STRING_SPLIT table function row estimation, it is a good idea to materialize splitted values as temporary table/table variable:

DECLARE @names NVARCHAR(MAX) = 'ruby,rails,scruffy,rubyonrails,sql';

CREATE TABLE #t(val NVARCHAR(120));
INSERT INTO #t(val) SELECT s.[value] FROM STRING_SPLIT(@names, ',') s;

SELECT *
FROM Tags tg
JOIN #t t
  ON t.val = tg.TagName
ORDER BY [Count] DESC;

SEDE - Live Demo

Related: How to Pass a List of Values Into a Stored Procedure


Original question has requirement SQL Server 2008. Because this question is often used as duplicate, I've added this answer as reference.

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

 <textarea style="width:300px; height:150px;" ></textarea>

Hunk #1 FAILED at 1. What's that mean?

Follow the instructions here, it solved my problem.

you have to run the command like as follow; patch -p0 --dry-run < path/to/your/patchFile/yourPatch.patch

How to access the correct `this` inside a callback?

What you should know about this

this (aka "the context") is a special keyword inside each function and its value only depends on how the function was called, not how/when/where it was defined. It is not affected by lexical scopes like other variables (except for arrow functions, see below). Here are some examples:

function foo() {
    console.log(this);
}

// normal function call
foo(); // `this` will refer to `window`

// as object method
var obj = {bar: foo};
obj.bar(); // `this` will refer to `obj`

// as constructor function
new foo(); // `this` will refer to an object that inherits from `foo.prototype`

To learn more about this, have a look at the MDN documentation.


How to refer to the correct this

Use arrow functions

ECMAScript 6 introduced arrow functions, which can be thought of as lambda functions. They don't have their own this binding. Instead, this is looked up in scope just like a normal variable. That means you don't have to call .bind. That's not the only special behavior they have, please refer to the MDN documentation for more information.

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', () => alert(this.data));
}

Don't use this

You actually don't want to access this in particular, but the object it refers to. That's why an easy solution is to simply create a new variable that also refers to that object. The variable can have any name, but common ones are self and that.

function MyConstructor(data, transport) {
    this.data = data;
    var self = this;
    transport.on('data', function() {
        alert(self.data);
    });
}

Since self is a normal variable, it obeys lexical scope rules and is accessible inside the callback. This also has the advantage that you can access the this value of the callback itself.

Explicitly set this of the callback - part 1

It might look like you have no control over the value of this because its value is set automatically, but that is actually not the case.

Every function has the method .bind [docs], which returns a new function with this bound to a value. The function has exactly the same behavior as the one you called .bind on, only that this was set by you. No matter how or when that function is called, this will always refer to the passed value.

function MyConstructor(data, transport) {
    this.data = data;
    var boundFunction = (function() { // parenthesis are not necessary
        alert(this.data);             // but might improve readability
    }).bind(this); // <- here we are calling `.bind()` 
    transport.on('data', boundFunction);
}

In this case, we are binding the callback's this to the value of MyConstructor's this.

Note: When a binding context for jQuery, use jQuery.proxy [docs] instead. The reason to do this is so that you don't need to store the reference to the function when unbinding an event callback. jQuery handles that internally.

Set this of the callback - part 2

Some functions/methods which accept callbacks also accept a value to which the callback's this should refer to. This is basically the same as binding it yourself, but the function/method does it for you. Array#map [docs] is such a method. Its signature is:

array.map(callback[, thisArg])

The first argument is the callback and the second argument is the value this should refer to. Here is a contrived example:

var arr = [1, 2, 3];
var obj = {multiplier: 42};

var new_arr = arr.map(function(v) {
    return v * this.multiplier;
}, obj); // <- here we are passing `obj` as second argument

Note: Whether or not you can pass a value for this is usually mentioned in the documentation of that function/method. For example, jQuery's $.ajax method [docs] describes an option called context:

This object will be made the context of all Ajax-related callbacks.


Common problem: Using object methods as callbacks/event handlers

Another common manifestation of this problem is when an object method is used as callback/event handler. Functions are first-class citizens in JavaScript and the term "method" is just a colloquial term for a function that is a value of an object property. But that function doesn't have a specific link to its "containing" object.

Consider the following example:

function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = function() {
    console.log(this.data);
};

The function this.method is assigned as click event handler, but if the document.body is clicked, the value logged will be undefined, because inside the event handler, this refers to the document.body, not the instance of Foo.
As already mentioned at the beginning, what this refers to depends on how the function is called, not how it is defined.
If the code was like the following, it might be more obvious that the function doesn't have an implicit reference to the object:

function method() {
    console.log(this.data);
}


function Foo() {
    this.data = 42,
    document.body.onclick = this.method;
}

Foo.prototype.method = method;

The solution is the same as mentioned above: If available, use .bind to explicitly bind this to a specific value

document.body.onclick = this.method.bind(this);

or explicitly call the function as a "method" of the object, by using an anonymous function as callback / event handler and assign the object (this) to another variable:

var self = this;
document.body.onclick = function() {
    self.method();
};

or use an arrow function:

document.body.onclick = () => this.method();

decompiling DEX into Java sourcecode

A lot has changed since most of these answers were posted. Now-a-days there a are many easy tools with GUI's, like these:

APK Easy Tool for Windows (GUI tool, friendly)
Bytecode Viewer - APK/Java Reverse Engineering Suite
URET Android Reverser Toolkit

Best place to find them is on the XDA Developers forum.

How to convert an ArrayList containing Integers to primitive int array?

Integer[] arr = (Integer[]) x.toArray(new Integer[x.size()]);

access arr like normal int[].

How to change the DataTable Column Name?

after generating XML you can just Replace your XML <Marks>... content here </Marks> tags with <SubjectMarks>... content here </SubjectMarks>tag. and pass updated XML to your DB.

Edit: I here explain complete process here.

Your XML Generate Like as below.

<NewDataSet>
      <StudentMarks> 
          <StudentID>1</StudentID>
          <CourseID>100</CourseID>
          <SubjectCode>MT400</SubjectCode>
          <Marks>80</Marks>
      </StudentMarks>
      <StudentMarks> 
          <StudentID>1</StudentID>
          <CourseID>100</CourseID>
          <SubjectCode>MT400</SubjectCode>
          <Marks>79</Marks>
      </StudentMarks>
      <StudentMarks> 
          <StudentID>1</StudentID>
          <CourseID>100</CourseID>
          <SubjectCode>MT400</SubjectCode>
          <Marks>88</Marks>
      </StudentMarks>
  </NewDataSet>

Here you can assign XML to string variable like as

string strXML = DataSet.GetXML();

strXML = strXML.Replace ("<Marks>","<SubjectMarks>");
strXML = strXML.Replace ("<Marks/>","<SubjectMarks/>");

and now pass strXML To your DB. Hope it will help for you.

Bootstrap 4 dropdown with search

dropdown with search using bootstrap 4.4.0 version

_x000D_
_x000D_
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

function filterFunction() {
  var input, filter, ul, li, a, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  div
    = document.getElementById("myDropdown");
  a = div.getElementsByTagName("a");
  for (i = 0; i <
    a.length; i++) {
    txtValue = a[i].textContent || a[i].innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      a[i].style.display = "";
    } else {
      a[i].style.display = "none";
    }
  }
}
_x000D_
#myInput {
  box-sizing: border-box;
  background-image: url('searchicon.png');
  background-position: 14px 12px;
  background-repeat: no-repeat;
  font-size: 16px;
  padding: 14px 20px 12px 45px;
  border: none;
  border-bottom: 1px solid #ddd;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f6f6f6;
  min-width: 230px;
  overflow: auto;
  border: 1px solid #ddd;
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}

.dropdown a:hover {
  background-color: #ddd;
}

.show {
  display: block;
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<div class="dropdown">
  <button onclick="myFunction()" class="dropbtn">Dropdown</button>
  <div id="myDropdown" class="dropdown-content">
    <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()">
    <a href="#about">home</a>
    <a href="#base">contact</a>

  </div>
</div>
_x000D_
_x000D_
_x000D_

Make ABC Ordered List Items Have Bold Style

Are you sure you correctly applied the styles, or that there isn't another stylesheet interfering with your lists? I tried this:

<ol type="A">
<li><span class="label">Text</span></li>
<li><span class="label">Text</span></li>
<li><span class="label">Text</span></li>
</ol>

Then in the stylesheet:

ol {font-weight: bold;}
ol li span.label {font-weight:normal;}

And it bolded the A, B, C etc and not the text.

(Tested it in Opera 9.6, FF 3, Safari 3.2 and IE 7)

jQuery Event : Detect changes to the html/text of a div

Following code works for me.

$("body").on('DOMSubtreeModified', "mydiv", function() {
    alert('changed');
});

Hope it will help someone :)

java.net.SocketException: Software caused connection abort: recv failed

The only time I've seen something like this happen is when I have a bad connection, or when somebody is closing the socket that I am using from a different thread context.

How to workaround 'FB is not defined'?

<script>  
    window.fbAsyncInit = function() {    
        FB.init({      
            appId      :'your-app-id',      
            xfbml      :true,      
            version    :'v2.1'
        });
    };
    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if(d.getElementById(id)) {
            return;
        }     
        js = d.createElement(s); 
        js.id = id;     
        js.src ="// connect.facebook.net/en_US /sdk.js";     
        fjs.parentNode.insertBefore(js, fjs);
    }
    (document,'script','facebook-jssdk'));
</script> 

From the documentation: The Facebook SDK for JavaScript doesn't have any standalone files that need to be downloaded or installed, instead you simply need to include a short piece of regular JavaScript in your HTML tha

How to find substring from string?

Use strstr(const char *s , const char *t) and include<string.h>

You can write your own function which behaves same as strstr and you can modify according to your requirement also

char * str_str(const char *s, const char *t)
{
int i, j, k;
for (i = 0; s[i] != '\0'; i++) 
{
for (j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++);
if (k > 0 && t[k] == '\0')
return (&s[i]);
}
return NULL;
}

How to solve privileges issues when restore PostgreSQL Database

Use the postgres (admin) user to dump the schema, recreate it and grant priviledges for use before you do your restore. In one command:

sudo -u postgres psql -c "DROP SCHEMA public CASCADE;
create SCHEMA public;
grant usage on schema public to public;
grant create on schema public to public;" myDBName

Suppress warning messages using mysql from within Terminal, but password written in bash script

I use something like:

mysql --defaults-extra-file=/path/to/config.cnf

or

mysqldump --defaults-extra-file=/path/to/config.cnf 

Where config.cnf contains:

[client]
user = "whatever"
password = "whatever"
host = "whatever"

This allows you to have multiple config files - for different servers/roles/databases. Using ~/.my.cnf will only allow you to have one set of configuration (although it may be a useful set of defaults).

If you're on a Debian based distro, and running as root, you could skip the above and just use /etc/mysql/debian.cnf to get in ... :

mysql --defaults-extra-file=/etc/mysql/debian.cnf

How to decompile an APK or DEX file on Android platform?

An APK is just in zip format. You can unzip it like any other .zip file.

You can decompile .dex files using the dexdump tool, which is provided in the Android SDK.

See https://stackoverflow.com/a/7750547/116938 for more dex info.

JQuery create a form and add elements to it programmatically

function setValToAssessment(id)
{

     $.getJSON("<?= URL.$param->module."/".$param->controller?>/setvalue",{id: id}, function(response)
     {
        var form = $('<form></form>').attr("id",'hiddenForm' ).attr("name", 'hiddenForm'); 
         $.each(response,function(key,value){
            $("<input type='text' value='"+value+"' >")
 .attr("id", key)
 .attr("name", key)
 .appendTo("form");


             });
              $('#hiddenForm').appendTo('body').submit();

        // window.location.href = "<?=URL.$param->module?>/assessment";
    });

}     

ASP.NET strange compilation error

This kind of errors appears "strange" because they are related to the .NET Framework dynamic source code generation and compilation feature, and, in my opinion, the various errors generated are not reported with all the information needed to understand the real root cause. IIS will report only a generic failure like "Configuration Error" or "Compilation Error", the command line of the dynamic compilation (with reference to temporary files created on-the-fly), and an error code.

Since the error is generic, by searching it on Internet (and in answers to this question), you'll find several different solutions that solved the issue for other people, but will not necessarily solve the issue for your specific case.

For the specific error reported in this question "-1073741502", the root cause appears to be a "DLL Initialization Failed" error during the compilation and from the following article it is likely to happen when the system is low on what is called Desktop Heap memory: https://blogs.msdn.microsoft.com/friis/2012/09/19/c-compiler-or-visual-basic-net-compilers-fail-with-error-code-1073741502-when-generating-assemblies-for-your-asp-net-site/ .

The same blog post suggests to change the app pool account to give more "Desktop Heap memory" or to increase it by changing Windows registry. And the solution to change the app pool account is the one accepted for this answer: https://stackoverflow.com/a/6929129/1996150

Since the "dynamic compilation" of ASP.NET pages appears to be not mandatory if all the code is already compiled within Visual Studio, in many cases similar errors can be solved by manually removing the element "<system.codedom>" from web.config file or removing the Microsoft.CodeDom.Providers.DotNetCompilerPlatform NuGet package (see https://stackoverflow.com/a/49903967/1996150).